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 can be written only inside the environment bodies and
1526    /// arguments whose declarations refer to the package by name
1527    /// ([`BodyDef::scoped`](crate::lang::mint::BodyDef::scoped),
1528    /// [`ArgDef::scoped`](crate::lang::mint::ArgDef::scoped)), for instance
1529    /// `\item` inside a list's body. See [`ScopedPackageDef`].
1530    ///
1531    /// The package and each of its elements are attributed to this feature.
1532    ///
1533    /// # Errors
1534    ///
1535    /// Never fails; problems are reported when the registry is built.
1536    pub fn scoped_package(&mut self, mut def: ScopedPackageDef) -> Result<(), BuildError> {
1537        def.owner = self.feature.clone();
1538        def.docs = crate::kept_docs(def.docs);
1539        for element in &mut def.elements {
1540            element.owner = self.feature.clone();
1541        }
1542        self.roster.scoped_packages.push(def);
1543        Ok(())
1544    }
1545
1546    /// Declares that this feature's definition of the callable name `name`, of
1547    /// kind `kind` (macro, environment or special character sequence), explicitly
1548    /// replaces another feature's definition of it.
1549    ///
1550    /// Two features that define one callable name in one parsing mode are
1551    /// otherwise a build error, unless the feature order places the feature
1552    /// registered last explicitly after every other feature that defines the
1553    /// name in that mode ([`crate::core::registry::order`]); with this
1554    /// declaration, a feature made to replace another states so. The
1555    /// declaration counts only where this feature's definition applies: in
1556    /// each mode in which the feature is registered last among those that
1557    /// define the name. Elsewhere it is not consulted.
1558    ///
1559    /// # Errors
1560    ///
1561    /// Never fails; the language build decides whether the replacement applies.
1562    pub fn override_callable(
1563        &mut self,
1564        kind: CallableKind,
1565        name: impl Into<Name>,
1566    ) -> Result<(), BuildError> {
1567        self.roster.overrides.push(OverrideDef {
1568            owner: self.feature.clone(),
1569            kind,
1570            name: name.into(),
1571        });
1572        Ok(())
1573    }
1574
1575    // --- capabilities and tables --------------------------------------------------------
1576
1577    /// Declares a [capability](CapabilityDef): a registered dotted name for a
1578    /// state of processing that a stage brings about.
1579    ///
1580    /// # Errors
1581    ///
1582    /// Never fails. A name already taken in the namespace that capabilities,
1583    /// tables and collections share is reported when the registry is built.
1584    pub fn capability(&mut self, def: CapabilityDef) -> Result<(), BuildError> {
1585        self.roster.capabilities.push((self.feature.clone(), def));
1586        Ok(())
1587    }
1588
1589    /// Declares an [argument role](ArgumentRoleDef) called `name`, described by
1590    /// `docs`: a registered name for what an argument of a command holds, which
1591    /// this feature and others set on arguments with
1592    /// [`ArgDef::role`](crate::lang::mint::ArgDef::role).
1593    ///
1594    /// Write `docs` for a person who reads the registry's declarations: one
1595    /// line saying what an argument of this role holds.
1596    ///
1597    /// # Errors
1598    ///
1599    /// Never fails. A role that another declaration, of this feature or
1600    /// another, declares too is reported when the registry is built, as
1601    /// [`BuildError::Duplicate`].
1602    ///
1603    /// # Examples
1604    ///
1605    /// ```
1606    /// use std::sync::Arc;
1607    /// use flm_core::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature, build_registry};
1608    ///
1609    /// struct Glossary;
1610    /// impl FlmFeature for Glossary {
1611    ///     fn info(&self) -> FeatureInfo { FeatureInfo::new("glossary", "Glossary") }
1612    ///     fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
1613    ///         b.argument_role("glossary.entry", "The key of a glossary entry.")
1614    ///     }
1615    /// }
1616    ///
1617    /// let registry = build_registry([Arc::new(Glossary) as Arc<dyn FlmFeature>])?;
1618    /// let role = registry.argument_role_named("glossary.entry").expect("declared above");
1619    /// assert_eq!(role.owner, "glossary");
1620    /// # Ok::<(), flm_core::core::registry::RegistryBuildError>(())
1621    /// ```
1622    // A role is a name one feature declares in the registry, not free text, so that
1623    // the name has an owner and a documentation text, and a misspelled role is
1624    // reported.
1625    pub fn argument_role(&mut self, name: impl Into<Name>, docs: impl Into<String>) -> Result<(), BuildError> {
1626        self.roster.argument_roles.push((self.feature.clone(), ArgumentRoleDef::new(name, docs)));
1627        Ok(())
1628    }
1629
1630    /// Declares that this feature sets the [argument role](ArgumentRoleDef)
1631    /// `name`, which another feature declares, on arguments of its own
1632    /// declarations, without depending on that feature: a peer declaration
1633    /// ([`PeerName`](super::PeerName)).
1634    ///
1635    /// A feature may set a role that another feature declares whenever that
1636    /// feature is part of the registry. Declaring the role as a peer is what
1637    /// lets the registry build when that feature is absent. When the registry
1638    /// is built, the declaration is resolved against the roles every feature
1639    /// declares:
1640    ///
1641    /// - if a feature declares the role, the declaration changes nothing;
1642    /// - if none does, the build still succeeds, one Note
1643    ///   ([`UnresolvedPeer`](super::UnresolvedPeer)) joins the registry's
1644    ///   [build diagnostics](super::FlmRegistry::build_diagnostics), and the
1645    ///   arguments of this feature keep the role, of which the registry holds
1646    ///   no description.
1647    ///
1648    /// A role that no feature declares and that this feature did not declare
1649    /// as a peer is a build error ([`BuildError::UndeclaredArgumentRole`]),
1650    /// which catches a misspelled name. Declaring the same name again from
1651    /// the same feature has no effect. Two features may each declare the
1652    /// same name.
1653    ///
1654    /// # Errors
1655    ///
1656    /// Never fails; an unresolved declaration is reported as a Note when the
1657    /// registry is built.
1658    pub fn peer_argument_role(&mut self, name: impl Into<Name>) -> Result<(), BuildError> {
1659        self.roster.peer_argument_roles.push(PeerArgumentRoleRecord {
1660            owner: self.feature.clone(),
1661            name: name.into(),
1662        });
1663        Ok(())
1664    }
1665
1666    /// Declares a [collection](CollectionDef): a name for a set of capabilities
1667    /// that any feature may add to.
1668    ///
1669    /// # Errors
1670    ///
1671    /// Never fails. A name already taken in the namespace that capabilities,
1672    /// tables and collections share is reported when the registry is built.
1673    pub fn collection(&mut self, def: CollectionDef) -> Result<(), BuildError> {
1674        self.roster.collections.push((self.feature.clone(), def));
1675        Ok(())
1676    }
1677
1678    /// Adds the capability `member` to the collection `collection`, which any
1679    /// feature may declare, in any order of registration.
1680    ///
1681    /// When no feature of the registry declares the collection, the build drops
1682    /// the member without any diagnostic. A feature that adds its check to a
1683    /// collection another feature declares must still be registrable on its own,
1684    /// and reporting the absent collection would refuse ordinary registries.
1685    ///
1686    /// # Errors
1687    ///
1688    /// Never fails. A member that is not a declared capability is reported when
1689    /// the registry is built.
1690    pub fn collection_member(
1691        &mut self,
1692        collection: impl Into<CapName>,
1693        member: impl Into<CapName>,
1694    ) -> Result<(), BuildError> {
1695        self.roster.members.push((self.feature.clone(), collection.into(), member.into()));
1696        Ok(())
1697    }
1698
1699    /// The value type of the table `name` as the declarations collected so far
1700    /// hold it: the type of a table some feature declared, else the type of a
1701    /// peer table this feature declared ([`peer_table`](FeatureBuilder::peer_table)),
1702    /// else `None`.
1703    ///
1704    /// A [`Finalizer`] reads every feature's declarations here, since the
1705    /// second registration round runs after the first round of every feature;
1706    /// a feature's `register` sees only the features registered before it.
1707    pub fn table_type_named(&self, name: &str) -> Option<TableType> {
1708        let declared = self.roster.tables.iter().find(|record| record.def.name.as_str() == name);
1709        declared.map(|record| record.def.ty).or_else(|| {
1710            self.roster
1711                .peer_tables
1712                .iter()
1713                .find(|record| record.owner == self.feature && record.name.as_str() == name)
1714                .map(|record| record.value)
1715        })
1716    }
1717
1718    fn table_record<T: Table>(
1719        &mut self,
1720        name: CapName,
1721        docs: String,
1722        external: bool,
1723    ) -> TableHandle<T> {
1724        self.roster.tables.push(TableRecord {
1725            def: TableDef {
1726                name: name.clone(),
1727                ty: TableType::of::<T>(),
1728                docs,
1729                owner: self.feature.clone(),
1730            },
1731            external,
1732            refines: None,
1733            default: false,
1734        });
1735        TableHandle::new(name)
1736    }
1737
1738    /// Declares a [table](crate::core::data::table::Table) holding a value of type
1739    /// `T`, under the name given by `T`'s [`TableName`] constant. A table is typed
1740    /// data that one stage writes beside the frozen trees and other stages read.
1741    ///
1742    /// A table's name is also a capability, the capability of the table having
1743    /// been written. This method therefore declares that capability too, and the
1744    /// name must be free in the namespace that capabilities, tables and
1745    /// collections share.
1746    ///
1747    /// The returned [`TableHandle`] is what a stage declares its writes and reads
1748    /// with, and what reads the table's value at run time.
1749    ///
1750    /// # Errors
1751    ///
1752    /// Never fails. A name clash is reported when the registry is built.
1753    pub fn table<T: Table>(
1754        &mut self,
1755        name: TableName<T>,
1756        docs: impl Into<String>,
1757    ) -> Result<TableHandle<T>, BuildError> {
1758        Ok(self.table_record::<T>(CapName::from(name.name()), crate::kept_docs(docs), false))
1759    }
1760
1761    /// Declares a table holding a value of type `T` under a name computed at
1762    /// registration, such as `flm.lowered.<backend>`.
1763    ///
1764    /// This method does exactly what [`table`](FeatureBuilder::table) does, for a
1765    /// name that is not known at compile time and so cannot be a [`TableName`]
1766    /// constant.
1767    ///
1768    /// # Errors
1769    ///
1770    /// Never fails. A name clash is reported when the registry is built.
1771    pub fn table_named<T: Table>(
1772        &mut self,
1773        name: impl Into<CapName>,
1774        docs: impl Into<String>,
1775    ) -> Result<TableHandle<T>, BuildError> {
1776        Ok(self.table_record::<T>(name.into(), crate::kept_docs(docs), false))
1777    }
1778
1779    /// Declares a table holding a value of type `T` under a name computed at
1780    /// registration, whose capability refines the capability `parent`: a stage
1781    /// that writes the table provides `parent` too, as a stage that provides a
1782    /// refining capability does ([`CapabilityDef::refines`]).
1783    ///
1784    /// Otherwise exactly [`table_named`](FeatureBuilder::table_named). A
1785    /// processing feature declares the table of its rendered formulas this way,
1786    /// as a refinement of the capability of rendered mathematics.
1787    ///
1788    /// # Errors
1789    ///
1790    /// Never fails. A name clash, a `parent` that no feature declares, or a
1791    /// chain of refinements that leads back to itself is reported when the
1792    /// registry is built.
1793    pub fn table_refining_named<T: Table>(
1794        &mut self,
1795        name: impl Into<CapName>,
1796        parent: impl Into<CapName>,
1797        docs: impl Into<String>,
1798    ) -> Result<TableHandle<T>, BuildError> {
1799        let handle = self.table_record::<T>(name.into(), crate::kept_docs(docs), false);
1800        if let Some(record) = self.roster.tables.last_mut() {
1801            record.refines = Some(parent.into());
1802        }
1803        Ok(handle)
1804    }
1805
1806    /// Declares an **external table** holding a value of type `T`. An external
1807    /// table is a table that no stage of the run writes: the caller installs its
1808    /// value when the run is constructed ([`Externals`](crate::core::run::Externals)).
1809    ///
1810    /// External tables bring data from outside the run into the plan, for example
1811    /// results carried over from a previous run, or a table the host computes
1812    /// itself. The installation satisfies the table's capability, and a stage that
1813    /// declares a write of the table is a build error.
1814    ///
1815    /// # Errors
1816    ///
1817    /// Never fails. A name clash, or a stage that writes this table, is reported
1818    /// when the registry is built.
1819    pub fn external_table<T: Table>(
1820        &mut self,
1821        name: TableName<T>,
1822        docs: impl Into<String>,
1823    ) -> Result<TableHandle<T>, BuildError> {
1824        Ok(self.table_record::<T>(CapName::from(name.name()), crate::kept_docs(docs), true))
1825    }
1826
1827    /// Declares an external table holding a value of type `T` under a name
1828    /// computed at registration; otherwise exactly
1829    /// [`external_table`](FeatureBuilder::external_table).
1830    ///
1831    /// # Errors
1832    ///
1833    /// Never fails; problems are reported when the registry is built.
1834    pub fn external_table_named<T: Table>(
1835        &mut self,
1836        name: impl Into<CapName>,
1837        docs: impl Into<String>,
1838    ) -> Result<TableHandle<T>, BuildError> {
1839        Ok(self.table_record::<T>(name.into(), crate::kept_docs(docs), true))
1840    }
1841
1842    // --- stages ---------------------------------------------------------------------------
1843
1844    fn push_stage(&mut self, stage: Arc<dyn Stage>) -> usize {
1845        let decl = stage.decl();
1846        self.roster.stages.push(StageRecord {
1847            owner: self.feature.clone(),
1848            kind: StageKind::Pipeline(stage),
1849            decl,
1850            rewrite: None,
1851        });
1852        self.roster.stages.len() - 1
1853    }
1854
1855    /// Registers an ordinary [stage](Stage): one that runs after the trees are
1856    /// frozen and computes data, checks something, or performs input and output.
1857    ///
1858    /// The builder reads the stage's [`decl`](Stage::decl) once, here, and the
1859    /// build and every plan use that declaration; a stage's declaration is
1860    /// therefore fixed for the life of the registry. Register a rewrite stage with
1861    /// [`rewrite_stage`](FeatureBuilder::rewrite_stage) instead.
1862    ///
1863    /// # Errors
1864    ///
1865    /// Never fails. A duplicate stage name, a check stage that declares a write,
1866    /// or a reference to an entity no feature declares is reported when the
1867    /// registry is built.
1868    pub fn stage(&mut self, stage: Arc<dyn Stage>) -> Result<(), BuildError> {
1869        self.push_stage(stage);
1870        Ok(())
1871    }
1872
1873    /// Registers a [rewrite stage](RewriteStage): a stage that turns one tree
1874    /// into another before the trees are frozen.
1875    ///
1876    /// The builder reads the stage's [`decl`](RewriteStage::decl) once, here. It
1877    /// declares at the same time the table of trees that the rewrite publishes,
1878    /// under the name the declaration gives, with the refinement and the default
1879    /// mark the declaration gives. A rewrite's output is therefore a table like
1880    /// any other, and no other part of the library needs to know that a rewrite
1881    /// produced it.
1882    ///
1883    /// # Errors
1884    ///
1885    /// Never fails; problems are reported when the registry is built.
1886    pub fn rewrite_stage(&mut self, stage: Arc<dyn RewriteStage>) -> Result<(), BuildError> {
1887        let rewrite = stage.decl();
1888        let decl = StageDecl::new(
1889            rewrite.name.clone(),
1890            crate::core::stage::Effect::Compute,
1891            crate::core::stage::Scope::PerTree,
1892        )
1893        .writes(TableHandle::<crate::core::stage::TreesTable>::new(rewrite.publishes.clone()))
1894        .docs(rewrite.docs.clone());
1895        self.roster.tables.push(TableRecord {
1896            def: TableDef {
1897                name: rewrite.publishes.clone(),
1898                ty: TableType::of::<crate::core::stage::TreesTable>(),
1899                docs: rewrite.docs.clone(),
1900                owner: self.feature.clone(),
1901            },
1902            external: false,
1903            refines: rewrite.refines.clone(),
1904            default: rewrite.default,
1905        });
1906        self.roster.stages.push(StageRecord {
1907            owner: self.feature.clone(),
1908            kind: StageKind::Rewrite(stage),
1909            decl,
1910            rewrite: Some(rewrite),
1911        });
1912        Ok(())
1913    }
1914
1915    /// Places [ordering edges](OrderingDef) on a stage, this feature's or
1916    /// another feature's, saying which capabilities' providers the stage must run
1917    /// after or before.
1918    ///
1919    /// # Errors
1920    ///
1921    /// Never fails. Edges on a stage that no feature registers, or edges that
1922    /// refer to a capability no feature declares, are reported when the registry
1923    /// is built.
1924    pub fn ordering(&mut self, def: OrderingDef) -> Result<(), BuildError> {
1925        self.roster.orderings.push((self.feature.clone(), def));
1926        Ok(())
1927    }
1928
1929    // --- lowering ---------------------------------------------------------------------
1930
1931    /// Registers a [lowering rule](LoweringRule): a named registry entity written
1932    /// for one element, which builds the element's presentation for one backend.
1933    ///
1934    /// # Errors
1935    ///
1936    /// Never fails. A duplicate rule name, an element or a backend that no feature
1937    /// declares, or two rules marked as the default for one element on one
1938    /// backend is reported when the registry is built.
1939    pub fn lowering_rule(&mut self, rule: LoweringRule) -> Result<(), BuildError> {
1940        self.roster.rules.push((self.feature.clone(), rule));
1941        Ok(())
1942    }
1943
1944    // The registry creates the value and hands it back, so that the nodes a backend
1945    // stages carry exactly the value the registry interned and attributed to the feature.
1946    /// Registers a **presentation element**: an element that exists only in the
1947    /// trees a backend writes, with no syntax and no callable name of its own,
1948    /// whose nodes carry a payload of type `P`. Returns the element value.
1949    ///
1950    /// The builder creates the element value here and returns it, because there
1951    /// is no source syntax to create it from and the backend's author needs the
1952    /// value itself to build the nodes that carry it. Attach aspects to it with
1953    /// [`attach`](FeatureBuilder::attach), as to any element.
1954    ///
1955    /// # Errors
1956    ///
1957    /// Never fails. A name that is also the name of an element that can appear in
1958    /// a parsed document is reported when the registry is built.
1959    pub fn presentation_element<P: PresPayload>(
1960        &mut self,
1961        name: impl Into<ElementName>,
1962        docs: impl Into<String>,
1963    ) -> Result<Arc<ElementSpec>, BuildError> {
1964        let name = name.into();
1965        let docs = crate::kept_docs(docs);
1966        let element = Arc::new(ElementSpec::new(name).docs(docs.clone()));
1967        self.roster.presentation.push(PresentationRecord {
1968            owner: self.feature.clone(),
1969            element: Arc::clone(&element),
1970            payload: TypeKey::of::<P>(),
1971            docs,
1972        });
1973        Ok(element)
1974    }
1975
1976    /// Registers a [backend](BackendDef): the registration bundle for one output
1977    /// format, with its native set and its lowering, emit and final stages.
1978    ///
1979    /// The builder registers the three stages as this feature's own stages, in
1980    /// the order lowering, emit, final; they are scheduled like any other stage.
1981    /// The backend declaration groups them so that a plan recognizes them as one
1982    /// backend.
1983    ///
1984    /// # Errors
1985    ///
1986    /// Never fails. A native element that no feature declares, or a duplicate
1987    /// backend or stage name, is reported when the registry is built; so is a
1988    /// native set that does not satisfy a [native-set
1989    /// implication](NativeImplication), as [`BuildError::NativeSetIncomplete`].
1990    pub fn backend(&mut self, def: BackendDef) -> Result<(), BuildError> {
1991        let lowering = self.push_stage(def.lowering);
1992        let emit = self.push_stage(def.emit);
1993        let final_stage = self.push_stage(def.final_stage);
1994        self.roster.backends.push(BackendRecord {
1995            owner: self.feature.clone(),
1996            name: def.name,
1997            native: def.native,
1998            docs: def.docs,
1999            lowering,
2000            emit,
2001            final_stage,
2002        });
2003        Ok(())
2004    }
2005
2006    /// Declares a [native-set implication](NativeImplication): a requirement on
2007    /// what a backend's native set must contain, checked against every backend of
2008    /// the registry, this feature's and every other feature's, when the registry
2009    /// is built.
2010    ///
2011    /// # Errors
2012    ///
2013    /// Never fails. An element that no feature declares is reported when the
2014    /// registry is built as [`BuildError::Undeclared`], and a backend whose native
2015    /// set does not satisfy the implication as
2016    /// [`BuildError::NativeSetIncomplete`].
2017    pub fn native_implication(&mut self, def: NativeImplication) -> Result<(), BuildError> {
2018        self.roster.native_implications.push((self.feature.clone(), def));
2019        Ok(())
2020    }
2021
2022    /// Declares a **peer backend**: a [peer declaration](super::PeerName) of a
2023    /// backend called `name` that this feature expects another feature of the
2024    /// registry to register. With it, this feature's lowering rules may list the
2025    /// backend in their default mark
2026    /// ([`DefaultMark::OnBackends`](crate::core::lowering::DefaultMark::OnBackends))
2027    /// without this feature registering the backend or depending on the feature
2028    /// that does.
2029    ///
2030    /// The declaration registers nothing and counts for this feature alone. When
2031    /// the registry is built, it is resolved against the declarations of every
2032    /// feature:
2033    ///
2034    /// - if a feature registers the backend, this feature's rules that refer to
2035    ///   it take part like any other rule;
2036    /// - if none does, the build still succeeds, one Note
2037    ///   ([`UnresolvedPeer`](super::UnresolvedPeer)) joins the registry's [build
2038    ///   diagnostics](super::FlmRegistry::build_diagnostics), and every rule of
2039    ///   this feature that refers to the backend is set aside: never selected, and
2040    ///   never counted by the check that the backend can write every element.
2041    ///
2042    /// See [`PeerName`](super::PeerName) for the full rules, and
2043    /// [`peer_element`](FeatureBuilder::peer_element) and
2044    /// [`peer_table`](FeatureBuilder::peer_table) for the presentation elements
2045    /// such a rule produces and the tables it reads.
2046    ///
2047    /// Declaring the same name again from the same feature has no effect: the
2048    /// repeat is merged into the first declaration, whose `docs` are kept. Two
2049    /// features may each declare the same name.
2050    ///
2051    /// # Errors
2052    ///
2053    /// Never fails; an unresolved declaration is reported as a Note when the
2054    /// registry is built.
2055    pub fn peer_backend(
2056        &mut self,
2057        name: impl Into<BackendName>,
2058        docs: impl Into<String>,
2059    ) -> Result<(), BuildError> {
2060        self.roster.peer_backends.push(PeerBackendRecord {
2061            owner: self.feature.clone(),
2062            name: name.into(),
2063            docs: crate::kept_docs(docs),
2064        });
2065        Ok(())
2066    }
2067
2068    /// Declares a **peer element**: a [peer declaration](super::PeerName) of a
2069    /// presentation element called `name`, whose nodes carry a payload of type
2070    /// `P`, that this feature expects another feature of the registry to register
2071    /// with [`presentation_element`](FeatureBuilder::presentation_element). With
2072    /// it, this feature's lowering rules may list the element in their `produces`
2073    /// without this feature depending on the feature that owns the element.
2074    ///
2075    /// The payload type is the declaration's signature. When the registry is
2076    /// built, the declaration is resolved against the declarations of every
2077    /// feature:
2078    ///
2079    /// - a presentation element registered under this name with payload type `P`
2080    ///   resolves it;
2081    /// - a presentation element registered with another payload type, or an
2082    ///   element of this name that can appear in a parsed document, is refused as
2083    ///   [`BuildError::PeerElementMismatch`];
2084    /// - a name that no feature declares leaves the declaration unresolved: every
2085    ///   rule of this feature that produces the element is set aside, as
2086    ///   [`peer_backend`](FeatureBuilder::peer_backend) describes.
2087    ///
2088    /// Declaring the same name again from the same feature with the same payload
2089    /// type has no effect: the repeat is merged into the first declaration, whose
2090    /// `docs` are kept. Declaring it again with another payload type is a
2091    /// duplicate, refused when the registry is built as [`BuildError::Duplicate`].
2092    /// Two features may each declare the same name, since a declaration counts for
2093    /// its own feature alone.
2094    ///
2095    /// # Errors
2096    ///
2097    /// Never fails. When the registry is built, a repeat with another payload type
2098    /// is reported as [`BuildError::Duplicate`], and a payload mismatch as
2099    /// [`BuildError::PeerElementMismatch`].
2100    pub fn peer_element<P: PresPayload>(
2101        &mut self,
2102        name: impl Into<ElementName>,
2103        docs: impl Into<String>,
2104    ) -> Result<(), BuildError> {
2105        self.roster.peer_elements.push(PeerElementRecord {
2106            owner: self.feature.clone(),
2107            name: name.into(),
2108            payload: TypeKey::of::<P>(),
2109            docs: crate::kept_docs(docs),
2110        });
2111        Ok(())
2112    }
2113
2114    /// Declares a **peer table**: a [peer declaration](super::PeerName) of a table
2115    /// called `name`, holding a value of type `R`, that this feature expects
2116    /// another feature of the registry to declare. With it, this feature's
2117    /// lowering rules may read the table, and its stages may write it, without
2118    /// this feature depending on the feature that owns the table.
2119    ///
2120    /// The value type is the declaration's signature: the type the reading rule
2121    /// expects, which is the type the owning feature declared the table with.
2122    /// When the registry is built, the declaration is resolved against the
2123    /// declarations of every feature: a table declared under this name holding an
2124    /// `R` resolves it; a table holding another type is refused as
2125    /// [`BuildError::PeerTableMismatch`]; and a name that no feature declares
2126    /// leaves the declaration unresolved.
2127    ///
2128    /// What an unresolved peer table does to a lowering rule depends on how the
2129    /// rule reads it:
2130    ///
2131    /// - a rule that reads it as a hard dependency
2132    ///   ([`LoweringDecl::reads`](crate::core::lowering::LoweringDecl::reads)) is
2133    ///   set aside, as [`peer_backend`](FeatureBuilder::peer_backend) describes,
2134    ///   because without the table the rule cannot do its work;
2135    /// - a rule that reads it optionally
2136    ///   ([`reads_opt`](crate::core::lowering::LoweringDecl::reads_opt)) is
2137    ///   selected and runs, and finds the table absent; this lets a rule write
2138    ///   what it can in a registry that does not hold the other feature.
2139    ///
2140    /// In both cases, one Note ([`UnresolvedPeer`](super::UnresolvedPeer)) joins
2141    /// the registry's [build diagnostics](super::FlmRegistry::build_diagnostics).
2142    ///
2143    /// A stage of this feature may also *write* a peer table: the other feature
2144    /// declares the table, and this feature's stage writes it (for example, the
2145    /// `graphics` feature's publish stage writes the copies of images into an
2146    /// output's artifact table, which the backend declares). When the peer table
2147    /// is unresolved, every stage of this feature that writes it is set aside and
2148    /// not registered, since it would have nowhere to write and the feature that
2149    /// reads the table is absent; the Note lists those stages. The build also
2150    /// drops the ordering edges placed on such a stage
2151    /// ([`FeatureBuilder::ordering`]).
2152    ///
2153    /// A peer table is not an [external table](crate::core::run::Externals): an
2154    /// external table is a table that no stage of the run writes, whose value the
2155    /// caller installs when the run is constructed, and the feature that declares
2156    /// it registers it with [`external_table`](FeatureBuilder::external_table);
2157    /// a peer table belongs to another feature, whose stage computes it like any
2158    /// other table.
2159    ///
2160    /// Declaring the same name again from the same feature with the same value
2161    /// type has no effect: the repeat is merged into the first declaration, whose
2162    /// `docs` are kept. Declaring it again with another value type is a duplicate,
2163    /// refused when the registry is built as [`BuildError::Duplicate`]. Two
2164    /// features may each declare the same name.
2165    ///
2166    /// # Errors
2167    ///
2168    /// Never fails. When the registry is built, a repeat with another value type
2169    /// is reported as [`BuildError::Duplicate`], and a value-type mismatch as
2170    /// [`BuildError::PeerTableMismatch`].
2171    pub fn peer_table<R: Table>(
2172        &mut self,
2173        name: impl Into<CapName>,
2174        docs: impl Into<String>,
2175    ) -> Result<(), BuildError> {
2176        self.roster.peer_tables.push(PeerTableRecord {
2177            owner: self.feature.clone(),
2178            name: name.into(),
2179            value: TableType::of::<R>(),
2180            docs: crate::kept_docs(docs),
2181        });
2182        Ok(())
2183    }
2184
2185    /// Declares a peer table whose value type is given as a [`TableType`]
2186    /// rather than as a type parameter: exactly
2187    /// [`peer_table`](FeatureBuilder::peer_table) with `R` the type `value`
2188    /// stands for.
2189    ///
2190    /// For a caller that names tables by name and learns their types from the
2191    /// declarations ([`table_type_named`](FeatureBuilder::table_type_named)),
2192    /// such as a [`Finalizer`] declaring for a feature written in another
2193    /// language.
2194    ///
2195    /// # Errors
2196    ///
2197    /// As [`peer_table`](FeatureBuilder::peer_table).
2198    pub fn peer_table_of(
2199        &mut self,
2200        name: impl Into<CapName>,
2201        value: TableType,
2202        docs: impl Into<String>,
2203    ) -> Result<(), BuildError> {
2204        self.roster.peer_tables.push(PeerTableRecord {
2205            owner: self.feature.clone(),
2206            name: name.into(),
2207            value,
2208            docs: crate::kept_docs(docs),
2209        });
2210        Ok(())
2211    }
2212
2213    /// The payload type of the presentation element `name` as the collected
2214    /// declarations hold it ([`presentation_element`](FeatureBuilder::presentation_element)),
2215    /// or `None` when no feature registered a presentation element of that
2216    /// name. Like [`table_type_named`](FeatureBuilder::table_type_named), it
2217    /// sees every feature's declarations from a [`Finalizer`].
2218    pub fn presentation_payload_named(&self, name: &str) -> Option<TypeKey> {
2219        self.roster
2220            .presentation
2221            .iter()
2222            .find(|record| record.element.name.as_str() == name)
2223            .map(|record| record.payload)
2224    }
2225
2226    /// Declares a peer element whose payload type is given as a [`TypeKey`]
2227    /// rather than as a type parameter: exactly
2228    /// [`peer_element`](FeatureBuilder::peer_element) with `P` the type
2229    /// `payload` stands for. For the same callers as
2230    /// [`peer_table_of`](FeatureBuilder::peer_table_of), with
2231    /// [`presentation_payload_named`](FeatureBuilder::presentation_payload_named).
2232    ///
2233    /// # Errors
2234    ///
2235    /// As [`peer_element`](FeatureBuilder::peer_element).
2236    pub fn peer_element_of(
2237        &mut self,
2238        name: impl Into<ElementName>,
2239        payload: TypeKey,
2240        docs: impl Into<String>,
2241    ) -> Result<(), BuildError> {
2242        self.roster.peer_elements.push(PeerElementRecord {
2243            owner: self.feature.clone(),
2244            name: name.into(),
2245            payload,
2246            docs: crate::kept_docs(docs),
2247        });
2248        Ok(())
2249    }
2250
2251    /// Declares a **peer scoped package**: a [peer
2252    /// declaration](super::PeerName) of a [scoped package](ScopedPackageDef)
2253    /// called `name` that this feature expects another feature of the registry to
2254    /// declare with [`scoped_package`](FeatureBuilder::scoped_package). With it,
2255    /// the environment bodies and arguments that this feature declares may refer
2256    /// to the package ([`BodyDef::scoped`](crate::lang::mint::BodyDef::scoped),
2257    /// [`ArgDef::scoped`](crate::lang::mint::ArgDef::scoped)) without this feature
2258    /// depending on the feature that owns it.
2259    ///
2260    /// The declaration registers nothing and counts for this feature alone. When
2261    /// the registry is built, it is resolved against the declarations of every
2262    /// feature:
2263    ///
2264    /// - if a feature declares the package, the bodies and arguments that refer to
2265    ///   it get its definitions, exactly as without the peer declaration;
2266    /// - if none does, the build still succeeds, one Note
2267    ///   ([`UnresolvedPeer`](super::UnresolvedPeer)) joins the registry's [build
2268    ///   diagnostics](super::FlmRegistry::build_diagnostics), and each body or
2269    ///   argument of this feature that refers to the package gets no definition
2270    ///   from it: a command the package would have defined is an unknown command
2271    ///   there, as anywhere else.
2272    ///
2273    /// A scoped package name that no feature declares and that this feature did
2274    /// not declare as a peer remains the build error
2275    /// [`MintError::UnknownScopedPackage`](crate::lang::mint::MintError::UnknownScopedPackage),
2276    /// which catches a misspelled name. See [`PeerName`](super::PeerName) for the
2277    /// other kinds of peer declaration.
2278    ///
2279    /// Declaring the same name again from the same feature has no effect: the
2280    /// repeat is merged into the first declaration, whose `docs` are kept. Two
2281    /// features may each declare the same name.
2282    ///
2283    /// # Errors
2284    ///
2285    /// Never fails; an unresolved declaration is reported as a Note when the
2286    /// registry is built.
2287    pub fn peer_scoped_package(
2288        &mut self,
2289        name: impl Into<Name>,
2290        docs: impl Into<String>,
2291    ) -> Result<(), BuildError> {
2292        self.roster.peer_scoped_packages.push(PeerScopedPackageRecord {
2293            owner: self.feature.clone(),
2294            name: name.into(),
2295            docs: crate::kept_docs(docs),
2296        });
2297        Ok(())
2298    }
2299
2300    /// Registers an [output](OutputDef): a name a caller asks for to have
2301    /// something produced, such as `text` or `html`.
2302    ///
2303    /// # Errors
2304    ///
2305    /// Never fails. An output whose table does not hold an artifact set, or whose
2306    /// capability is neither its table's capability nor a refinement of it, is
2307    /// reported when the registry is built.
2308    pub fn output(&mut self, def: OutputDef) -> Result<(), BuildError> {
2309        self.roster.outputs.push((self.feature.clone(), def));
2310        Ok(())
2311    }
2312
2313    /// Registers a [workflow](WorkflowDef): a named set of demands together with
2314    /// the choices that go with them.
2315    ///
2316    /// # Errors
2317    ///
2318    /// Never fails. A workflow that refers to an output, capability, stage,
2319    /// backend, element or lowering rule that no feature declares, a chain of
2320    /// workflows that leads back to itself, or a render option value whose option
2321    /// type no feature declares or cannot be set on a render request is reported
2322    /// when the registry is built.
2323    pub fn workflow(&mut self, def: WorkflowDef) -> Result<(), BuildError> {
2324        self.roster.workflows.push((self.feature.clone(), def));
2325        Ok(())
2326    }
2327
2328    /// Registers fields for the workflow called `def.name`: every field that
2329    /// `def` declares replaces that field of the workflow a feature registers
2330    /// under that name with [`workflow`](FeatureBuilder::workflow), so that the
2331    /// two make one workflow. When no feature registers a workflow of that name,
2332    /// `def` is the workflow.
2333    ///
2334    /// A field is declared when it is set: `extends` given, a list or a map not
2335    /// empty, `docs` not empty
2336    /// ([`WorkflowDef::replace_declared_fields`]). Fields registered for one name
2337    /// by several features are applied in registration order, the later replacing
2338    /// the earlier, and the fields the embedding program registers with
2339    /// [`RegistryBuilder::workflow_fields`](super::RegistryBuilder::workflow_fields)
2340    /// are applied after all of them. A feature uses this method to change some
2341    /// fields of a workflow without knowing whether another feature registers a
2342    /// workflow of that name.
2343    ///
2344    /// # Errors
2345    ///
2346    /// Never fails; the combined workflow is checked like any other when the
2347    /// registry is built.
2348    pub fn workflow_fields(&mut self, def: WorkflowDef) -> Result<(), BuildError> {
2349        self.roster.workflow_fields.push((self.feature.clone(), def));
2350        Ok(())
2351    }
2352
2353    // --- options and services ---------------------------------------------------------
2354
2355    /// Declares the option type `T`, whose values are set where its binding
2356    /// `bind` allows: on the document, on the render request, on either, or
2357    /// nowhere because the value is fixed when the registry is built (see
2358    /// [`Bind`] and [option types](crate::model::options)).
2359    ///
2360    /// # Errors
2361    ///
2362    /// Never fails. A second declaration of the same option type, or a workflow
2363    /// that sets a value where the binding does not allow it, is reported when
2364    /// the registry is built.
2365    pub fn options<T: Options>(&mut self, bind: Bind) -> Result<(), BuildError> {
2366        self.roster.options.push(OptionDecl::of::<T>(self.feature.clone(), bind));
2367        Ok(())
2368    }
2369
2370    /// Declares the option type `T` with the binding `bind` and with
2371    /// documentation prose; otherwise exactly [`options`](FeatureBuilder::options).
2372    ///
2373    /// # Errors
2374    ///
2375    /// Never fails; problems are reported when the registry is built.
2376    pub fn options_with_docs<T: Options>(
2377        &mut self,
2378        bind: Bind,
2379        docs: impl Into<String>,
2380    ) -> Result<(), BuildError> {
2381        self.roster.options.push(OptionDecl::of::<T>(self.feature.clone(), bind).docs(docs));
2382        Ok(())
2383    }
2384
2385    /// Declares the option type declared from data under the name `name`, with
2386    /// the binding `bind` and the documentation `docs`. Only a
2387    /// [`SettingsDecl`](crate::core::settings::SettingsDecl) declares one
2388    /// ([`config_data`](crate::core::settings::SettingsDecl::config_data),
2389    /// [`options_data`](crate::core::settings::SettingsDecl::options_data)).
2390    ///
2391    /// # Errors
2392    ///
2393    /// Never fails; a second declaration of the same name, by this feature or
2394    /// another, is reported when the registry is built, as for an option type
2395    /// that is a Rust type.
2396    pub(crate) fn options_named(&mut self, name: Name, bind: Bind, docs: String) -> Result<(), BuildError> {
2397        self.roster.options.push(OptionDecl::named(name, self.feature.clone(), bind).docs(docs));
2398        Ok(())
2399    }
2400
2401    /// Declares a [service slot](crate::core::services) called `name`, holding
2402    /// values of type `S` (usually a trait-object type), and taking as many
2403    /// contributions as `arity` allows.
2404    ///
2405    /// A service is a value that can be shared across threads which one feature
2406    /// supplies for another feature, or for the embedding program, to use. By
2407    /// declaring a service slot, a feature states that something it needs is to be
2408    /// supplied from outside the feature, by another feature or by the embedding
2409    /// program.
2410    ///
2411    /// # Errors
2412    ///
2413    /// [`BuildError::ContributionAfterAssembly`] when called from a
2414    /// [`Finalizer`]: the build assembles the service slots between the two
2415    /// registration rounds, and they cannot change afterwards.
2416    pub fn service_slot<S: ?Sized + Any + Send + Sync>(
2417        &mut self,
2418        name: impl Into<Name>,
2419        arity: Arity,
2420        docs: impl Into<String>,
2421    ) -> Result<(), BuildError> {
2422        self.round_one_only(RoundTwoAction::DeclareSlot)?;
2423        self.roster.slots.push(SlotDecl {
2424            name: name.into(),
2425            ty: TypeKey::of::<S>(),
2426            arity,
2427            owner: self.feature.clone(),
2428            docs: crate::kept_docs(docs),
2429        });
2430        Ok(())
2431    }
2432
2433    fn contribute_inner<S: ?Sized + Any + Send + Sync>(
2434        &mut self,
2435        target: SlotTarget,
2436        imp: Arc<S>,
2437        prepend: bool,
2438    ) -> Result<(), BuildError> {
2439        self.round_one_only(RoundTwoAction::Contribute)?;
2440        self.roster.contributions.push(Contribution::new(
2441            self.feature.clone(),
2442            target,
2443            imp,
2444            prepend,
2445        ));
2446        Ok(())
2447    }
2448
2449    /// Contributes `imp` to the service slot whose value type is `S`, after every
2450    /// contribution already made to it.
2451    ///
2452    /// # Errors
2453    ///
2454    /// [`BuildError::ContributionAfterAssembly`] when called from a
2455    /// [`Finalizer`].
2456    pub fn contribute<S: ?Sized + Any + Send + Sync>(
2457        &mut self,
2458        imp: Arc<S>,
2459    ) -> Result<(), BuildError> {
2460        self.contribute_inner(SlotTarget::ByType(TypeKey::of::<S>()), imp, false)
2461    }
2462
2463    /// Contributes `imp` to the service slot called `slot`, after every
2464    /// contribution already made to it.
2465    ///
2466    /// When no feature declares that service slot, the registry build fails. For
2467    /// a service slot that another feature owns and that may be absent, use
2468    /// [`peer_slot`](FeatureBuilder::peer_slot) instead.
2469    ///
2470    /// # Errors
2471    ///
2472    /// [`BuildError::ContributionAfterAssembly`] when called from a
2473    /// [`Finalizer`].
2474    pub fn contribute_to<S: ?Sized + Any + Send + Sync>(
2475        &mut self,
2476        slot: impl Into<Name>,
2477        imp: Arc<S>,
2478    ) -> Result<(), BuildError> {
2479        self.contribute_inner(SlotTarget::ByName(slot.into()), imp, false)
2480    }
2481
2482    /// Contributes `imp` to the service slot whose value type is `S`, before
2483    /// every contribution appended to it.
2484    ///
2485    /// Order matters for a service slot that takes several contributions and consults
2486    /// them in turn; with this method a feature places its contribution first.
2487    /// Among the contributions placed first this way, a read for precedence
2488    /// takes those of the feature placed last in the feature order first
2489    /// ([`Services::services_by_precedence_named`](crate::core::services::Services::services_by_precedence_named)).
2490    ///
2491    /// # Errors
2492    ///
2493    /// [`BuildError::ContributionAfterAssembly`] when called from a
2494    /// [`Finalizer`].
2495    pub fn contribute_first<S: ?Sized + Any + Send + Sync>(
2496        &mut self,
2497        imp: Arc<S>,
2498    ) -> Result<(), BuildError> {
2499        self.contribute_inner(SlotTarget::ByType(TypeKey::of::<S>()), imp, true)
2500    }
2501
2502    /// Contributes `imp` to the service slot called `slot`, before every
2503    /// contribution appended to it. Among the contributions placed first this
2504    /// way, a read for precedence takes those of the feature placed last in the
2505    /// feature order first
2506    /// ([`Services::services_by_precedence_named`](crate::core::services::Services::services_by_precedence_named)).
2507    ///
2508    /// # Errors
2509    ///
2510    /// [`BuildError::ContributionAfterAssembly`] when called from a
2511    /// [`Finalizer`].
2512    pub fn contribute_first_to<S: ?Sized + Any + Send + Sync>(
2513        &mut self,
2514        slot: impl Into<Name>,
2515        imp: Arc<S>,
2516    ) -> Result<(), BuildError> {
2517        self.contribute_inner(SlotTarget::ByName(slot.into()), imp, true)
2518    }
2519
2520    /// Makes a **peer contribution**: contributes `imp` to the service slot
2521    /// called `slot`, a service slot that another feature of the registry is
2522    /// expected to declare. A feature uses it to offer a value to a feature that may not be
2523    /// registered. This is the service-slot form of a [peer
2524    /// declaration](super::PeerName).
2525    ///
2526    /// [`contribute_to`](FeatureBuilder::contribute_to) is the form for a service
2527    /// slot this feature owns, or one it knows is declared: contributing to a
2528    /// service slot that no feature declares is then a registry build error
2529    /// ([`ServiceError::UndeclaredSlot`]), which catches a misspelled name. With
2530    /// this method, the service slot belongs to another feature:
2531    ///
2532    /// - if a feature declares the service slot, the value fills it exactly as
2533    ///   [`contribute_to`](FeatureBuilder::contribute_to) would, after every
2534    ///   contribution already made, and with its type checked against the
2535    ///   service slot's value type;
2536    /// - if no feature declares it, the value is dropped, the build still
2537    ///   succeeds, and one Note ([`UnresolvedPeer`](super::UnresolvedPeer)) joins
2538    ///   the registry's [build diagnostics](super::FlmRegistry::build_diagnostics),
2539    ///   one per feature and service slot, however many values this feature
2540    ///   offered to that service slot.
2541    ///
2542    /// The value type `S` is the declaration's signature, written as the type the
2543    /// service slot declares: a trait-object type, as in
2544    /// `b.peer_slot::<dyn Greeter>(…)`, when the value is behavior. A value of
2545    /// another type than the service slot declares
2546    /// is refused, as it is through
2547    /// [`contribute_to`](FeatureBuilder::contribute_to).
2548    ///
2549    /// Every peer contribution, resolved or not, is listed on the finished
2550    /// registry ([`FlmRegistry::peer_slots`](super::FlmRegistry::peer_slots)), so a
2551    /// misspelled service slot name can be found on any registry that holds the feature.
2552    ///
2553    /// # Errors
2554    ///
2555    /// [`BuildError::ContributionAfterAssembly`] when called from a
2556    /// [`Finalizer`]: the build assembles the service slots between the two
2557    /// registration rounds, and they cannot change afterwards.
2558    pub fn peer_slot<S: ?Sized + Any + Send + Sync>(
2559        &mut self,
2560        slot: impl Into<Name>,
2561        imp: Arc<S>,
2562    ) -> Result<(), BuildError> {
2563        self.round_one_only(RoundTwoAction::Contribute)?;
2564        self.roster.contributions.push(
2565            Contribution::new(self.feature.clone(), SlotTarget::ByName(slot.into()), imp, false)
2566                .as_peer(),
2567        );
2568        Ok(())
2569    }
2570
2571    /// Declares that this feature cannot work unless the service slot whose value
2572    /// type is `S` is filled.
2573    ///
2574    /// A required service slot that is not filled makes the registry build fail, so a
2575    /// missing service is reported once, when the registry is built, instead of
2576    /// as a failure in the middle of processing a document.
2577    ///
2578    /// # Errors
2579    ///
2580    /// [`BuildError::ContributionAfterAssembly`] when called from a
2581    /// [`Finalizer`].
2582    pub fn require_service<S: ?Sized + Any + Send + Sync>(&mut self) -> Result<(), BuildError> {
2583        self.round_one_only(RoundTwoAction::RequireSlot)?;
2584        self.roster.requirements.push(ServiceRequirement {
2585            owner: self.feature.clone(),
2586            target: SlotTarget::ByType(TypeKey::of::<S>()),
2587        });
2588        Ok(())
2589    }
2590
2591    /// Declares that this feature cannot work unless the service slot called
2592    /// `slot` is filled; otherwise exactly
2593    /// [`require_service`](FeatureBuilder::require_service).
2594    ///
2595    /// # Errors
2596    ///
2597    /// [`BuildError::ContributionAfterAssembly`] when called from a
2598    /// [`Finalizer`].
2599    pub fn require_service_named(&mut self, slot: impl Into<Name>) -> Result<(), BuildError> {
2600        self.round_one_only(RoundTwoAction::RequireSlot)?;
2601        self.roster.requirements.push(ServiceRequirement {
2602            owner: self.feature.clone(),
2603            target: SlotTarget::ByName(slot.into()),
2604        });
2605        Ok(())
2606    }
2607
2608    // --- hooks and records ------------------------------------------------------------
2609
2610    /// Registers a [`Finalizer`] of this feature: a build hook that runs in the
2611    /// build's second registration round, once the service slots are assembled.
2612    ///
2613    /// A feature may register several finalizers; they run in the order
2614    /// registered.
2615    ///
2616    /// # Errors
2617    ///
2618    /// [`BuildError::ContributionAfterAssembly`] when called from a
2619    /// [`Finalizer`]: there are exactly two rounds, so a finalizer cannot add a
2620    /// third.
2621    pub fn finalizer(&mut self, finalizer: Arc<dyn Finalizer>) -> Result<(), BuildError> {
2622        self.round_one_only(RoundTwoAction::RegisterFinalizer)?;
2623        self.roster.finalizers.push((self.feature.clone(), finalizer));
2624        Ok(())
2625    }
2626
2627    /// Registers a [`LateInit`] hook of this feature: a build hook that runs once
2628    /// the FLM language is built, for example to compile the templates the
2629    /// feature's configuration holds.
2630    ///
2631    /// Unlike [`finalizer`](FeatureBuilder::finalizer), this method may be called
2632    /// in either round.
2633    ///
2634    /// # Errors
2635    ///
2636    /// Never fails. A failure of the hook itself makes the build fail in the
2637    /// late-initialization phase.
2638    pub fn late_init(&mut self, hook: Arc<dyn LateInit>) -> Result<(), BuildError> {
2639        self.roster.late_inits.push((self.feature.clone(), hook));
2640        Ok(())
2641    }
2642
2643    /// Records a [style definition](StyleDef) in the registry: a stylesheet that
2644    /// a feature's output depends on, under an identifier.
2645    ///
2646    /// A lowering rule or an emitter then requires the definition by its
2647    /// identifier where its output needs it; the backend that writes the output
2648    /// resolves the identifier against the definitions recorded here.
2649    ///
2650    /// # Errors
2651    ///
2652    /// Never fails.
2653    pub fn style_def(&mut self, mut def: StyleDef) -> Result<(), BuildError> {
2654        def.docs = crate::kept_docs(def.docs);
2655        self.roster.styles.push((self.feature.clone(), def));
2656        Ok(())
2657    }
2658
2659    /// Records a [script definition](ScriptDef) in the registry: the counterpart
2660    /// of [`style_def`](FeatureBuilder::style_def) for scripts.
2661    ///
2662    /// # Errors
2663    ///
2664    /// Never fails.
2665    pub fn script_def(&mut self, mut def: ScriptDef) -> Result<(), BuildError> {
2666        def.docs = crate::kept_docs(def.docs);
2667        self.roster.scripts.push((self.feature.clone(), def));
2668        Ok(())
2669    }
2670
2671    /// Gives `bytes` as an input of the [registry digest](crate::model::digest),
2672    /// the number that stands for everything about a registry that can change
2673    /// what processing produces.
2674    ///
2675    /// The build computes the digest from the declarations it can enumerate. A
2676    /// feature's configuration may hold other data that changes what processing
2677    /// produces (for example, the text of an author-written template), which the
2678    /// build cannot see. The feature gives that data here, so that data cached
2679    /// under the digest is not reused after the configuration changes.
2680    ///
2681    /// # Errors
2682    ///
2683    /// Never fails.
2684    pub fn digest_input(&mut self, bytes: &[u8]) -> Result<(), BuildError> {
2685        self.roster
2686            .digest_inputs
2687            .push(DigestInput { owner: self.feature.clone(), bytes: bytes.to_vec() });
2688        Ok(())
2689    }
2690}
2691
2692impl fmt::Debug for FeatureBuilder<'_> {
2693    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2694        f.debug_struct("FeatureBuilder")
2695            .field("feature", &self.feature)
2696            .field("round", &self.round)
2697            .finish()
2698    }
2699}
2700
2701/// The feature name that represents the embedding program itself.
2702///
2703/// Service contributions made through
2704/// [`RegistryBuilder::contribute`](super::RegistryBuilder::contribute) and
2705/// [`RegistryBuilder::contribute_to`](super::RegistryBuilder::contribute_to),
2706/// and workflow fields given through
2707/// [`RegistryBuilder::workflow_fields`](super::RegistryBuilder::workflow_fields),
2708/// come from no feature; they are attributed to this name, so that every
2709/// contribution has an owner to show in a message. The leading underscore
2710/// keeps it apart from the dotted lowercase names of features.
2711pub const HOST_FEATURE: &str = "_host";