Skip to main content

flm_core/core/registry/
builder.rs

1//! The feature builder, through which a feature declares what it contributes
2//! to a registry; the collected declarations of one registry build; and the
3//! error type that every check of the build reports.
4//!
5//! [`FeatureBuilder`] is the value a feature receives in
6//! [`FlmFeature::register`](super::FlmFeature::register). Each of its methods
7//! records one typed declaration (an element, a capability, a table, a stage,
8//! a lowering rule, a backend, an output, a workflow, an option type, a
9//! service slot, and so on) in the [`Roster`], the collected declarations of
10//! one registry build, and attributes the declaration to the feature being
11//! registered. The builder checks and resolves nothing while a feature
12//! registers: the registry build does all of that once every feature has
13//! registered (see [`super::build`]).
14//!
15//! Because the checks run afterwards, registration order never matters. A
16//! feature may refer to a capability, a table or a stage that another feature
17//! declares, whether or not that feature has registered yet, and a feature
18//! never needs to be listed after the features it refers to. The only problem
19//! a builder method reports at once is one it can detect on its own: a
20//! [`Finalizer`] calling a method that only the first registration round may
21//! call.
22//!
23//! # The two registration rounds
24//!
25//! [`FlmFeature::register`](super::FlmFeature::register) is the first round,
26//! in which every method of the builder may be called. A feature's
27//! [`Finalizer`] is the second round: it runs after every feature has
28//! registered, once the build has assembled the service slots, and may read
29//! the assembled services and declare entities derived from what other
30//! features contributed. The service slots are complete by then, so in the
31//! second round a feature may not declare a service slot, contribute to one,
32//! require one, or register another finalizer. The builder refuses each of
33//! these with [`BuildError::ContributionAfterAssembly`], and a
34//! [`RoundTwoAction`] says which one was attempted.
35//!
36//! # Attribution of declarations
37//!
38//! No declaration type holds the name of the feature that makes it: the
39//! builder records, on every declaration, the feature it was created for. A
40//! feature therefore never writes its own name, and the same feature type can
41//! be registered under another name without any change to its declarations.
42//!
43//! # Build errors
44//!
45//! [`BuildError`] is the error type of every phase of the registry build. Each
46//! variant identifies the feature at fault wherever one feature is at fault,
47//! and holds the parts of its message as data, not as a finished sentence: a
48//! [`Site`] says where in a declaration a reference was written, and a list
49//! gives the names that would have been valid. A host can therefore format or
50//! translate the message. The `Display` implementation writes the standard
51//! English message.
52//!
53//! See also [`super::entities`] for the declaration values that these methods
54//! take, [features and
55//! packages](crate::guide::concepts_overview#features-and-packages) for the
56//! concepts, and [the builder only
57//! records](crate::guide::extending#the-builder-only-records) in the guide to
58//! extending FLM.
59
60use std::any::{Any, TypeId};
61use std::fmt;
62use std::sync::Arc;
63
64use crate::model::element::ElementSpec;
65use crate::core::lowering::LoweringRule;
66use crate::model::names::{
67    BackendName, CapName, ElementName, FeatureName, Name, OutputName, RuleName, StageName,
68    WorkflowName,
69};
70use crate::model::options::{Bind, OptionDecl, Options, TypeKey};
71use crate::core::registry::entities::{
72    ArgumentRoleDef, BackendDef, CapabilityDef, CollectionDef, Finalizer, LateInit, NativeImplication,
73    OrderingDef, OutputDef, ScriptDef, StyleDef, WorkflowDef,
74};
75use crate::core::registry::feature::FeatureInfo;
76use crate::core::registry::frozen::ElementTypeText;
77use crate::core::registry::order::FeatureChain;
78use crate::core::services::{
79    Arity, Contribution, ServiceError, ServiceRequirement, Services, SlotDecl, SlotTarget,
80};
81use crate::core::stage::{RewriteDecl, RewriteStage, Stage, StageDecl};
82use crate::core::data::table::{Table, TableDef, TableHandle, TableName, TableType};
83use crate::lang::mint::{CallableKind, ElementDef, FallbackDef, OverrideDef, ScopedPackageDef};
84use crate::lang::{LangBuildError, PresPayload};
85
86/// The place in a declaration where a reference to another entity was written.
87///
88/// One declaration may refer to a dozen other entities, so a build error about
89/// a reference must say both which name was wrong and where it was written.
90/// This enum gives the place as data, with the name of the enclosing
91/// declaration in each variant, so that a host can format or translate the
92/// message instead of parsing a sentence. [`BuildError::Undeclared`],
93/// [`BuildError::TableTypeMismatch`] and [`BuildError::CollectionAsCapability`]
94/// carry a site.
95///
96/// `Display` writes the site as the beginning of a sentence that the error
97/// message completes with the entity referred to, for example
98/// ``stage `flm.refs.resolve` provides``.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum Site {
101    /// A capability's `refines`.
102    CapabilityRefines {
103        /// The refining capability.
104        capability: CapName,
105    },
106    /// A member added to a collection; the member is the entity referred
107    /// to.
108    CollectionMember {
109        /// The collection.
110        collection: CapName,
111        /// The member.
112        member: CapName,
113    },
114    /// A stage's `provides`.
115    StageProvides {
116        /// The stage.
117        stage: StageName,
118    },
119    /// A stage's `writes`.
120    StageWrites {
121        /// The stage.
122        stage: StageName,
123    },
124    /// The stage that ordering edges are placed on.
125    OrderingEdges,
126    /// A capability that an ordering edge on a stage refers to.
127    OrderingEdge {
128        /// The stage the edge applies to.
129        stage: StageName,
130    },
131    /// A backend's native set.
132    BackendNative {
133        /// The backend.
134        backend: BackendName,
135    },
136    /// The element a lowering rule lowers.
137    RuleLowers {
138        /// The rule.
139        rule: RuleName,
140    },
141    /// A rule's `produces`.
142    RuleProduces {
143        /// The rule.
144        rule: RuleName,
145    },
146    /// A rule's `requires`.
147    RuleRequires {
148        /// The rule.
149        rule: RuleName,
150    },
151    /// A rule's `reads` or `reads_opt`.
152    RuleReads {
153        /// The rule.
154        rule: RuleName,
155    },
156    /// A backend in a rule's default mark.
157    RuleDefaultMark {
158        /// The rule.
159        rule: RuleName,
160    },
161    /// An output's capability.
162    OutputCapability {
163        /// The output.
164        output: OutputName,
165    },
166    /// An output's table.
167    OutputTable {
168        /// The output.
169        output: OutputName,
170    },
171    /// An output's [`made_from`](super::OutputDef::made_from).
172    OutputMadeFrom {
173        /// The output.
174        output: OutputName,
175    },
176    /// A workflow's `extends`.
177    WorkflowExtends {
178        /// The workflow.
179        workflow: WorkflowName,
180    },
181    /// A workflow's outputs.
182    WorkflowOutputs {
183        /// The workflow.
184        workflow: WorkflowName,
185    },
186    /// A workflow's demands.
187    WorkflowDemands {
188        /// The workflow.
189        workflow: WorkflowName,
190    },
191    /// A workflow's provider preferences.
192    WorkflowPrefers {
193        /// The workflow.
194        workflow: WorkflowName,
195    },
196    /// The backend of one of a workflow's lowering selections.
197    WorkflowLoweringSelection {
198        /// The workflow.
199        workflow: WorkflowName,
200    },
201    /// A rule that one of a workflow's lowering selections prefers.
202    WorkflowLoweringPreference {
203        /// The workflow.
204        workflow: WorkflowName,
205    },
206    /// A backend or an element in a workflow's list of elements accepted as
207    /// unrenderable.
208    WorkflowUnsupported {
209        /// The workflow.
210        workflow: WorkflowName,
211    },
212    /// The element that an aspect is attached to.
213    Attachment {
214        /// The aspect's type name.
215        aspect: &'static str,
216    },
217    /// The element that a native-set implication requires backends to write
218    /// natively (`must_claim`).
219    NativeImplication,
220}
221
222/// Where an argument stands in the declaration of a command: the place that
223/// [`BuildError::UndeclaredArgumentRole`] refers to.
224///
225/// Its [`Display`](fmt::Display) form writes the argument as a message does,
226/// for example `` argument 1 of `\k` `` or
227/// `` the argument `name` of the field `\tag` of `\k` ``.
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct ArgumentPlace {
230    /// The command whose declaration holds the argument, as it is written:
231    /// `\ref`, `\begin{figure}`, or the trigger of a special character
232    /// sequence.
233    pub command: String,
234    /// The name of the [tack-on field](crate::lang::mint::TackOnField) whose
235    /// own argument list holds the argument; `None` for an argument of the
236    /// command itself.
237    pub field: Option<String>,
238    /// The argument's name, or `None` for an argument without one.
239    pub argument: Option<String>,
240    /// The argument's position, counting from zero, in the argument list that
241    /// holds it.
242    pub index: usize,
243}
244
245impl fmt::Display for Site {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        match self {
248            Site::CapabilityRefines { capability } => {
249                write!(f, "capability `{capability}` refines")
250            }
251            Site::CollectionMember { collection, .. } => {
252                write!(f, "a member added to collection `{collection}` is")
253            }
254            Site::StageProvides { stage } => write!(f, "stage `{stage}` provides"),
255            Site::StageWrites { stage } => write!(f, "stage `{stage}` writes"),
256            Site::OrderingEdges => f.write_str("an ordering declaration applies to"),
257            Site::OrderingEdge { stage } => {
258                write!(f, "an ordering declaration of stage `{stage}` refers to")
259            }
260            Site::BackendNative { backend } => {
261                write!(f, "backend `{backend}` declares that it writes natively")
262            }
263            Site::RuleLowers { rule } => write!(f, "rule `{rule}` lowers"),
264            Site::RuleProduces { rule } => write!(f, "rule `{rule}` produces"),
265            Site::RuleRequires { rule } => write!(f, "rule `{rule}` requires"),
266            Site::RuleReads { rule } => write!(f, "rule `{rule}` reads"),
267            Site::RuleDefaultMark { rule } => write!(f, "rule `{rule}` is marked as the default on"),
268            Site::OutputCapability { output } => write!(f, "output `{output}` demands"),
269            Site::OutputTable { output } => write!(f, "output `{output}` keeps its artifacts in"),
270            Site::OutputMadeFrom { output } => write!(f, "output `{output}` is made from"),
271            Site::WorkflowExtends { workflow } => write!(f, "workflow `{workflow}` extends"),
272            Site::WorkflowOutputs { workflow } => write!(f, "workflow `{workflow}` asks for"),
273            Site::WorkflowDemands { workflow } => write!(f, "workflow `{workflow}` demands"),
274            Site::WorkflowPrefers { workflow } => write!(f, "workflow `{workflow}` prefers"),
275            Site::WorkflowLoweringSelection { workflow } => {
276                write!(f, "workflow `{workflow}` selects lowering rules for")
277            }
278            Site::WorkflowLoweringPreference { workflow } => {
279                write!(f, "workflow `{workflow}` prefers")
280            }
281            Site::WorkflowUnsupported { workflow } => {
282                write!(f, "workflow `{workflow}`'s list of elements accepted as unrenderable refers to")
283            }
284            Site::Attachment { aspect } => write!(f, "aspect `{aspect}` is attached to"),
285            Site::NativeImplication => {
286                f.write_str("a rule that requires backends to write an element natively refers to")
287            }
288        }
289    }
290}
291
292impl fmt::Display for ArgumentPlace {
293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294        match &self.argument {
295            Some(name) => write!(f, "the argument `{name}`")?,
296            None => write!(f, "argument {}", self.index + 1)?,
297        }
298        if let Some(field) = &self.field {
299            write!(f, " of the field `\\{field}`")?;
300        }
301        write!(f, " of `{}`", self.command)
302    }
303}
304
305/// The action that a [`Finalizer`] attempted although only the first
306/// registration round may perform it: the detail of a
307/// [`BuildError::ContributionAfterAssembly`].
308///
309/// The service slots are assembled between the two registration rounds, and
310/// there are exactly two rounds, so in the second round nothing may change a
311/// service slot or register another finalizer.
312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
313pub enum RoundTwoAction {
314    /// Declare a service slot.
315    DeclareSlot,
316    /// Contribute to a service slot.
317    Contribute,
318    /// Require that a service slot be filled.
319    RequireSlot,
320    /// Register a finalizer.
321    RegisterFinalizer,
322}
323
324impl fmt::Display for RoundTwoAction {
325    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326        f.write_str(match self {
327            RoundTwoAction::DeclareSlot => "declare a service slot",
328            RoundTwoAction::Contribute => "contribute to a service slot",
329            RoundTwoAction::RequireSlot => "require a service slot",
330            RoundTwoAction::RegisterFinalizer => "register a finalizer",
331        })
332    }
333}
334
335/// An error found while a registry is built, attributed to the feature at
336/// fault wherever one feature is at fault.
337///
338/// Each variant holds the parts of its message as data, not as text; `Display`
339/// writes the standard English message. A build collects every error of the
340/// phase that fails and returns them together in a
341/// [`RegistryBuildError`](super::RegistryBuildError). A feature's
342/// [`register`](super::FlmFeature::register) method or a [`Finalizer`] may also
343/// return a `BuildError` (usually the one a builder method returned) to refuse
344/// the build.
345#[derive(Debug, Clone)]
346pub enum BuildError {
347    /// A feature refused the build, or one of its declarations was refused
348    /// with a message of its own: the feature's
349    /// [`register`](super::FlmFeature::register) method or one of its
350    /// [`Finalizer`]s returned an error, or a workflow the feature registered
351    /// sets an option value of an option type that no feature declares, or of
352    /// one that cannot be set on a render request.
353    Feature {
354        /// The feature.
355        feature: FeatureName,
356        /// What is wrong, as text for a person to read.
357        detail: String,
358    },
359    /// A feature gave a documentation text to an element type
360    /// ([`FeatureBuilder::element_type_text`]) that it does not declare.
361    UndeclaredElementTypeText {
362        /// The feature that gave the text.
363        feature: FeatureName,
364        /// The element type.
365        element: ElementName,
366        /// The features that declare the element type, in name order, with
367        /// [`LANGUAGE_OWNER`](crate::lang::mint::LANGUAGE_OWNER) for a
368        /// structural element type; empty when no feature declares it.
369        declarers: Vec<FeatureName>,
370    },
371    /// Two declarations gave a documentation text to one element type: two
372    /// calls of [`FeatureBuilder::element_type_text`], or one beside the
373    /// text of the language's structural element type or of a presentation
374    /// element of that name.
375    DuplicateElementTypeText {
376        /// The element type.
377        element: ElementName,
378        /// The feature that gave the first text, or
379        /// [`LANGUAGE_OWNER`](crate::lang::mint::LANGUAGE_OWNER) for the
380        /// language.
381        first: FeatureName,
382        /// The feature that gave the second text; the same as `first` when
383        /// one feature gave two texts.
384        second: FeatureName,
385    },
386    /// Two features are registered under one name.
387    DuplicateFeature {
388        /// The name.
389        feature: FeatureName,
390    },
391    /// Two declarations of one name in one namespace. For a peer
392    /// declaration, `first` and `second` are the same feature, which declared
393    /// the name twice with two different signatures.
394    Duplicate {
395        /// The namespace (`capability`, `table`, `stage`, `peer table`, and
396        /// so on).
397        kind: &'static str,
398        /// The name.
399        name: Name,
400        /// The feature that made the first declaration.
401        first: FeatureName,
402        /// The feature that made the second declaration.
403        second: FeatureName,
404    },
405    /// A table and a capability declared on its own have the same name.
406    TableCapabilityClash {
407        /// The name.
408        name: CapName,
409        /// The feature declaring the table.
410        table_owner: FeatureName,
411        /// The feature declaring the capability.
412        capability_owner: FeatureName,
413    },
414    /// A declaration refers to an entity that no feature declares.
415    Undeclared {
416        /// The feature whose declaration holds the reference.
417        feature: FeatureName,
418        /// The namespace of the missing entity (`capability`, `table`,
419        /// `stage`, `element`, and so on).
420        kind: &'static str,
421        /// Where in the declaration the reference is written.
422        site: Site,
423        /// The name referred to.
424        name: Name,
425        /// The names declared in that namespace, in name order.
426        roster: Vec<Name>,
427    },
428    /// An argument has a role ([`ArgDef::role`](crate::lang::mint::ArgDef::role))
429    /// that no feature declares, and that the feature whose declaration holds
430    /// the argument did not declare as a peer
431    /// ([`FeatureBuilder::peer_argument_role`]).
432    UndeclaredArgumentRole {
433        /// The feature whose declaration holds the argument.
434        feature: FeatureName,
435        /// Where the argument stands in the declaration. The place is boxed,
436        /// so that a [`BuildError`] stays small.
437        place: Box<ArgumentPlace>,
438        /// The role.
439        role: Name,
440        /// The argument role names that features declare, in name order.
441        roster: Vec<Name>,
442    },
443    /// A declaration refers to a table with a value type other than the
444    /// table's declared value type.
445    TableTypeMismatch {
446        /// The feature whose declaration holds the reference.
447        feature: FeatureName,
448        /// Where in the declaration the reference is written.
449        site: Site,
450        /// The table.
451        table: CapName,
452        /// The declared value type.
453        declared: &'static str,
454        /// The type the reference expects.
455        referenced: &'static str,
456    },
457    /// A chain of capability refinements leads back to a capability already
458    /// in it.
459    RefinesCycle {
460        /// The capabilities of the cycle, starting at the first in name
461        /// order.
462        cycle: Vec<CapName>,
463    },
464    /// Two refinements of one capability are marked as its default.
465    TwoDefaults {
466        /// The capability they refine.
467        parent: CapName,
468        /// The first refinement marked default.
469        first: CapName,
470        /// The second refinement marked default.
471        second: CapName,
472    },
473    /// A capability is marked as a default refinement but refines nothing.
474    DefaultWithoutParent {
475        /// The capability.
476        name: CapName,
477    },
478    /// A stage whose effect is `Check` declares a write of a table.
479    CheckWrites {
480        /// The stage.
481        stage: StageName,
482        /// The table.
483        table: CapName,
484    },
485    /// A stage declares a write of an external table, which only the caller
486    /// installs.
487    ExternalTableWritten {
488        /// The stage.
489        stage: StageName,
490        /// The table.
491        table: CapName,
492    },
493    /// A stage provides a collection: a collection can be demanded but never
494    /// provided.
495    CollectionAsCapability {
496        /// The stage.
497        stage: StageName,
498        /// Where in the stage's declaration the collection is written.
499        site: Site,
500        /// The collection.
501        collection: CapName,
502    },
503    /// Two lowering rules are marked as the default for one element on one
504    /// backend, or as the general default for one element.
505    TwoDefaultRules {
506        /// The element.
507        element: ElementName,
508        /// The backend, or `None` for the general default.
509        backend: Option<BackendName>,
510        /// The first rule marked default.
511        first: RuleName,
512        /// The second rule marked default.
513        second: RuleName,
514    },
515    /// A chain of workflows, each extending the next, leads back to a
516    /// workflow already in it.
517    ExtendsCycle {
518        /// The workflows of the cycle, starting at the first in name order.
519        cycle: Vec<WorkflowName>,
520    },
521    /// An output's capability is neither its table's capability nor a
522    /// refinement of it.
523    OutputCapabilityMismatch {
524        /// The output.
525        output: OutputName,
526        /// The capability.
527        capability: CapName,
528        /// The table.
529        table: CapName,
530    },
531    /// An output's table is not an artifact set.
532    OutputTableNotArtifactSet {
533        /// The output.
534        output: OutputName,
535        /// The table.
536        table: CapName,
537        /// The table's value type.
538        ty: &'static str,
539    },
540    /// A part of a style or script definition that takes its text from a
541    /// table ([`DefContent::Table`](super::DefContent::Table)) names a table
542    /// that no feature declares, or one that does not hold
543    /// [`DefinitionText`](super::DefinitionText).
544    DefinitionPartTable {
545        /// `style` or `script`.
546        kind: &'static str,
547        /// The definition's identifier.
548        definition: Name,
549        /// The table the part names.
550        table: CapName,
551        /// The value type the table is declared with; `None` when no feature
552        /// declares it.
553        found: Option<&'static str>,
554    },
555    /// An aspect is attached to an element that already carries it.
556    AspectCollision {
557        /// The attaching feature.
558        feature: FeatureName,
559        /// The element.
560        element: ElementName,
561        /// The aspect's type name.
562        aspect: &'static str,
563    },
564    /// A backend's native set lacks an element that a [native-set
565    /// implication](NativeImplication) requires it to hold.
566    NativeSetIncomplete {
567        /// The backend.
568        backend: BackendName,
569        /// The element of the backend's native set that made the implication
570        /// apply, or `None` when the implication applies to every backend.
571        because: Option<ElementName>,
572        /// The element the backend's native set must also hold.
573        must_claim: ElementName,
574    },
575    /// A [peer declaration](super::PeerName) of a presentation element
576    /// resolved to an element whose payload type is not the signature of the
577    /// peer declaration.
578    PeerElementMismatch {
579        /// The feature that made the peer declaration.
580        feature: FeatureName,
581        /// The element.
582        element: ElementName,
583        /// The payload type of the element's own declaration, or `None` when
584        /// the name is that of a source element (an element that can appear
585        /// in a parsed document), which carries no payload.
586        declared: Option<&'static str>,
587        /// The payload type given in the peer declaration.
588        expected: &'static str,
589    },
590    /// A [peer declaration](super::PeerName) of a table resolved to a table
591    /// whose value type is not the signature of the peer declaration.
592    PeerTableMismatch {
593        /// The feature that made the peer declaration.
594        feature: FeatureName,
595        /// The table.
596        table: CapName,
597        /// The value type of the table's own declaration.
598        declared: &'static str,
599        /// The value type given in the peer declaration.
600        expected: &'static str,
601    },
602    /// A problem with a service slot, found when the slots are assembled.
603    Service(ServiceError),
604    /// A [`Finalizer`] attempted an action that only the first registration
605    /// round may perform.
606    ContributionAfterAssembly {
607        /// The feature.
608        feature: FeatureName,
609        /// The action attempted.
610        action: RoundTwoAction,
611    },
612    /// The build of the FLM language from the element declarations found a
613    /// problem, such as two features defining one command.
614    Lang(LangBuildError),
615    /// A [`LateInit`] hook failed.
616    LateInit {
617        /// The feature that registered the hook.
618        feature: FeatureName,
619        /// What failed, as the hook reported it.
620        detail: String,
621    },
622    /// The chains of the feature order, reduced to the features of the
623    /// registry, order a feature before itself, so the features have no final
624    /// order ([`super::order`]). The build reports one cycle.
625    FeatureOrderCycle {
626        /// The features of the cycle, each placed before the next and the
627        /// last before the first, starting from the feature of the cycle that
628        /// comes first in the order the features were added.
629        cycle: Vec<FeatureName>,
630        /// Every chain that orders two consecutive features of the cycle, as
631        /// written and with its origin, in the order of the cycle.
632        chains: Vec<FeatureChain>,
633    },
634}
635
636/// The giver of a documentation text, or a declarer, as a message names it:
637/// `the language` for [`LANGUAGE_OWNER`](crate::lang::mint::LANGUAGE_OWNER),
638/// `feature ‘name’` for a feature.
639fn giver(owner: &FeatureName) -> String {
640    if owner.as_str() == crate::lang::mint::LANGUAGE_OWNER {
641        String::from("the language")
642    } else {
643        format!("feature ‘{owner}’")
644    }
645}
646
647/// The givers `owners` in a list for a message: `a`, `a and b`, `a, b and c`.
648fn givers(owners: &[FeatureName]) -> String {
649    let named: Vec<String> = owners.iter().map(giver).collect();
650    match named.split_last() {
651        Some((last, [])) => last.clone(),
652        Some((last, head)) => format!("{} and {last}", head.join(", ")),
653        None => String::new(),
654    }
655}
656
657fn join<'a>(names: impl IntoIterator<Item = &'a Name>) -> String {
658    names.into_iter().map(|name| name.as_str()).collect::<Vec<_>>().join(", ")
659}
660
661impl fmt::Display for BuildError {
662    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
663        match self {
664            BuildError::Feature { feature, detail } => {
665                write!(f, "feature `{feature}`: {detail}")
666            }
667            BuildError::UndeclaredElementTypeText { feature, element, declarers } => {
668                if declarers.is_empty() {
669                    write!(
670                        f,
671                        "Invalid documentation text for undeclared element type ‘{element}’ \
672                         (given by {})",
673                        giver(feature)
674                    )
675                } else {
676                    write!(
677                        f,
678                        "Invalid documentation text for element type ‘{element}’ from {}: an \
679                         element type’s text must be given by a feature declaring the type \
680                         (declared by {})",
681                        giver(feature),
682                        givers(declarers)
683                    )
684                }
685            }
686            BuildError::DuplicateElementTypeText { element, first, second } => {
687                if first == second {
688                    write!(
689                        f,
690                        "Duplicate documentation text for element type ‘{element}’ (given twice \
691                         by {})",
692                        giver(first)
693                    )
694                } else {
695                    write!(
696                        f,
697                        "Duplicate documentation text for element type ‘{element}’ (given by {} \
698                         and by {})",
699                        giver(first),
700                        giver(second)
701                    )
702                }
703            }
704            BuildError::DuplicateFeature { feature } => {
705                write!(f, "two features are registered under the name `{feature}`")
706            }
707            BuildError::Duplicate { kind, name, first, second } => {
708                write!(f, "{kind} `{name}` is declared twice: first by feature `{first}`, then by feature `{second}`")
709            }
710            BuildError::TableCapabilityClash { name, table_owner, capability_owner } => write!(
711                f,
712                "`{name}` is declared both as a table, by feature `{table_owner}`, and as a \
713                 capability, by feature `{capability_owner}`; a table's name is already a \
714                 capability, so no capability may be declared under it"
715            ),
716            BuildError::Undeclared { feature, kind, site, name, roster } => write!(
717                f,
718                "feature `{feature}`: {site} the {kind} `{name}`, but no feature declares this \
719                 {kind}; declared {kind} names: [{}]",
720                join(roster)
721            ),
722            BuildError::UndeclaredArgumentRole { feature, place, role, roster } => write!(
723                f,
724                "feature `{feature}`: {place} has the argument role `{role}`, which no registered \
725                 feature declares; a feature that sets another feature's argument role must \
726                 declare it with `FeatureBuilder::peer_argument_role`; declared argument role \
727                 names: [{}]",
728                join(roster)
729            ),
730            BuildError::TableTypeMismatch { feature, site, table, declared, referenced } => write!(
731                f,
732                "feature `{feature}`: {site} the table `{table}` as holding `{referenced}`, but \
733                 the table is declared as holding `{declared}`"
734            ),
735            BuildError::RefinesCycle { cycle } => {
736                let mut names: Vec<&str> = cycle.iter().map(|n| n.as_str()).collect();
737                names.push(cycle[0].as_str());
738                write!(f, "capabilities refine each other in a cycle: {}", names.join(" -> "))
739            }
740            BuildError::TwoDefaults { parent, first, second } => write!(
741                f,
742                "capability `{parent}` may have only one default refinement, but `{first}` and \
743                 `{second}` are both marked default"
744            ),
745            BuildError::DefaultWithoutParent { name } => {
746                write!(f, "capability `{name}` is marked as a default refinement but refines no capability")
747            }
748            BuildError::CheckWrites { stage, table } => {
749                write!(f, "check stage `{stage}` declares a write of table `{table}`; a check stage writes no table")
750            }
751            BuildError::ExternalTableWritten { stage, table } => {
752                write!(
753                    f,
754                    "stage `{stage}` declares a write of the external table `{table}`; only the \
755                     caller installs an external table, and no stage may write it"
756                )
757            }
758            BuildError::CollectionAsCapability { stage, site, collection } => write!(
759                f,
760                "{site} the collection `{collection}`; a collection can be demanded but never \
761                 provided, so stage `{stage}` may not provide it"
762            ),
763            BuildError::TwoDefaultRules { element, backend, first, second } => match backend {
764                Some(backend) => write!(
765                    f,
766                    "element `{element}` may have only one default lowering rule on backend \
767                     `{backend}`, but rules `{first}` and `{second}` are both marked default there"
768                ),
769                None => write!(
770                    f,
771                    "element `{element}` may have only one general default lowering rule, but \
772                     rules `{first}` and `{second}` are both marked as the general default"
773                ),
774            },
775            BuildError::ExtendsCycle { cycle } => {
776                let mut names: Vec<&str> = cycle.iter().map(|n| n.as_str()).collect();
777                names.push(cycle[0].as_str());
778                write!(f, "workflows extend each other in a cycle: {}", names.join(" -> "))
779            }
780            BuildError::OutputCapabilityMismatch { output, capability, table } => write!(
781                f,
782                "output `{output}` demands the capability `{capability}`, which is neither the \
783                 capability of its table `{table}` nor a refinement of it"
784            ),
785            BuildError::OutputTableNotArtifactSet { output, table, ty } => write!(
786                f,
787                "the table `{table}` of output `{output}` holds `{ty}`; an output's table must \
788                 hold an artifact set"
789            ),
790            BuildError::DefinitionPartTable { kind, definition, table, found: None } => write!(
791                f,
792                "the table `{table}` that the {kind} definition `{definition}` takes a part from \
793                 must be declared by a feature of the registry"
794            ),
795            BuildError::DefinitionPartTable { kind, definition, table, found: Some(found) } => write!(
796                f,
797                "the table `{table}` that the {kind} definition `{definition}` takes a part from \
798                 must hold `DefinitionText`, not `{found}`"
799            ),
800            BuildError::AspectCollision { feature, element, aspect } => write!(
801                f,
802                "feature `{feature}` attaches aspect `{aspect}` to element `{element}`, which \
803                 already carries that aspect; an element carries each aspect at most once"
804            ),
805            BuildError::NativeSetIncomplete { backend, because, must_claim } => match because {
806                Some(because) => write!(
807                    f,
808                    "backend `{backend}` must write the element `{must_claim}` natively, \
809                     because it writes the element `{because}` natively"
810                ),
811                None => write!(
812                    f,
813                    "backend `{backend}` must write the element `{must_claim}` natively, as \
814                     every backend must"
815                ),
816            },
817            BuildError::PeerElementMismatch { feature, element, declared, expected } => {
818                match declared {
819                    Some(declared) => write!(
820                        f,
821                        "feature `{feature}` refers to the presentation element `{element}` as \
822                         carrying payload `{expected}`, but the element is declared with payload \
823                         `{declared}`"
824                    ),
825                    None => write!(
826                        f,
827                        "feature `{feature}` refers to the presentation element `{element}` as \
828                         carrying payload `{expected}`, but `{element}` is declared as an element \
829                         that a parsed document can contain, which carries no payload"
830                    ),
831                }
832            }
833            BuildError::PeerTableMismatch { feature, table, declared, expected } => write!(
834                f,
835                "feature `{feature}` refers to the table `{table}` as holding `{expected}`, but \
836                 the table is declared as holding `{declared}`"
837            ),
838            BuildError::Service(error) => fmt::Display::fmt(error, f),
839            BuildError::ContributionAfterAssembly { feature, action } => write!(
840                f,
841                "a finalizer of feature `{feature}` may not {action}; only the feature's \
842                 `register` method may"
843            ),
844            BuildError::Lang(error) => fmt::Display::fmt(error, f),
845            BuildError::LateInit { feature, detail } => {
846                write!(f, "the late-initialization hook of feature `{feature}` failed: {detail}")
847            }
848            BuildError::FeatureOrderCycle { cycle, chains } => {
849                let written: Vec<String> =
850                    chains.iter().map(|chain| format!("`{chain}` ({})", chain.origin())).collect();
851                let (subject, verb) = match written.as_slice() {
852                    [one] => (format!("the chain {one}"), "orders"),
853                    [first, last] => (format!("the chains {first} and {last}"), "order"),
854                    [head @ .., last] => (format!("the chains {}, and {last}", head.join(", ")), "order"),
855                    [] => (String::from("the chains"), "order"),
856                };
857                let mut names: Vec<&str> = cycle.iter().map(|name| name.as_str()).collect();
858                if let Some(first) = names.first().copied() {
859                    names.push(first);
860                }
861                write!(
862                    f,
863                    "the feature order must not contain a cycle, but {subject} {verb} the features \
864                     in the cycle `{}`",
865                    names.join(" < ")
866                )
867            }
868        }
869    }
870}
871
872impl std::error::Error for BuildError {}
873
874impl From<ServiceError> for BuildError {
875    fn from(error: ServiceError) -> BuildError {
876        BuildError::Service(error)
877    }
878}
879
880/// One feature's request to attach an aspect implementation to every element
881/// value whose element type has a given name, including the values that other
882/// features declare.
883///
884/// [`FeatureBuilder::attach`] records it; the build's validate phase merges it
885/// into the element values.
886pub struct Attachment {
887    /// The feature that attaches the aspect.
888    pub owner: FeatureName,
889    /// The element type name; every element value of that type gets the
890    /// aspect.
891    pub element: ElementName,
892    /// The type identifier of the aspect's trait-object type.
893    pub aspect_id: TypeId,
894    /// The name of the aspect's trait-object type.
895    pub aspect_name: &'static str,
896    /// The implementation, in the form the element's aspect map stores
897    /// (`AspectMap::insert_erased`).
898    pub imp: Arc<dyn Any + Send + Sync>,
899}
900
901/// A table as the collected declarations ([`Roster`]) hold it: its
902/// declaration, whether it is external and, for the table of trees that a
903/// rewrite stage publishes, the capability that table's capability refines and
904/// whether it is the default refinement.
905pub struct TableRecord {
906    /// The table's declaration.
907    pub def: TableDef,
908    /// Whether the table is external: no stage writes it, and the caller
909    /// installs its value when a run is constructed.
910    pub external: bool,
911    /// The capability that the table's capability refines; set only for the
912    /// table of trees a rewrite stage publishes.
913    pub refines: Option<CapName>,
914    /// Whether the table's capability is the default refinement of
915    /// `refines`.
916    pub default: bool,
917}
918
919/// A registered stage, in either of the two forms a stage takes.
920///
921/// Both forms are scheduled together and share one numbering, but they do
922/// different work: a rewrite stage changes the trees before they are frozen,
923/// and an ordinary stage computes data beside the frozen trees, checks
924/// something, or writes output.
925pub enum StageKind {
926    /// An ordinary stage, which runs after the trees are frozen: it computes
927    /// data, checks something, or performs input and output. See [`Stage`].
928    Pipeline(Arc<dyn Stage>),
929    /// A rewrite stage, which runs before the trees are frozen. See
930    /// [`RewriteStage`].
931    Rewrite(Arc<dyn RewriteStage>),
932}
933
934/// A stage as the collected declarations ([`Roster`]) hold it: the stage, the
935/// feature that registered it, and its declaration, read from the stage once,
936/// at registration, so that the rest of the build and every plan use the same
937/// declaration.
938pub struct StageRecord {
939    /// The feature that registered the stage.
940    pub owner: FeatureName,
941    /// The stage, in its form.
942    pub kind: StageKind,
943    /// The stage's declaration. For a rewrite stage, the builder makes it
944    /// from the rewrite's own declaration, so both forms are scheduled the
945    /// same way.
946    pub decl: StageDecl,
947    /// A rewrite stage's own declaration; `None` for an ordinary stage.
948    pub rewrite: Option<RewriteDecl>,
949}
950
951/// A backend as the collected declarations ([`Roster`]) hold it. The builder
952/// records the backend's three stages as ordinary stages of the same feature;
953/// the three indices here give their positions in the list of stages.
954pub struct BackendRecord {
955    /// The feature that registered the backend.
956    pub owner: FeatureName,
957    /// The backend's name.
958    pub name: BackendName,
959    /// The native set: the elements the emit stage writes directly.
960    pub native: Vec<ElementName>,
961    /// Documentation prose.
962    pub docs: String,
963    /// The position of the lowering stage in [`Roster::stages`].
964    pub lowering: usize,
965    /// The position of the emit stage in [`Roster::stages`].
966    pub emit: usize,
967    /// The position of the final stage in [`Roster::stages`].
968    pub final_stage: usize,
969}
970
971/// A presentation element as the collected declarations ([`Roster`]) hold it:
972/// the element value the builder created for it, and the type of payload its
973/// nodes carry.
974pub struct PresentationRecord {
975    /// The feature that registered the element.
976    pub owner: FeatureName,
977    /// The element value the builder created.
978    pub element: Arc<ElementSpec>,
979    /// The type of the payload the element's nodes carry.
980    pub payload: TypeKey,
981    /// Documentation prose.
982    pub docs: String,
983}
984
985/// A peer declaration of a backend as the collected declarations ([`Roster`])
986/// hold it: the name of a backend that the declaring feature expects another
987/// feature to register. See [`PeerName`](super::PeerName).
988pub struct PeerBackendRecord {
989    /// The declaring feature.
990    pub owner: FeatureName,
991    /// The backend's name.
992    pub name: BackendName,
993    /// Documentation prose: why the feature refers to the backend.
994    pub docs: String,
995}
996
997/// A peer declaration of a presentation element as the collected declarations
998/// ([`Roster`]) hold it: the name of a presentation element that the declaring
999/// feature expects another feature to register, with the payload type its
1000/// nodes are expected to carry as the declaration's signature. See
1001/// [`PeerName`](super::PeerName).
1002pub struct PeerElementRecord {
1003    /// The declaring feature.
1004    pub owner: FeatureName,
1005    /// The element's name.
1006    pub name: ElementName,
1007    /// The payload type of the nodes that the declaring feature's rules build.
1008    pub payload: TypeKey,
1009    /// Documentation prose: why the feature refers to the element.
1010    pub docs: String,
1011}
1012
1013/// A peer declaration of a table as the collected declarations ([`Roster`])
1014/// hold it: the name of a table that the declaring feature expects another
1015/// feature to declare, with the value type the table is expected to hold as
1016/// the declaration's signature. See [`PeerName`](super::PeerName).
1017pub struct PeerTableRecord {
1018    /// The declaring feature.
1019    pub owner: FeatureName,
1020    /// The table's name.
1021    pub name: CapName,
1022    /// The value type as which the declaring feature's rules read the table.
1023    pub value: TableType,
1024    /// Documentation prose: why the feature refers to the table.
1025    pub docs: String,
1026}
1027
1028/// A peer declaration of a scoped package as the collected declarations
1029/// ([`Roster`]) hold it: the name of a [scoped package](ScopedPackageDef) that
1030/// the declaring feature expects another feature to declare. See
1031/// [`PeerName`](super::PeerName).
1032pub struct PeerScopedPackageRecord {
1033    /// The declaring feature.
1034    pub owner: FeatureName,
1035    /// The package's name.
1036    pub name: Name,
1037    /// Documentation prose: why the feature's environment bodies or arguments
1038    /// refer to the package.
1039    pub docs: String,
1040}
1041
1042/// A peer declaration of an argument role as the collected declarations
1043/// ([`Roster`]) hold it: the name of an [argument role](ArgumentRoleDef) that
1044/// the declaring feature sets on arguments of its own declarations and
1045/// expects another feature to declare. See [`PeerName`](super::PeerName).
1046pub struct PeerArgumentRoleRecord {
1047    /// The declaring feature.
1048    pub owner: FeatureName,
1049    /// The role's name.
1050    pub name: Name,
1051}
1052
1053/// A peer declaration of an element value as the collected declarations
1054/// ([`Roster`]) hold it: one more value of an element type that the declaring
1055/// feature expects another feature to declare. The element declaration itself
1056/// is held among [`Roster::elements`], at `position`, until the build resolves
1057/// it. See [`PeerName`](super::PeerName).
1058pub struct PeerElementValueRecord {
1059    /// The declaring feature.
1060    pub owner: FeatureName,
1061    /// The element type's name, which is the name of the declaration's
1062    /// element value.
1063    pub element: ElementName,
1064    /// The callable names (commands) the declaration defines.
1065    pub names: Vec<Name>,
1066    /// The position of the element declaration in [`Roster::elements`], valid
1067    /// until the build resolves the declaration.
1068    pub position: usize,
1069    /// Whether the build found a feature that declares the element type;
1070    /// `false` until the build resolves the declaration.
1071    pub resolved: bool,
1072}
1073
1074/// Bytes that a feature gave as an input of the registry digest, with
1075/// [`FeatureBuilder::digest_input`].
1076pub struct DigestInput {
1077    /// The feature that gave the bytes.
1078    pub owner: FeatureName,
1079    /// The bytes.
1080    pub bytes: Vec<u8>,
1081}
1082
1083/// The collected declarations of one registry build: every declaration every
1084/// feature made, in registration order, each attributed to the feature that
1085/// made it.
1086///
1087/// [`FeatureBuilder`] fills it.
1088/// [`RegistryBuilder::build`](super::RegistryBuilder::build) checks it and
1089/// numbers its entries into the frozen registry, after which it no longer
1090/// exists; the registry keeps its element declarations, scoped packages,
1091/// fallbacks and overrides
1092/// ([`FlmRegistry::declarations`](super::FlmRegistry::declarations)). Only
1093/// the registry build creates and reads a `Roster`; the type is public so
1094/// that its contents are documented.
1095#[derive(Default)]
1096pub struct Roster {
1097    /// The features, in registration order.
1098    pub features: Vec<FeatureInfo>,
1099    /// The element declarations, including the peer element values until the
1100    /// build drops the unresolved ones.
1101    pub elements: Vec<ElementDef>,
1102    /// The aspect attachments.
1103    pub attachments: Vec<Attachment>,
1104    /// The fallback declarations.
1105    pub fallbacks: Vec<FallbackDef>,
1106    /// The scoped packages.
1107    pub scoped_packages: Vec<ScopedPackageDef>,
1108    /// The declarations that a feature's definition of a callable name
1109    /// replaces another feature's ([`FeatureBuilder::override_callable`]).
1110    pub overrides: Vec<OverrideDef>,
1111    /// The capabilities declared on their own, each with the declaring
1112    /// feature.
1113    pub capabilities: Vec<(FeatureName, CapabilityDef)>,
1114    /// The collections, each with the declaring feature.
1115    pub collections: Vec<(FeatureName, CollectionDef)>,
1116    /// The argument roles, each with the declaring feature.
1117    pub argument_roles: Vec<(FeatureName, ArgumentRoleDef)>,
1118    /// The documentation texts that features gave to element types
1119    /// ([`FeatureBuilder::element_type_text`]), in declaration order. The
1120    /// build checks them and adds the texts of the language's structural
1121    /// element types and of the presentation elements.
1122    pub element_type_texts: Vec<ElementTypeText>,
1123    /// The collection members, as (contributing feature, collection,
1124    /// member).
1125    pub members: Vec<(FeatureName, CapName, CapName)>,
1126    /// The tables.
1127    pub tables: Vec<TableRecord>,
1128    /// The stages of both forms.
1129    pub stages: Vec<StageRecord>,
1130    /// The ordering edges, each with the feature that placed them.
1131    pub orderings: Vec<(FeatureName, OrderingDef)>,
1132    /// The lowering rules, each with the registering feature.
1133    pub rules: Vec<(FeatureName, LoweringRule)>,
1134    /// The presentation elements.
1135    pub presentation: Vec<PresentationRecord>,
1136    /// The backends.
1137    pub backends: Vec<BackendRecord>,
1138    /// The outputs, each with the registering feature.
1139    pub outputs: Vec<(FeatureName, OutputDef)>,
1140    /// The workflows, each with the registering feature.
1141    pub workflows: Vec<(FeatureName, WorkflowDef)>,
1142    /// The fields registered for workflows by name, each with the
1143    /// registering feature, in registration order; see
1144    /// [`FeatureBuilder::workflow_fields`].
1145    pub workflow_fields: Vec<(FeatureName, WorkflowDef)>,
1146    /// The option type declarations.
1147    pub options: Vec<OptionDecl>,
1148    /// The service slot declarations.
1149    pub slots: Vec<SlotDecl>,
1150    /// The contributions to service slots.
1151    pub contributions: Vec<Contribution>,
1152    /// The requirements that a service slot be filled.
1153    pub requirements: Vec<ServiceRequirement>,
1154    /// The finalizers, each with the registering feature.
1155    pub finalizers: Vec<(FeatureName, Arc<dyn Finalizer>)>,
1156    /// The late-initialization hooks, each with the registering feature.
1157    pub late_inits: Vec<(FeatureName, Arc<dyn LateInit>)>,
1158    /// The style definitions, each with the registering feature.
1159    pub styles: Vec<(FeatureName, StyleDef)>,
1160    /// The script definitions, each with the registering feature.
1161    pub scripts: Vec<(FeatureName, ScriptDef)>,
1162    /// The native-set implications, each with the declaring feature.
1163    pub native_implications: Vec<(FeatureName, NativeImplication)>,
1164    /// The peer declarations of backends.
1165    pub peer_backends: Vec<PeerBackendRecord>,
1166    /// The peer declarations of presentation elements.
1167    pub peer_elements: Vec<PeerElementRecord>,
1168    /// The peer declarations of tables.
1169    pub peer_tables: Vec<PeerTableRecord>,
1170    /// The peer declarations of scoped packages.
1171    pub peer_scoped_packages: Vec<PeerScopedPackageRecord>,
1172    /// The peer declarations of element values; each element declaration is
1173    /// also held in [`elements`](Roster::elements) until the build drops the
1174    /// unresolved ones.
1175    pub peer_element_values: Vec<PeerElementValueRecord>,
1176    /// The peer declarations of argument roles.
1177    pub peer_argument_roles: Vec<PeerArgumentRoleRecord>,
1178    /// The bytes features gave as inputs of the registry digest.
1179    pub digest_inputs: Vec<DigestInput>,
1180    /// The errors that features' `register` methods and finalizers returned
1181    /// during the current registration round; the build takes them out at
1182    /// the end of each round.
1183    pub errors: Vec<BuildError>,
1184}
1185
1186/// Which of the build's two registration rounds a feature builder serves.
1187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1188enum Round {
1189    One,
1190    Two,
1191}
1192
1193// Recording everything and checking it afterwards is what makes registration
1194// order irrelevant: a feature may name what a later feature declares, and it
1195// declares no dependencies, since its declarations already say what it needs.
1196/// The feature builder: the value through which a feature declares what it
1197/// contributes to a registry. Each method records one declaration in the
1198/// build's [`Roster`] and attributes it to the feature this builder was created
1199/// for.
1200///
1201/// The registry build creates one builder per feature and round. It hands one
1202/// to the feature's [`FlmFeature::register`](super::FlmFeature::register)
1203/// method, in the first registration round, where every method may be called;
1204/// and one to each of the feature's [`Finalizer`]s, in the second round, where
1205/// the methods that declare, fill or require service slots and the method that
1206/// registers a finalizer return [`BuildError::ContributionAfterAssembly`]. Only
1207/// in the second round does [`services`](FeatureBuilder::services) return the
1208/// assembled services.
1209///
1210/// The methods are grouped by what they declare: the language
1211/// ([`element`](FeatureBuilder::element),
1212/// [`attach`](FeatureBuilder::attach), [`fallback`](FeatureBuilder::fallback),
1213/// [`scoped_package`](FeatureBuilder::scoped_package),
1214/// [`override_callable`](FeatureBuilder::override_callable),
1215/// [`argument_role`](FeatureBuilder::argument_role),
1216/// [`element_type_text`](FeatureBuilder::element_type_text)); capabilities and
1217/// tables ([`capability`](FeatureBuilder::capability),
1218/// [`collection`](FeatureBuilder::collection),
1219/// [`collection_member`](FeatureBuilder::collection_member),
1220/// [`table`](FeatureBuilder::table),
1221/// [`external_table`](FeatureBuilder::external_table)); stages
1222/// ([`stage`](FeatureBuilder::stage),
1223/// [`rewrite_stage`](FeatureBuilder::rewrite_stage),
1224/// [`ordering`](FeatureBuilder::ordering)); lowering and output
1225/// ([`lowering_rule`](FeatureBuilder::lowering_rule),
1226/// [`presentation_element`](FeatureBuilder::presentation_element),
1227/// [`backend`](FeatureBuilder::backend),
1228/// [`native_implication`](FeatureBuilder::native_implication),
1229/// [`output`](FeatureBuilder::output), [`workflow`](FeatureBuilder::workflow),
1230/// [`workflow_fields`](FeatureBuilder::workflow_fields)); peer declarations of entities other
1231/// features own ([`peer_backend`](FeatureBuilder::peer_backend),
1232/// [`peer_element`](FeatureBuilder::peer_element),
1233/// [`peer_table`](FeatureBuilder::peer_table),
1234/// [`peer_slot`](FeatureBuilder::peer_slot),
1235/// [`peer_scoped_package`](FeatureBuilder::peer_scoped_package),
1236/// [`peer_element_value`](FeatureBuilder::peer_element_value),
1237/// [`peer_argument_role`](FeatureBuilder::peer_argument_role)); options and
1238/// services ([`options`](FeatureBuilder::options),
1239/// [`service_slot`](FeatureBuilder::service_slot),
1240/// [`contribute`](FeatureBuilder::contribute),
1241/// [`contribute_first`](FeatureBuilder::contribute_first),
1242/// [`require_service`](FeatureBuilder::require_service)); and build hooks and
1243/// records ([`finalizer`](FeatureBuilder::finalizer),
1244/// [`late_init`](FeatureBuilder::late_init),
1245/// [`style_def`](FeatureBuilder::style_def),
1246/// [`script_def`](FeatureBuilder::script_def),
1247/// [`digest_input`](FeatureBuilder::digest_input)). Several of these methods
1248/// have a variant that takes the target by name instead of by type, or that
1249/// adds documentation prose: [`table_named`](FeatureBuilder::table_named),
1250/// [`external_table_named`](FeatureBuilder::external_table_named),
1251/// [`options_with_docs`](FeatureBuilder::options_with_docs),
1252/// [`contribute_to`](FeatureBuilder::contribute_to),
1253/// [`contribute_first_to`](FeatureBuilder::contribute_first_to) and
1254/// [`require_service_named`](FeatureBuilder::require_service_named). Two
1255/// methods read the builder instead of recording a declaration:
1256/// [`feature`](FeatureBuilder::feature) and
1257/// [`services`](FeatureBuilder::services).
1258///
1259/// Every method that records a declaration returns a `Result`, so that a feature's `register` method can
1260/// end each call with `?`, and so that a method can start reporting a problem
1261/// without a change to its callers. Most methods always return `Ok`; the
1262/// others say under `# Errors` when they fail. Problems with the declarations
1263/// themselves are reported when the registry is built.
1264///
1265/// # Examples
1266///
1267/// ```
1268/// use flm_core::core::registry::{BuildError, CapabilityDef, FeatureBuilder};
1269///
1270/// fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
1271///     b.capability(CapabilityDef::new("counting.done").docs("Counting has run."))?;
1272///     assert_eq!(b.feature(), "counting");
1273///     Ok(())
1274/// }
1275/// ```
1276pub struct FeatureBuilder<'a> {
1277    roster: &'a mut Roster,
1278    feature: FeatureName,
1279    round: Round,
1280    services: Option<&'a Services>,
1281}
1282
1283impl<'a> FeatureBuilder<'a> {
1284    /// A builder for the first registration round of `feature`, with no
1285    /// services to read.
1286    pub(crate) fn round_one(roster: &'a mut Roster, feature: FeatureName) -> FeatureBuilder<'a> {
1287        FeatureBuilder { roster, feature, round: Round::One, services: None }
1288    }
1289
1290    /// A builder for the second registration round of `feature`, able to read
1291    /// the assembled `services`.
1292    pub(crate) fn round_two(
1293        roster: &'a mut Roster,
1294        feature: FeatureName,
1295        services: &'a Services,
1296    ) -> FeatureBuilder<'a> {
1297        FeatureBuilder { roster, feature, round: Round::Two, services: Some(services) }
1298    }
1299
1300    /// The name of the feature this builder records for: every declaration made
1301    /// through this builder is attributed to it.
1302    ///
1303    /// A feature reads it to compose the names of its own entities, so that the
1304    /// name the feature was registered under is the one that appears in the names
1305    /// of its entities (`flm.<feature>.<...>`).
1306    pub fn feature(&self) -> &FeatureName {
1307        &self.feature
1308    }
1309
1310    /// The assembled services, or `None` in the first registration round.
1311    ///
1312    /// The build assembles the service slots between the two rounds, so only a
1313    /// [`Finalizer`] can read them. A feature that needs a service to decide what
1314    /// to declare registers a finalizer and makes those declarations there.
1315    pub fn services(&self) -> Option<&'a Services> {
1316        self.services
1317    }
1318
1319    fn round_one_only(&self, action: RoundTwoAction) -> Result<(), BuildError> {
1320        if self.round == Round::Two {
1321            return Err(BuildError::ContributionAfterAssembly {
1322                feature: self.feature.clone(),
1323                action,
1324            });
1325        }
1326        Ok(())
1327    }
1328
1329    // --- the language ---------------------------------------------------------------
1330
1331    /// Declares an element: an element value, the callable names (commands) that
1332    /// produce it, and the syntax of those commands. See [`ElementDef`] for how a
1333    /// declaration is written.
1334    ///
1335    /// The declaration is attributed to this feature, regardless of the value
1336    /// of `def.owner`.
1337    ///
1338    /// # Errors
1339    ///
1340    /// Never fails. A name that clashes with another feature's, or another problem
1341    /// with the declaration, is reported when the registry is built.
1342    pub fn element(&mut self, mut def: ElementDef) -> Result<(), BuildError> {
1343        def.owner = self.feature.clone();
1344        self.roster.elements.push(def);
1345        Ok(())
1346    }
1347
1348    /// Declares one more value of an element type that another feature owns,
1349    /// with the commands that produce it: a [peer declaration](super::PeerName) of
1350    /// the element type, which carries the element declaration that
1351    /// [`element`](Self::element) takes.
1352    ///
1353    /// The declaration lets this feature add a value of the type without
1354    /// depending on the feature that owns the type. That feature's lowering rules,
1355    /// stages and aspects serve every value of the type, so the value is
1356    /// meaningful only when that feature is registered. A feature **declares the
1357    /// element type** when any of its declarations other than a peer element
1358    /// value creates an element of that name: an [`element`](Self::element)
1359    /// declaration (a value of its own, or the type alone with no callable name,
1360    /// [`SyntaxDef::Synthesized`](crate::lang::mint::SyntaxDef::Synthesized)), an
1361    /// element of a [scoped package](Self::scoped_package), a
1362    /// [fallback](Self::fallback), a [presentation
1363    /// element](Self::presentation_element), or a field that an argument attaches;
1364    /// the language's structural elements count too.
1365    ///
1366    /// When the registry is built, the declaration is resolved against the element
1367    /// types that the other declarations of the registry create.
1368    ///
1369    /// - If a feature declares the element type, this declaration is kept,
1370    ///   attributed to this feature, exactly as [`element`](Self::element) would
1371    ///   keep it.
1372    /// - If no feature declares it, the build still succeeds, the declaration is
1373    ///   dropped (its commands are then unknown commands, like any command no
1374    ///   feature defines), and one Note ([`UnresolvedPeer`](super::UnresolvedPeer))
1375    ///   joins the registry's [build
1376    ///   diagnostics](super::FlmRegistry::build_diagnostics), one per feature and
1377    ///   element type, however many values this feature declared for it. Without
1378    ///   this rule, a value that no lowering rule lowers would make every rendering
1379    ///   plan of the registry fail.
1380    ///
1381    /// Every such declaration, resolved or not, is listed on the finished
1382    /// registry
1383    /// ([`FlmRegistry::peer_element_values`](super::FlmRegistry::peer_element_values)).
1384    /// See [`PeerName`](super::PeerName) for the other kinds of peer declaration.
1385    ///
1386    /// # Errors
1387    ///
1388    /// Never fails. An unresolved declaration is reported as a Note when the
1389    /// registry is built, and a kept one is checked then like any element
1390    /// declaration.
1391    pub fn peer_element_value(&mut self, mut def: ElementDef) -> Result<(), BuildError> {
1392        def.owner = self.feature.clone();
1393        self.roster.peer_element_values.push(PeerElementValueRecord {
1394            owner: self.feature.clone(),
1395            element: def.element.name.clone(),
1396            names: def.names.clone(),
1397            position: self.roster.elements.len(),
1398            resolved: false,
1399        });
1400        self.roster.elements.push(def);
1401        Ok(())
1402    }
1403
1404    /// Gives the element type `name` its documentation text: what the nodes
1405    /// of that type mean, whatever their element value.
1406    ///
1407    /// An element type is the name its element values share, and each value
1408    /// carries a text of its own ([`ElementSpec::docs`]); this text is the
1409    /// type's, written once for all its values, not a copy of one value's
1410    /// text. It is FLM, written as every documentation text is
1411    /// ([`ElementDef::docs`](crate::lang::mint::ElementDef::docs)).
1412    ///
1413    /// This feature must declare the element type, in the sense that
1414    /// [`peer_element_value`](Self::peer_element_value) defines: one of its
1415    /// declarations other than a peer element value creates an element of
1416    /// that name. A registry holds at most one text per element type, so of
1417    /// several features that declare one type, one gives its text. The
1418    /// language gives the texts of its [structural
1419    /// elements](crate::lang::structural), and a [presentation
1420    /// element](Self::presentation_element) has the text it is declared with.
1421    ///
1422    /// The finished registry gives the text by the type's name, with the
1423    /// feature that gave it
1424    /// ([`FlmRegistry::element_type_text`](super::FlmRegistry::element_type_text)).
1425    ///
1426    /// # Errors
1427    ///
1428    /// Never fails. When the registry is built, a text for an element type
1429    /// this feature does not declare is reported as
1430    /// [`BuildError::UndeclaredElementTypeText`], and a second text for one
1431    /// element type as [`BuildError::DuplicateElementTypeText`].
1432    ///
1433    /// # Examples
1434    ///
1435    /// ```
1436    /// use std::sync::Arc;
1437    /// use flm_core::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature, build_registry};
1438    /// use flm_core::lang::mint::{ElementDef, SyntaxDef};
1439    /// use flm_core::model::element::ElementSpec;
1440    ///
1441    /// struct Notes;
1442    /// impl FlmFeature for Notes {
1443    ///     fn info(&self) -> FeatureInfo { FeatureInfo::new("notes", "Notes") }
1444    ///     fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
1445    ///         let note = Arc::new(ElementSpec::new("notes.note"));
1446    ///         b.element(ElementDef::new("notes", ["note"], SyntaxDef::Macro { args: Vec::new() }, note)
1447    ///             .docs("Starts a note."))?;
1448    ///         b.element_type_text("notes.note", "A note, set apart from the text around it.")
1449    ///     }
1450    /// }
1451    ///
1452    /// let registry = build_registry([Arc::new(Notes) as Arc<dyn FlmFeature>])?;
1453    /// let text = registry.element_type_text("notes.note").expect("given above");
1454    /// assert_eq!(text.owner, "notes");
1455    /// # Ok::<(), flm_core::core::registry::RegistryBuildError>(())
1456    /// ```
1457    pub fn element_type_text(
1458        &mut self,
1459        name: impl Into<ElementName>,
1460        docs: impl Into<String>,
1461    ) -> Result<(), BuildError> {
1462        self.roster.element_type_texts.push(ElementTypeText {
1463            element: name.into(),
1464            docs: crate::kept_docs(docs),
1465            owner: self.feature.clone(),
1466        });
1467        Ok(())
1468    }
1469
1470    /// Attaches the aspect implementation `imp` to every element value whose
1471    /// element type is called `element`, including other features' elements and
1472    /// the language's structural elements.
1473    ///
1474    /// An aspect is a piece of behavior attached to an element when the feature
1475    /// registers it and read back through a trait object (see [elements and
1476    /// aspects](crate::guide::concepts_overview#elements-and-aspects)). This method
1477    /// gives behavior to elements a feature does not own: for example, a
1478    /// cross-referencing feature makes headings referenceable without the headings
1479    /// feature depending on it. Give the aspect as its **trait-object type**, as in
1480    /// `b.attach::<dyn Referenceable>("flm.heading", imp)`. A concrete type fails
1481    /// to compile, because an aspect is looked up by the trait it is requested
1482    /// as.
1483    ///
1484    /// # Errors
1485    ///
1486    /// Never fails. When the registry is built, an element type that no feature
1487    /// declares is reported as [`BuildError::Undeclared`], and an aspect that an
1488    /// element already carries as [`BuildError::AspectCollision`].
1489    pub fn attach<A: ?Sized + Any + Send + Sync>(
1490        &mut self,
1491        element: impl Into<ElementName>,
1492        imp: Arc<A>,
1493    ) -> Result<(), BuildError> {
1494        const {
1495            assert!(
1496                size_of::<&A>() == 2 * size_of::<*const ()>(),
1497                "the aspect must be given as its trait-object type, as in \
1498                 .attach::<dyn MyAspect>(…)"
1499            );
1500        }
1501        self.roster.attachments.push(Attachment {
1502            owner: self.feature.clone(),
1503            element: element.into(),
1504            aspect_id: TypeId::of::<A>(),
1505            aspect_name: std::any::type_name::<A>(),
1506            imp: Arc::new(imp),
1507        });
1508        Ok(())
1509    }
1510
1511    /// Declares a fallback: the meaning of a callable name in a parsing mode where
1512    /// nothing else defines it. See [`FallbackDef`]. The declaration is attributed
1513    /// to this feature.
1514    ///
1515    /// # Errors
1516    ///
1517    /// Never fails; problems are reported when the registry is built.
1518    pub fn fallback(&mut self, mut def: FallbackDef) -> Result<(), BuildError> {
1519        def.owner = self.feature.clone();
1520        self.roster.fallbacks.push(def);
1521        Ok(())
1522    }
1523
1524    /// Declares a scoped package. A scoped package is a set of element
1525    /// declarations that is on no scope stack until something adds it: the
1526    /// declaration of an environment body or an argument that refers to the
1527    /// package by name
1528    /// ([`BodyDef::scoped`](crate::lang::mint::BodyDef::scoped),
1529    /// [`ArgDef::scoped`](crate::lang::mint::ArgDef::scoped)), for instance
1530    /// `\item` inside a list's body, or a program that adds it to a parsing
1531    /// state ([`BuiltLang::scoped_package`](crate::lang::BuiltLang::scoped_package)).
1532    /// See [`ScopedPackageDef`].
1533    ///
1534    /// The package and each of its elements are attributed to this feature.
1535    ///
1536    /// # Errors
1537    ///
1538    /// Never fails; problems are reported when the registry is built.
1539    pub fn scoped_package(&mut self, mut def: ScopedPackageDef) -> Result<(), BuildError> {
1540        def.owner = self.feature.clone();
1541        def.docs = crate::kept_docs(def.docs);
1542        for element in &mut def.elements {
1543            element.owner = self.feature.clone();
1544        }
1545        self.roster.scoped_packages.push(def);
1546        Ok(())
1547    }
1548
1549    /// Declares that this feature's definition of the callable name `name`, of
1550    /// kind `kind` (macro, environment or special character sequence), explicitly
1551    /// replaces another feature's definition of it.
1552    ///
1553    /// Two features that define one callable name in one parsing mode, both
1554    /// ordinarily or, where no feature defines it ordinarily in that mode, both
1555    /// weakly ([`crate::lang::mint::packages`]), are otherwise a build error,
1556    /// unless the feature order places the feature registered last explicitly
1557    /// after every other of them ([`crate::core::registry::order`]); with this
1558    /// declaration, a feature made to replace another states so. The
1559    /// declaration counts only where this feature's definition applies: in
1560    /// each mode in which the feature is registered last among those that
1561    /// define the name. Elsewhere it is not consulted.
1562    ///
1563    /// # Errors
1564    ///
1565    /// Never fails; the language build decides whether the replacement applies.
1566    pub fn override_callable(
1567        &mut self,
1568        kind: CallableKind,
1569        name: impl Into<Name>,
1570    ) -> Result<(), BuildError> {
1571        self.roster.overrides.push(OverrideDef {
1572            owner: self.feature.clone(),
1573            kind,
1574            name: name.into(),
1575        });
1576        Ok(())
1577    }
1578
1579    // --- capabilities and tables --------------------------------------------------------
1580
1581    /// Declares a [capability](CapabilityDef): a registered dotted name for a
1582    /// state of processing that a stage brings about.
1583    ///
1584    /// # Errors
1585    ///
1586    /// Never fails. A name already taken in the namespace that capabilities,
1587    /// tables and collections share is reported when the registry is built.
1588    pub fn capability(&mut self, def: CapabilityDef) -> Result<(), BuildError> {
1589        self.roster.capabilities.push((self.feature.clone(), def));
1590        Ok(())
1591    }
1592
1593    /// Declares an [argument role](ArgumentRoleDef) called `name`, described by
1594    /// `docs`: a registered name for what an argument of a command holds, which
1595    /// this feature and others set on arguments with
1596    /// [`ArgDef::role`](crate::lang::mint::ArgDef::role).
1597    ///
1598    /// Write `docs` for a person who reads the registry's declarations: one
1599    /// line saying what an argument of this role holds.
1600    ///
1601    /// # Errors
1602    ///
1603    /// Never fails. A role that another declaration, of this feature or
1604    /// another, declares too is reported when the registry is built, as
1605    /// [`BuildError::Duplicate`].
1606    ///
1607    /// # Examples
1608    ///
1609    /// ```
1610    /// use std::sync::Arc;
1611    /// use flm_core::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature, build_registry};
1612    ///
1613    /// struct Glossary;
1614    /// impl FlmFeature for Glossary {
1615    ///     fn info(&self) -> FeatureInfo { FeatureInfo::new("glossary", "Glossary") }
1616    ///     fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
1617    ///         b.argument_role("glossary.entry", "The key of a glossary entry.")
1618    ///     }
1619    /// }
1620    ///
1621    /// let registry = build_registry([Arc::new(Glossary) as Arc<dyn FlmFeature>])?;
1622    /// let role = registry.argument_role_named("glossary.entry").expect("declared above");
1623    /// assert_eq!(role.owner, "glossary");
1624    /// # Ok::<(), flm_core::core::registry::RegistryBuildError>(())
1625    /// ```
1626    // A role is a name one feature declares in the registry, not free text, so that
1627    // the name has an owner and a documentation text, and a misspelled role is
1628    // reported.
1629    pub fn argument_role(&mut self, name: impl Into<Name>, docs: impl Into<String>) -> Result<(), BuildError> {
1630        self.roster.argument_roles.push((self.feature.clone(), ArgumentRoleDef::new(name, docs)));
1631        Ok(())
1632    }
1633
1634    /// Declares that this feature sets the [argument role](ArgumentRoleDef)
1635    /// `name`, which another feature declares, on arguments of its own
1636    /// declarations, without depending on that feature: a peer declaration
1637    /// ([`PeerName`](super::PeerName)).
1638    ///
1639    /// A feature may set a role that another feature declares whenever that
1640    /// feature is part of the registry. Declaring the role as a peer is what
1641    /// lets the registry build when that feature is absent. When the registry
1642    /// is built, the declaration is resolved against the roles every feature
1643    /// declares:
1644    ///
1645    /// - if a feature declares the role, the declaration changes nothing;
1646    /// - if none does, the build still succeeds, one Note
1647    ///   ([`UnresolvedPeer`](super::UnresolvedPeer)) joins the registry's
1648    ///   [build diagnostics](super::FlmRegistry::build_diagnostics), and the
1649    ///   arguments of this feature keep the role, of which the registry holds
1650    ///   no description.
1651    ///
1652    /// A role that no feature declares and that this feature did not declare
1653    /// as a peer is a build error ([`BuildError::UndeclaredArgumentRole`]),
1654    /// which catches a misspelled name. Declaring the same name again from
1655    /// the same feature has no effect. Two features may each declare the
1656    /// same name.
1657    ///
1658    /// # Errors
1659    ///
1660    /// Never fails; an unresolved declaration is reported as a Note when the
1661    /// registry is built.
1662    pub fn peer_argument_role(&mut self, name: impl Into<Name>) -> Result<(), BuildError> {
1663        self.roster.peer_argument_roles.push(PeerArgumentRoleRecord {
1664            owner: self.feature.clone(),
1665            name: name.into(),
1666        });
1667        Ok(())
1668    }
1669
1670    /// Declares a [collection](CollectionDef): a name for a set of capabilities
1671    /// that any feature may add to.
1672    ///
1673    /// # Errors
1674    ///
1675    /// Never fails. A name already taken in the namespace that capabilities,
1676    /// tables and collections share is reported when the registry is built.
1677    pub fn collection(&mut self, def: CollectionDef) -> Result<(), BuildError> {
1678        self.roster.collections.push((self.feature.clone(), def));
1679        Ok(())
1680    }
1681
1682    /// Adds the capability `member` to the collection `collection`, which any
1683    /// feature may declare, in any order of registration.
1684    ///
1685    /// When no feature of the registry declares the collection, the build drops
1686    /// the member without any diagnostic. A feature that adds its check to a
1687    /// collection another feature declares must still be registrable on its own,
1688    /// and reporting the absent collection would refuse ordinary registries.
1689    ///
1690    /// # Errors
1691    ///
1692    /// Never fails. A member that is not a declared capability is reported when
1693    /// the registry is built.
1694    pub fn collection_member(
1695        &mut self,
1696        collection: impl Into<CapName>,
1697        member: impl Into<CapName>,
1698    ) -> Result<(), BuildError> {
1699        self.roster.members.push((self.feature.clone(), collection.into(), member.into()));
1700        Ok(())
1701    }
1702
1703    /// The value type of the table `name` as the declarations collected so far
1704    /// hold it: the type of a table some feature declared, else the type of a
1705    /// peer table this feature declared ([`peer_table`](FeatureBuilder::peer_table)),
1706    /// else `None`.
1707    ///
1708    /// A [`Finalizer`] reads every feature's declarations here, since the
1709    /// second registration round runs after the first round of every feature;
1710    /// a feature's `register` sees only the features registered before it.
1711    pub fn table_type_named(&self, name: &str) -> Option<TableType> {
1712        let declared = self.roster.tables.iter().find(|record| record.def.name.as_str() == name);
1713        declared.map(|record| record.def.ty).or_else(|| {
1714            self.roster
1715                .peer_tables
1716                .iter()
1717                .find(|record| record.owner == self.feature && record.name.as_str() == name)
1718                .map(|record| record.value)
1719        })
1720    }
1721
1722    fn table_record<T: Table>(
1723        &mut self,
1724        name: CapName,
1725        docs: String,
1726        external: bool,
1727    ) -> TableHandle<T> {
1728        self.roster.tables.push(TableRecord {
1729            def: TableDef {
1730                name: name.clone(),
1731                ty: TableType::of::<T>(),
1732                docs,
1733                owner: self.feature.clone(),
1734            },
1735            external,
1736            refines: None,
1737            default: false,
1738        });
1739        TableHandle::new(name)
1740    }
1741
1742    /// Declares a [table](crate::core::data::table::Table) holding a value of type
1743    /// `T`, under the name given by `T`'s [`TableName`] constant. A table is typed
1744    /// data that one stage writes beside the frozen trees and other stages read.
1745    ///
1746    /// A table's name is also a capability, the capability of the table having
1747    /// been written. This method therefore declares that capability too, and the
1748    /// name must be free in the namespace that capabilities, tables and
1749    /// collections share.
1750    ///
1751    /// The returned [`TableHandle`] is what a stage declares its writes and reads
1752    /// with, and what reads the table's value at run time.
1753    ///
1754    /// # Errors
1755    ///
1756    /// Never fails. A name clash is reported when the registry is built.
1757    pub fn table<T: Table>(
1758        &mut self,
1759        name: TableName<T>,
1760        docs: impl Into<String>,
1761    ) -> Result<TableHandle<T>, BuildError> {
1762        Ok(self.table_record::<T>(CapName::from(name.name()), crate::kept_docs(docs), false))
1763    }
1764
1765    /// Declares a table holding a value of type `T` under a name computed at
1766    /// registration, such as `flm.lowered.<backend>`.
1767    ///
1768    /// This method does exactly what [`table`](FeatureBuilder::table) does, for a
1769    /// name that is not known at compile time and so cannot be a [`TableName`]
1770    /// constant.
1771    ///
1772    /// # Errors
1773    ///
1774    /// Never fails. A name clash is reported when the registry is built.
1775    pub fn table_named<T: Table>(
1776        &mut self,
1777        name: impl Into<CapName>,
1778        docs: impl Into<String>,
1779    ) -> Result<TableHandle<T>, BuildError> {
1780        Ok(self.table_record::<T>(name.into(), crate::kept_docs(docs), false))
1781    }
1782
1783    /// Declares a table holding a value of type `T` under a name computed at
1784    /// registration, whose capability refines the capability `parent`: a stage
1785    /// that writes the table provides `parent` too, as a stage that provides a
1786    /// refining capability does ([`CapabilityDef::refines`]).
1787    ///
1788    /// Otherwise exactly [`table_named`](FeatureBuilder::table_named). A
1789    /// processing feature declares the table of its rendered formulas this way,
1790    /// as a refinement of the capability of rendered mathematics.
1791    ///
1792    /// # Errors
1793    ///
1794    /// Never fails. A name clash, a `parent` that no feature declares, or a
1795    /// chain of refinements that leads back to itself is reported when the
1796    /// registry is built.
1797    pub fn table_refining_named<T: Table>(
1798        &mut self,
1799        name: impl Into<CapName>,
1800        parent: impl Into<CapName>,
1801        docs: impl Into<String>,
1802    ) -> Result<TableHandle<T>, BuildError> {
1803        let handle = self.table_record::<T>(name.into(), crate::kept_docs(docs), false);
1804        if let Some(record) = self.roster.tables.last_mut() {
1805            record.refines = Some(parent.into());
1806        }
1807        Ok(handle)
1808    }
1809
1810    /// Declares an **external table** holding a value of type `T`. An external
1811    /// table is a table that no stage of the run writes: the caller installs its
1812    /// value when the run is constructed ([`Externals`](crate::core::run::Externals)).
1813    ///
1814    /// External tables bring data from outside the run into the plan, for example
1815    /// results carried over from a previous run, or a table the host computes
1816    /// itself. The installation satisfies the table's capability, and a stage that
1817    /// declares a write of the table is a build error.
1818    ///
1819    /// # Errors
1820    ///
1821    /// Never fails. A name clash, or a stage that writes this table, is reported
1822    /// when the registry is built.
1823    pub fn external_table<T: Table>(
1824        &mut self,
1825        name: TableName<T>,
1826        docs: impl Into<String>,
1827    ) -> Result<TableHandle<T>, BuildError> {
1828        Ok(self.table_record::<T>(CapName::from(name.name()), crate::kept_docs(docs), true))
1829    }
1830
1831    /// Declares an external table holding a value of type `T` under a name
1832    /// computed at registration; otherwise exactly
1833    /// [`external_table`](FeatureBuilder::external_table).
1834    ///
1835    /// # Errors
1836    ///
1837    /// Never fails; problems are reported when the registry is built.
1838    pub fn external_table_named<T: Table>(
1839        &mut self,
1840        name: impl Into<CapName>,
1841        docs: impl Into<String>,
1842    ) -> Result<TableHandle<T>, BuildError> {
1843        Ok(self.table_record::<T>(name.into(), crate::kept_docs(docs), true))
1844    }
1845
1846    // --- stages ---------------------------------------------------------------------------
1847
1848    fn push_stage(&mut self, stage: Arc<dyn Stage>) -> usize {
1849        let decl = stage.decl();
1850        self.roster.stages.push(StageRecord {
1851            owner: self.feature.clone(),
1852            kind: StageKind::Pipeline(stage),
1853            decl,
1854            rewrite: None,
1855        });
1856        self.roster.stages.len() - 1
1857    }
1858
1859    /// Registers an ordinary [stage](Stage): one that runs after the trees are
1860    /// frozen and computes data, checks something, or performs input and output.
1861    ///
1862    /// The builder reads the stage's [`decl`](Stage::decl) once, here, and the
1863    /// build and every plan use that declaration; a stage's declaration is
1864    /// therefore fixed for the life of the registry. Register a rewrite stage with
1865    /// [`rewrite_stage`](FeatureBuilder::rewrite_stage) instead.
1866    ///
1867    /// # Errors
1868    ///
1869    /// Never fails. A duplicate stage name, a check stage that declares a write,
1870    /// or a reference to an entity no feature declares is reported when the
1871    /// registry is built.
1872    pub fn stage(&mut self, stage: Arc<dyn Stage>) -> Result<(), BuildError> {
1873        self.push_stage(stage);
1874        Ok(())
1875    }
1876
1877    /// Registers a [rewrite stage](RewriteStage): a stage that turns one tree
1878    /// into another before the trees are frozen.
1879    ///
1880    /// The builder reads the stage's [`decl`](RewriteStage::decl) once, here. It
1881    /// declares at the same time the table of trees that the rewrite publishes,
1882    /// under the name the declaration gives, with the refinement and the default
1883    /// mark the declaration gives. A rewrite's output is therefore a table like
1884    /// any other, and no other part of the library needs to know that a rewrite
1885    /// produced it.
1886    ///
1887    /// # Errors
1888    ///
1889    /// Never fails; problems are reported when the registry is built.
1890    pub fn rewrite_stage(&mut self, stage: Arc<dyn RewriteStage>) -> Result<(), BuildError> {
1891        let rewrite = stage.decl();
1892        let decl = StageDecl::new(
1893            rewrite.name.clone(),
1894            crate::core::stage::Effect::Compute,
1895            crate::core::stage::Scope::PerTree,
1896        )
1897        .writes(TableHandle::<crate::core::stage::TreesTable>::new(rewrite.publishes.clone()))
1898        .docs(rewrite.docs.clone());
1899        self.roster.tables.push(TableRecord {
1900            def: TableDef {
1901                name: rewrite.publishes.clone(),
1902                ty: TableType::of::<crate::core::stage::TreesTable>(),
1903                docs: rewrite.docs.clone(),
1904                owner: self.feature.clone(),
1905            },
1906            external: false,
1907            refines: rewrite.refines.clone(),
1908            default: rewrite.default,
1909        });
1910        self.roster.stages.push(StageRecord {
1911            owner: self.feature.clone(),
1912            kind: StageKind::Rewrite(stage),
1913            decl,
1914            rewrite: Some(rewrite),
1915        });
1916        Ok(())
1917    }
1918
1919    /// Places [ordering edges](OrderingDef) on a stage, this feature's or
1920    /// another feature's, saying which capabilities' providers the stage must run
1921    /// after or before.
1922    ///
1923    /// # Errors
1924    ///
1925    /// Never fails. Edges on a stage that no feature registers, or edges that
1926    /// refer to a capability no feature declares, are reported when the registry
1927    /// is built.
1928    pub fn ordering(&mut self, def: OrderingDef) -> Result<(), BuildError> {
1929        self.roster.orderings.push((self.feature.clone(), def));
1930        Ok(())
1931    }
1932
1933    // --- lowering ---------------------------------------------------------------------
1934
1935    /// Registers a [lowering rule](LoweringRule): a named registry entity written
1936    /// for one element, which builds the element's presentation for one backend.
1937    ///
1938    /// # Errors
1939    ///
1940    /// Never fails. A duplicate rule name, an element or a backend that no feature
1941    /// declares, or two rules marked as the default for one element on one
1942    /// backend is reported when the registry is built.
1943    pub fn lowering_rule(&mut self, rule: LoweringRule) -> Result<(), BuildError> {
1944        self.roster.rules.push((self.feature.clone(), rule));
1945        Ok(())
1946    }
1947
1948    // The registry creates the value and hands it back, so that the nodes a backend
1949    // stages carry exactly the value the registry interned and attributed to the feature.
1950    /// Registers a **presentation element**: an element that exists only in the
1951    /// trees a backend writes, with no syntax and no callable name of its own,
1952    /// whose nodes carry a payload of type `P`. Returns the element value.
1953    ///
1954    /// The builder creates the element value here and returns it, because there
1955    /// is no source syntax to create it from and the backend's author needs the
1956    /// value itself to build the nodes that carry it. Attach aspects to it with
1957    /// [`attach`](FeatureBuilder::attach), as to any element.
1958    ///
1959    /// # Errors
1960    ///
1961    /// Never fails. A name that is also the name of an element that can appear in
1962    /// a parsed document is reported when the registry is built.
1963    pub fn presentation_element<P: PresPayload>(
1964        &mut self,
1965        name: impl Into<ElementName>,
1966        docs: impl Into<String>,
1967    ) -> Result<Arc<ElementSpec>, BuildError> {
1968        let name = name.into();
1969        let docs = crate::kept_docs(docs);
1970        let element = Arc::new(ElementSpec::new(name).docs(docs.clone()));
1971        self.roster.presentation.push(PresentationRecord {
1972            owner: self.feature.clone(),
1973            element: Arc::clone(&element),
1974            payload: TypeKey::of::<P>(),
1975            docs,
1976        });
1977        Ok(element)
1978    }
1979
1980    /// Registers a [backend](BackendDef): the registration bundle for one output
1981    /// format, with its native set and its lowering, emit and final stages.
1982    ///
1983    /// The builder registers the three stages as this feature's own stages, in
1984    /// the order lowering, emit, final; they are scheduled like any other stage.
1985    /// The backend declaration groups them so that a plan recognizes them as one
1986    /// backend.
1987    ///
1988    /// # Errors
1989    ///
1990    /// Never fails. A native element that no feature declares, or a duplicate
1991    /// backend or stage name, is reported when the registry is built; so is a
1992    /// native set that does not satisfy a [native-set
1993    /// implication](NativeImplication), as [`BuildError::NativeSetIncomplete`].
1994    pub fn backend(&mut self, def: BackendDef) -> Result<(), BuildError> {
1995        let lowering = self.push_stage(def.lowering);
1996        let emit = self.push_stage(def.emit);
1997        let final_stage = self.push_stage(def.final_stage);
1998        self.roster.backends.push(BackendRecord {
1999            owner: self.feature.clone(),
2000            name: def.name,
2001            native: def.native,
2002            docs: def.docs,
2003            lowering,
2004            emit,
2005            final_stage,
2006        });
2007        Ok(())
2008    }
2009
2010    /// Declares a [native-set implication](NativeImplication): a requirement on
2011    /// what a backend's native set must contain, checked against every backend of
2012    /// the registry, this feature's and every other feature's, when the registry
2013    /// is built.
2014    ///
2015    /// # Errors
2016    ///
2017    /// Never fails. An element that no feature declares is reported when the
2018    /// registry is built as [`BuildError::Undeclared`], and a backend whose native
2019    /// set does not satisfy the implication as
2020    /// [`BuildError::NativeSetIncomplete`].
2021    pub fn native_implication(&mut self, def: NativeImplication) -> Result<(), BuildError> {
2022        self.roster.native_implications.push((self.feature.clone(), def));
2023        Ok(())
2024    }
2025
2026    /// Declares a **peer backend**: a [peer declaration](super::PeerName) of a
2027    /// backend called `name` that this feature expects another feature of the
2028    /// registry to register. With it, this feature's lowering rules may list the
2029    /// backend in their default mark
2030    /// ([`DefaultMark::OnBackends`](crate::core::lowering::DefaultMark::OnBackends))
2031    /// without this feature registering the backend or depending on the feature
2032    /// that does.
2033    ///
2034    /// The declaration registers nothing and counts for this feature alone. When
2035    /// the registry is built, it is resolved against the declarations of every
2036    /// feature:
2037    ///
2038    /// - if a feature registers the backend, this feature's rules that refer to
2039    ///   it take part like any other rule;
2040    /// - if none does, the build still succeeds, one Note
2041    ///   ([`UnresolvedPeer`](super::UnresolvedPeer)) joins the registry's [build
2042    ///   diagnostics](super::FlmRegistry::build_diagnostics), and every rule of
2043    ///   this feature that refers to the backend is set aside: never selected, and
2044    ///   never counted by the check that the backend can write every element.
2045    ///
2046    /// See [`PeerName`](super::PeerName) for the full rules, and
2047    /// [`peer_element`](FeatureBuilder::peer_element) and
2048    /// [`peer_table`](FeatureBuilder::peer_table) for the presentation elements
2049    /// such a rule produces and the tables it reads.
2050    ///
2051    /// Declaring the same name again from the same feature has no effect: the
2052    /// repeat is merged into the first declaration, whose `docs` are kept. Two
2053    /// features may each declare the same name.
2054    ///
2055    /// # Errors
2056    ///
2057    /// Never fails; an unresolved declaration is reported as a Note when the
2058    /// registry is built.
2059    pub fn peer_backend(
2060        &mut self,
2061        name: impl Into<BackendName>,
2062        docs: impl Into<String>,
2063    ) -> Result<(), BuildError> {
2064        self.roster.peer_backends.push(PeerBackendRecord {
2065            owner: self.feature.clone(),
2066            name: name.into(),
2067            docs: crate::kept_docs(docs),
2068        });
2069        Ok(())
2070    }
2071
2072    /// Declares a **peer element**: a [peer declaration](super::PeerName) of a
2073    /// presentation element called `name`, whose nodes carry a payload of type
2074    /// `P`, that this feature expects another feature of the registry to register
2075    /// with [`presentation_element`](FeatureBuilder::presentation_element). With
2076    /// it, this feature's lowering rules may list the element in their `produces`
2077    /// without this feature depending on the feature that owns the element.
2078    ///
2079    /// The payload type is the declaration's signature. When the registry is
2080    /// built, the declaration is resolved against the declarations of every
2081    /// feature:
2082    ///
2083    /// - a presentation element registered under this name with payload type `P`
2084    ///   resolves it;
2085    /// - a presentation element registered with another payload type, or an
2086    ///   element of this name that can appear in a parsed document, is refused as
2087    ///   [`BuildError::PeerElementMismatch`];
2088    /// - a name that no feature declares leaves the declaration unresolved: every
2089    ///   rule of this feature that produces the element is set aside, as
2090    ///   [`peer_backend`](FeatureBuilder::peer_backend) describes.
2091    ///
2092    /// Declaring the same name again from the same feature with the same payload
2093    /// type has no effect: the repeat is merged into the first declaration, whose
2094    /// `docs` are kept. Declaring it again with another payload type is a
2095    /// duplicate, refused when the registry is built as [`BuildError::Duplicate`].
2096    /// Two features may each declare the same name, since a declaration counts for
2097    /// its own feature alone.
2098    ///
2099    /// # Errors
2100    ///
2101    /// Never fails. When the registry is built, a repeat with another payload type
2102    /// is reported as [`BuildError::Duplicate`], and a payload mismatch as
2103    /// [`BuildError::PeerElementMismatch`].
2104    pub fn peer_element<P: PresPayload>(
2105        &mut self,
2106        name: impl Into<ElementName>,
2107        docs: impl Into<String>,
2108    ) -> Result<(), BuildError> {
2109        self.roster.peer_elements.push(PeerElementRecord {
2110            owner: self.feature.clone(),
2111            name: name.into(),
2112            payload: TypeKey::of::<P>(),
2113            docs: crate::kept_docs(docs),
2114        });
2115        Ok(())
2116    }
2117
2118    /// Declares a **peer table**: a [peer declaration](super::PeerName) of a table
2119    /// called `name`, holding a value of type `R`, that this feature expects
2120    /// another feature of the registry to declare. With it, this feature's
2121    /// lowering rules may read the table, and its stages may write it, without
2122    /// this feature depending on the feature that owns the table.
2123    ///
2124    /// The value type is the declaration's signature: the type the reading rule
2125    /// expects, which is the type the owning feature declared the table with.
2126    /// When the registry is built, the declaration is resolved against the
2127    /// declarations of every feature: a table declared under this name holding an
2128    /// `R` resolves it; a table holding another type is refused as
2129    /// [`BuildError::PeerTableMismatch`]; and a name that no feature declares
2130    /// leaves the declaration unresolved.
2131    ///
2132    /// What an unresolved peer table does to a lowering rule depends on how the
2133    /// rule reads it:
2134    ///
2135    /// - a rule that reads it as a hard dependency
2136    ///   ([`LoweringDecl::reads`](crate::core::lowering::LoweringDecl::reads)) is
2137    ///   set aside, as [`peer_backend`](FeatureBuilder::peer_backend) describes,
2138    ///   because without the table the rule cannot do its work;
2139    /// - a rule that reads it optionally
2140    ///   ([`reads_opt`](crate::core::lowering::LoweringDecl::reads_opt)) is
2141    ///   selected and runs, and finds the table absent; this lets a rule write
2142    ///   what it can in a registry that does not hold the other feature.
2143    ///
2144    /// In both cases, one Note ([`UnresolvedPeer`](super::UnresolvedPeer)) joins
2145    /// the registry's [build diagnostics](super::FlmRegistry::build_diagnostics).
2146    ///
2147    /// A stage of this feature may also *write* a peer table: the other feature
2148    /// declares the table, and this feature's stage writes it (for example, the
2149    /// `graphics` feature's publish stage writes the copies of images into an
2150    /// output's artifact table, which the backend declares). When the peer table
2151    /// is unresolved, every stage of this feature that writes it is set aside and
2152    /// not registered, since it would have nowhere to write and the feature that
2153    /// reads the table is absent; the Note lists those stages. The build also
2154    /// drops the ordering edges placed on such a stage
2155    /// ([`FeatureBuilder::ordering`]).
2156    ///
2157    /// A peer table is not an [external table](crate::core::run::Externals): an
2158    /// external table is a table that no stage of the run writes, whose value the
2159    /// caller installs when the run is constructed, and the feature that declares
2160    /// it registers it with [`external_table`](FeatureBuilder::external_table);
2161    /// a peer table belongs to another feature, whose stage computes it like any
2162    /// other table.
2163    ///
2164    /// Declaring the same name again from the same feature with the same value
2165    /// type has no effect: the repeat is merged into the first declaration, whose
2166    /// `docs` are kept. Declaring it again with another value type is a duplicate,
2167    /// refused when the registry is built as [`BuildError::Duplicate`]. Two
2168    /// features may each declare the same name.
2169    ///
2170    /// # Errors
2171    ///
2172    /// Never fails. When the registry is built, a repeat with another value type
2173    /// is reported as [`BuildError::Duplicate`], and a value-type mismatch as
2174    /// [`BuildError::PeerTableMismatch`].
2175    pub fn peer_table<R: Table>(
2176        &mut self,
2177        name: impl Into<CapName>,
2178        docs: impl Into<String>,
2179    ) -> Result<(), BuildError> {
2180        self.roster.peer_tables.push(PeerTableRecord {
2181            owner: self.feature.clone(),
2182            name: name.into(),
2183            value: TableType::of::<R>(),
2184            docs: crate::kept_docs(docs),
2185        });
2186        Ok(())
2187    }
2188
2189    /// Declares a peer table whose value type is given as a [`TableType`]
2190    /// rather than as a type parameter: exactly
2191    /// [`peer_table`](FeatureBuilder::peer_table) with `R` the type `value`
2192    /// stands for.
2193    ///
2194    /// For a caller that names tables by name and learns their types from the
2195    /// declarations ([`table_type_named`](FeatureBuilder::table_type_named)),
2196    /// such as a [`Finalizer`] declaring for a feature written in another
2197    /// language.
2198    ///
2199    /// # Errors
2200    ///
2201    /// As [`peer_table`](FeatureBuilder::peer_table).
2202    pub fn peer_table_of(
2203        &mut self,
2204        name: impl Into<CapName>,
2205        value: TableType,
2206        docs: impl Into<String>,
2207    ) -> Result<(), BuildError> {
2208        self.roster.peer_tables.push(PeerTableRecord {
2209            owner: self.feature.clone(),
2210            name: name.into(),
2211            value,
2212            docs: crate::kept_docs(docs),
2213        });
2214        Ok(())
2215    }
2216
2217    /// The payload type of the presentation element `name` as the collected
2218    /// declarations hold it ([`presentation_element`](FeatureBuilder::presentation_element)),
2219    /// or `None` when no feature registered a presentation element of that
2220    /// name. Like [`table_type_named`](FeatureBuilder::table_type_named), it
2221    /// sees every feature's declarations from a [`Finalizer`].
2222    pub fn presentation_payload_named(&self, name: &str) -> Option<TypeKey> {
2223        self.roster
2224            .presentation
2225            .iter()
2226            .find(|record| record.element.name.as_str() == name)
2227            .map(|record| record.payload)
2228    }
2229
2230    /// Declares a peer element whose payload type is given as a [`TypeKey`]
2231    /// rather than as a type parameter: exactly
2232    /// [`peer_element`](FeatureBuilder::peer_element) with `P` the type
2233    /// `payload` stands for. For the same callers as
2234    /// [`peer_table_of`](FeatureBuilder::peer_table_of), with
2235    /// [`presentation_payload_named`](FeatureBuilder::presentation_payload_named).
2236    ///
2237    /// # Errors
2238    ///
2239    /// As [`peer_element`](FeatureBuilder::peer_element).
2240    pub fn peer_element_of(
2241        &mut self,
2242        name: impl Into<ElementName>,
2243        payload: TypeKey,
2244        docs: impl Into<String>,
2245    ) -> Result<(), BuildError> {
2246        self.roster.peer_elements.push(PeerElementRecord {
2247            owner: self.feature.clone(),
2248            name: name.into(),
2249            payload,
2250            docs: crate::kept_docs(docs),
2251        });
2252        Ok(())
2253    }
2254
2255    /// Declares a **peer scoped package**: a [peer
2256    /// declaration](super::PeerName) of a [scoped package](ScopedPackageDef)
2257    /// called `name` that this feature expects another feature of the registry to
2258    /// declare with [`scoped_package`](FeatureBuilder::scoped_package). With it,
2259    /// the environment bodies and arguments that this feature declares may refer
2260    /// to the package ([`BodyDef::scoped`](crate::lang::mint::BodyDef::scoped),
2261    /// [`ArgDef::scoped`](crate::lang::mint::ArgDef::scoped)) without this feature
2262    /// depending on the feature that owns it.
2263    ///
2264    /// The declaration registers nothing and counts for this feature alone. When
2265    /// the registry is built, it is resolved against the declarations of every
2266    /// feature:
2267    ///
2268    /// - if a feature declares the package, the bodies and arguments that refer to
2269    ///   it get its definitions, exactly as without the peer declaration;
2270    /// - if none does, the build still succeeds, one Note
2271    ///   ([`UnresolvedPeer`](super::UnresolvedPeer)) joins the registry's [build
2272    ///   diagnostics](super::FlmRegistry::build_diagnostics), and each body or
2273    ///   argument of this feature that refers to the package gets no definition
2274    ///   from it: a command the package would have defined is an unknown command
2275    ///   there, as anywhere else.
2276    ///
2277    /// A scoped package name that no feature declares and that this feature did
2278    /// not declare as a peer remains the build error
2279    /// [`MintError::UnknownScopedPackage`](crate::lang::mint::MintError::UnknownScopedPackage),
2280    /// which catches a misspelled name. See [`PeerName`](super::PeerName) for the
2281    /// other kinds of peer declaration.
2282    ///
2283    /// Declaring the same name again from the same feature has no effect: the
2284    /// repeat is merged into the first declaration, whose `docs` are kept. Two
2285    /// features may each declare the same name.
2286    ///
2287    /// # Errors
2288    ///
2289    /// Never fails; an unresolved declaration is reported as a Note when the
2290    /// registry is built.
2291    pub fn peer_scoped_package(
2292        &mut self,
2293        name: impl Into<Name>,
2294        docs: impl Into<String>,
2295    ) -> Result<(), BuildError> {
2296        self.roster.peer_scoped_packages.push(PeerScopedPackageRecord {
2297            owner: self.feature.clone(),
2298            name: name.into(),
2299            docs: crate::kept_docs(docs),
2300        });
2301        Ok(())
2302    }
2303
2304    /// Registers an [output](OutputDef): a name a caller asks for to have
2305    /// something produced, such as `text` or `html`.
2306    ///
2307    /// # Errors
2308    ///
2309    /// Never fails. An output whose table does not hold an artifact set, or whose
2310    /// capability is neither its table's capability nor a refinement of it, is
2311    /// reported when the registry is built.
2312    pub fn output(&mut self, def: OutputDef) -> Result<(), BuildError> {
2313        self.roster.outputs.push((self.feature.clone(), def));
2314        Ok(())
2315    }
2316
2317    /// Registers a [workflow](WorkflowDef): a named set of demands together with
2318    /// the choices that go with them.
2319    ///
2320    /// # Errors
2321    ///
2322    /// Never fails. A workflow that refers to an output, capability, stage,
2323    /// backend, element or lowering rule that no feature declares, a chain of
2324    /// workflows that leads back to itself, or a render option value whose option
2325    /// type no feature declares or cannot be set on a render request is reported
2326    /// when the registry is built.
2327    pub fn workflow(&mut self, def: WorkflowDef) -> Result<(), BuildError> {
2328        self.roster.workflows.push((self.feature.clone(), def));
2329        Ok(())
2330    }
2331
2332    /// Registers fields for the workflow called `def.name`: every field that
2333    /// `def` declares replaces that field of the workflow a feature registers
2334    /// under that name with [`workflow`](FeatureBuilder::workflow), so that the
2335    /// two make one workflow. When no feature registers a workflow of that name,
2336    /// `def` is the workflow.
2337    ///
2338    /// A field is declared when it is set: `extends` given, a list or a map not
2339    /// empty, `docs` not empty
2340    /// ([`WorkflowDef::replace_declared_fields`]). Fields registered for one name
2341    /// by several features are applied in registration order, the later replacing
2342    /// the earlier, and the fields the embedding program registers with
2343    /// [`RegistryBuilder::workflow_fields`](super::RegistryBuilder::workflow_fields)
2344    /// are applied after all of them. A feature uses this method to change some
2345    /// fields of a workflow without knowing whether another feature registers a
2346    /// workflow of that name.
2347    ///
2348    /// # Errors
2349    ///
2350    /// Never fails; the combined workflow is checked like any other when the
2351    /// registry is built.
2352    pub fn workflow_fields(&mut self, def: WorkflowDef) -> Result<(), BuildError> {
2353        self.roster.workflow_fields.push((self.feature.clone(), def));
2354        Ok(())
2355    }
2356
2357    // --- options and services ---------------------------------------------------------
2358
2359    /// Declares the option type `T`, whose values are set where its binding
2360    /// `bind` allows: on the document, on the render request, on either, or
2361    /// nowhere because the value is fixed when the registry is built (see
2362    /// [`Bind`] and [option types](crate::model::options)).
2363    ///
2364    /// # Errors
2365    ///
2366    /// Never fails. A second declaration of the same option type, or a workflow
2367    /// that sets a value where the binding does not allow it, is reported when
2368    /// the registry is built.
2369    pub fn options<T: Options>(&mut self, bind: Bind) -> Result<(), BuildError> {
2370        self.roster.options.push(OptionDecl::of::<T>(self.feature.clone(), bind));
2371        Ok(())
2372    }
2373
2374    /// Declares the option type `T` with the binding `bind` and with
2375    /// documentation prose; otherwise exactly [`options`](FeatureBuilder::options).
2376    ///
2377    /// # Errors
2378    ///
2379    /// Never fails; problems are reported when the registry is built.
2380    pub fn options_with_docs<T: Options>(
2381        &mut self,
2382        bind: Bind,
2383        docs: impl Into<String>,
2384    ) -> Result<(), BuildError> {
2385        self.roster.options.push(OptionDecl::of::<T>(self.feature.clone(), bind).docs(docs));
2386        Ok(())
2387    }
2388
2389    /// Declares the option type declared from data under the name `name`, with
2390    /// the binding `bind` and the documentation `docs`. Only a
2391    /// [`SettingsDecl`](crate::core::settings::SettingsDecl) declares one
2392    /// ([`config_data`](crate::core::settings::SettingsDecl::config_data),
2393    /// [`options_data`](crate::core::settings::SettingsDecl::options_data)).
2394    ///
2395    /// # Errors
2396    ///
2397    /// Never fails; a second declaration of the same name, by this feature or
2398    /// another, is reported when the registry is built, as for an option type
2399    /// that is a Rust type.
2400    pub(crate) fn options_named(&mut self, name: Name, bind: Bind, docs: String) -> Result<(), BuildError> {
2401        self.roster.options.push(OptionDecl::named(name, self.feature.clone(), bind).docs(docs));
2402        Ok(())
2403    }
2404
2405    /// Declares a [service slot](crate::core::services) called `name`, holding
2406    /// values of type `S` (usually a trait-object type), and taking as many
2407    /// contributions as `arity` allows.
2408    ///
2409    /// A service is a value that can be shared across threads which one feature
2410    /// supplies for another feature, or for the embedding program, to use. By
2411    /// declaring a service slot, a feature states that something it needs is to be
2412    /// supplied from outside the feature, by another feature or by the embedding
2413    /// program.
2414    ///
2415    /// # Errors
2416    ///
2417    /// [`BuildError::ContributionAfterAssembly`] when called from a
2418    /// [`Finalizer`]: the build assembles the service slots between the two
2419    /// registration rounds, and they cannot change afterwards.
2420    pub fn service_slot<S: ?Sized + Any + Send + Sync>(
2421        &mut self,
2422        name: impl Into<Name>,
2423        arity: Arity,
2424        docs: impl Into<String>,
2425    ) -> Result<(), BuildError> {
2426        self.round_one_only(RoundTwoAction::DeclareSlot)?;
2427        self.roster.slots.push(SlotDecl {
2428            name: name.into(),
2429            ty: TypeKey::of::<S>(),
2430            arity,
2431            owner: self.feature.clone(),
2432            docs: crate::kept_docs(docs),
2433        });
2434        Ok(())
2435    }
2436
2437    fn contribute_inner<S: ?Sized + Any + Send + Sync>(
2438        &mut self,
2439        target: SlotTarget,
2440        imp: Arc<S>,
2441        prepend: bool,
2442    ) -> Result<(), BuildError> {
2443        self.round_one_only(RoundTwoAction::Contribute)?;
2444        self.roster.contributions.push(Contribution::new(
2445            self.feature.clone(),
2446            target,
2447            imp,
2448            prepend,
2449        ));
2450        Ok(())
2451    }
2452
2453    /// Contributes `imp` to the service slot whose value type is `S`, after every
2454    /// contribution already made to it.
2455    ///
2456    /// # Errors
2457    ///
2458    /// [`BuildError::ContributionAfterAssembly`] when called from a
2459    /// [`Finalizer`].
2460    pub fn contribute<S: ?Sized + Any + Send + Sync>(
2461        &mut self,
2462        imp: Arc<S>,
2463    ) -> Result<(), BuildError> {
2464        self.contribute_inner(SlotTarget::ByType(TypeKey::of::<S>()), imp, false)
2465    }
2466
2467    /// Contributes `imp` to the service slot called `slot`, after every
2468    /// contribution already made to it.
2469    ///
2470    /// When no feature declares that service slot, the registry build fails. For
2471    /// a service slot that another feature owns and that may be absent, use
2472    /// [`peer_slot`](FeatureBuilder::peer_slot) instead.
2473    ///
2474    /// # Errors
2475    ///
2476    /// [`BuildError::ContributionAfterAssembly`] when called from a
2477    /// [`Finalizer`].
2478    pub fn contribute_to<S: ?Sized + Any + Send + Sync>(
2479        &mut self,
2480        slot: impl Into<Name>,
2481        imp: Arc<S>,
2482    ) -> Result<(), BuildError> {
2483        self.contribute_inner(SlotTarget::ByName(slot.into()), imp, false)
2484    }
2485
2486    /// Contributes `imp` to the service slot whose value type is `S`, before
2487    /// every contribution appended to it.
2488    ///
2489    /// Order matters for a service slot that takes several contributions and consults
2490    /// them in turn; with this method a feature places its contribution first.
2491    /// Among the contributions placed first this way, a read for precedence
2492    /// takes those of the feature placed last in the feature order first
2493    /// ([`Services::services_by_precedence_named`](crate::core::services::Services::services_by_precedence_named)).
2494    ///
2495    /// # Errors
2496    ///
2497    /// [`BuildError::ContributionAfterAssembly`] when called from a
2498    /// [`Finalizer`].
2499    pub fn contribute_first<S: ?Sized + Any + Send + Sync>(
2500        &mut self,
2501        imp: Arc<S>,
2502    ) -> Result<(), BuildError> {
2503        self.contribute_inner(SlotTarget::ByType(TypeKey::of::<S>()), imp, true)
2504    }
2505
2506    /// Contributes `imp` to the service slot called `slot`, before every
2507    /// contribution appended to it. Among the contributions placed first this
2508    /// way, a read for precedence takes those of the feature placed last in the
2509    /// feature order first
2510    /// ([`Services::services_by_precedence_named`](crate::core::services::Services::services_by_precedence_named)).
2511    ///
2512    /// # Errors
2513    ///
2514    /// [`BuildError::ContributionAfterAssembly`] when called from a
2515    /// [`Finalizer`].
2516    pub fn contribute_first_to<S: ?Sized + Any + Send + Sync>(
2517        &mut self,
2518        slot: impl Into<Name>,
2519        imp: Arc<S>,
2520    ) -> Result<(), BuildError> {
2521        self.contribute_inner(SlotTarget::ByName(slot.into()), imp, true)
2522    }
2523
2524    /// Makes a **peer contribution**: contributes `imp` to the service slot
2525    /// called `slot`, a service slot that another feature of the registry is
2526    /// expected to declare. A feature uses it to offer a value to a feature that may not be
2527    /// registered. This is the service-slot form of a [peer
2528    /// declaration](super::PeerName).
2529    ///
2530    /// [`contribute_to`](FeatureBuilder::contribute_to) is the form for a service
2531    /// slot this feature owns, or one it knows is declared: contributing to a
2532    /// service slot that no feature declares is then a registry build error
2533    /// ([`ServiceError::UndeclaredSlot`]), which catches a misspelled name. With
2534    /// this method, the service slot belongs to another feature:
2535    ///
2536    /// - if a feature declares the service slot, the value fills it exactly as
2537    ///   [`contribute_to`](FeatureBuilder::contribute_to) would, after every
2538    ///   contribution already made, and with its type checked against the
2539    ///   service slot's value type;
2540    /// - if no feature declares it, the value is dropped, the build still
2541    ///   succeeds, and one Note ([`UnresolvedPeer`](super::UnresolvedPeer)) joins
2542    ///   the registry's [build diagnostics](super::FlmRegistry::build_diagnostics),
2543    ///   one per feature and service slot, however many values this feature
2544    ///   offered to that service slot.
2545    ///
2546    /// The value type `S` is the declaration's signature, written as the type the
2547    /// service slot declares: a trait-object type, as in
2548    /// `b.peer_slot::<dyn Greeter>(…)`, when the value is behavior. A value of
2549    /// another type than the service slot declares
2550    /// is refused, as it is through
2551    /// [`contribute_to`](FeatureBuilder::contribute_to).
2552    ///
2553    /// Every peer contribution, resolved or not, is listed on the finished
2554    /// registry ([`FlmRegistry::peer_slots`](super::FlmRegistry::peer_slots)), so a
2555    /// misspelled service slot name can be found on any registry that holds the feature.
2556    ///
2557    /// # Errors
2558    ///
2559    /// [`BuildError::ContributionAfterAssembly`] when called from a
2560    /// [`Finalizer`]: the build assembles the service slots between the two
2561    /// registration rounds, and they cannot change afterwards.
2562    pub fn peer_slot<S: ?Sized + Any + Send + Sync>(
2563        &mut self,
2564        slot: impl Into<Name>,
2565        imp: Arc<S>,
2566    ) -> Result<(), BuildError> {
2567        self.round_one_only(RoundTwoAction::Contribute)?;
2568        self.roster.contributions.push(
2569            Contribution::new(self.feature.clone(), SlotTarget::ByName(slot.into()), imp, false)
2570                .as_peer(),
2571        );
2572        Ok(())
2573    }
2574
2575    /// Declares that this feature cannot work unless the service slot whose value
2576    /// type is `S` is filled.
2577    ///
2578    /// A required service slot that is not filled makes the registry build fail, so a
2579    /// missing service is reported once, when the registry is built, instead of
2580    /// as a failure in the middle of processing a document.
2581    ///
2582    /// # Errors
2583    ///
2584    /// [`BuildError::ContributionAfterAssembly`] when called from a
2585    /// [`Finalizer`].
2586    pub fn require_service<S: ?Sized + Any + Send + Sync>(&mut self) -> Result<(), BuildError> {
2587        self.round_one_only(RoundTwoAction::RequireSlot)?;
2588        self.roster.requirements.push(ServiceRequirement {
2589            owner: self.feature.clone(),
2590            target: SlotTarget::ByType(TypeKey::of::<S>()),
2591        });
2592        Ok(())
2593    }
2594
2595    /// Declares that this feature cannot work unless the service slot called
2596    /// `slot` is filled; otherwise exactly
2597    /// [`require_service`](FeatureBuilder::require_service).
2598    ///
2599    /// # Errors
2600    ///
2601    /// [`BuildError::ContributionAfterAssembly`] when called from a
2602    /// [`Finalizer`].
2603    pub fn require_service_named(&mut self, slot: impl Into<Name>) -> Result<(), BuildError> {
2604        self.round_one_only(RoundTwoAction::RequireSlot)?;
2605        self.roster.requirements.push(ServiceRequirement {
2606            owner: self.feature.clone(),
2607            target: SlotTarget::ByName(slot.into()),
2608        });
2609        Ok(())
2610    }
2611
2612    // --- hooks and records ------------------------------------------------------------
2613
2614    /// Registers a [`Finalizer`] of this feature: a build hook that runs in the
2615    /// build's second registration round, once the service slots are assembled.
2616    ///
2617    /// A feature may register several finalizers; they run in the order
2618    /// registered.
2619    ///
2620    /// # Errors
2621    ///
2622    /// [`BuildError::ContributionAfterAssembly`] when called from a
2623    /// [`Finalizer`]: there are exactly two rounds, so a finalizer cannot add a
2624    /// third.
2625    pub fn finalizer(&mut self, finalizer: Arc<dyn Finalizer>) -> Result<(), BuildError> {
2626        self.round_one_only(RoundTwoAction::RegisterFinalizer)?;
2627        self.roster.finalizers.push((self.feature.clone(), finalizer));
2628        Ok(())
2629    }
2630
2631    /// Registers a [`LateInit`] hook of this feature: a build hook that runs once
2632    /// the FLM language is built, for example to compile the templates the
2633    /// feature's configuration holds.
2634    ///
2635    /// Unlike [`finalizer`](FeatureBuilder::finalizer), this method may be called
2636    /// in either round.
2637    ///
2638    /// # Errors
2639    ///
2640    /// Never fails. A failure of the hook itself makes the build fail in the
2641    /// late-initialization phase.
2642    pub fn late_init(&mut self, hook: Arc<dyn LateInit>) -> Result<(), BuildError> {
2643        self.roster.late_inits.push((self.feature.clone(), hook));
2644        Ok(())
2645    }
2646
2647    /// Records a [style definition](StyleDef) in the registry: a stylesheet that
2648    /// a feature's output depends on, under an identifier.
2649    ///
2650    /// A lowering rule or an emitter then requires the definition by its
2651    /// identifier where its output needs it; the backend that writes the output
2652    /// resolves the identifier against the definitions recorded here.
2653    ///
2654    /// # Errors
2655    ///
2656    /// Never fails.
2657    pub fn style_def(&mut self, mut def: StyleDef) -> Result<(), BuildError> {
2658        def.docs = crate::kept_docs(def.docs);
2659        self.roster.styles.push((self.feature.clone(), def));
2660        Ok(())
2661    }
2662
2663    /// Records a [script definition](ScriptDef) in the registry: the counterpart
2664    /// of [`style_def`](FeatureBuilder::style_def) for scripts.
2665    ///
2666    /// # Errors
2667    ///
2668    /// Never fails.
2669    pub fn script_def(&mut self, mut def: ScriptDef) -> Result<(), BuildError> {
2670        def.docs = crate::kept_docs(def.docs);
2671        self.roster.scripts.push((self.feature.clone(), def));
2672        Ok(())
2673    }
2674
2675    /// Gives `bytes` as an input of the [registry digest](crate::model::digest),
2676    /// the number that stands for everything about a registry that can change
2677    /// what processing produces.
2678    ///
2679    /// The build computes the digest from the declarations it can enumerate. A
2680    /// feature's configuration may hold other data that changes what processing
2681    /// produces (for example, the text of an author-written template), which the
2682    /// build cannot see. The feature gives that data here, so that data cached
2683    /// under the digest is not reused after the configuration changes.
2684    ///
2685    /// # Errors
2686    ///
2687    /// Never fails.
2688    pub fn digest_input(&mut self, bytes: &[u8]) -> Result<(), BuildError> {
2689        self.roster
2690            .digest_inputs
2691            .push(DigestInput { owner: self.feature.clone(), bytes: bytes.to_vec() });
2692        Ok(())
2693    }
2694}
2695
2696impl fmt::Debug for FeatureBuilder<'_> {
2697    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2698        f.debug_struct("FeatureBuilder")
2699            .field("feature", &self.feature)
2700            .field("round", &self.round)
2701            .finish()
2702    }
2703}
2704
2705/// The feature name that represents the embedding program itself.
2706///
2707/// Service contributions made through
2708/// [`RegistryBuilder::contribute`](super::RegistryBuilder::contribute) and
2709/// [`RegistryBuilder::contribute_to`](super::RegistryBuilder::contribute_to),
2710/// and workflow fields given through
2711/// [`RegistryBuilder::workflow_fields`](super::RegistryBuilder::workflow_fields),
2712/// come from no feature; they are attributed to this name, so that every
2713/// contribution has an owner to show in a message. The leading underscore
2714/// keeps it apart from the dotted lowercase names of features.
2715pub const HOST_FEATURE: &str = "_host";