flm_core/core/registry/build.rs
1//! The registry build: [`RegistryBuilder`] collects the features a registry
2//! is built from, together with the embedding program's own service
3//! contributions and workflow fields, and [`RegistryBuilder::build`] checks
4//! all their declarations against each other and freezes the result into an
5//! [`FlmRegistry`].
6//!
7//! # The five phases
8//!
9//! A build runs in five phases. Each phase collects every problem it finds
10//! before the build stops:
11//!
12//! 1. **Collect.** The features take their final order: the build reduces
13//! the chains of the feature order to the features it holds and sorts the
14//! features by them, breaking ties by the order in which the features were
15//! added ([`super::order`]); chains that order a feature before itself are
16//! an error ([`BuildError::FeatureOrderCycle`]), and the features then keep
17//! the order in which they were added. Then every feature's
18//! [`register`](super::FlmFeature::register) method runs, in that order,
19//! and records its declarations in the collected declarations
20//! ([`Roster`]). Before a feature's `register` method runs, the build
21//! declares the option types that the feature's
22//! [`settings`](super::FlmFeature::settings) declaration lists; an error
23//! there is recorded like an error that `register` returns. Then the build
24//! assembles the service slots from the declared service slots, the
25//! contributions to them and the requirements that they be filled.
26//! 2. **Finalize.** Every [`Finalizer`](super::Finalizer) that a feature
27//! registered runs. A finalizer can read the assembled services and
28//! declare further entities derived from what other features contributed.
29//! 3. **Validate.** The build drops the members added to collections that no
30//! feature declares, and applies the fields registered for workflows by
31//! name. It checks the documentation texts of element types
32//! ([`FeatureBuilder::element_type_text`](super::FeatureBuilder::element_type_text)):
33//! a text from a feature that does not declare the type, and a second text
34//! for one type, are errors. It resolves the [peer
35//! declarations](super::PeerName): a signature mismatch is an error; an
36//! unresolved declaration is a Note ([`UnresolvedPeer`]) among the build
37//! diagnostics; the lowering rules that depend on it are set aside
38//! (excluded from rule selection; see [`PeerName`]), and a stage that
39//! writes an unresolved peer table is not registered. Then the checks over
40//! all the collected declarations run, and the aspects that features
41//! attach to other features' elements are merged into the element values.
42//! Finally, every backend's native set is checked against the declared
43//! [native-set implications](super::NativeImplication), with the merged
44//! aspects.
45//! 4. **Language.** The build creates the language that documents are parsed
46//! with (the commands and their syntax, and the parsing settings;
47//! [`FlmRegistry::lang`]) from the element, fallback, scoped-package and
48//! override declarations.
49//! 5. **Late initialization.** Every [`LateInit`](super::LateInit) hook runs
50//! with the finished language. A hook that cannot do its work returns an
51//! error, and the phase fails with one [`BuildError::LateInit`] per such
52//! hook. A problem the hook reports about the configuration it prepares (for
53//! example, a template that does not parse) does not fail the build: it
54//! joins the registry's build diagnostics, which
55//! [`FlmRegistry::build_diagnostics`] returns.
56//!
57//! The build then computes the [registry digest](crate::model::digest) and
58//! numbers the collected declarations into the frozen [`FlmRegistry`]. The
59//! numbering can still find a reference that the checks let through; such an
60//! error is reported under [`BuildPhase::Validate`].
61//!
62//! # Why a failing phase stops the build
63//!
64//! A phase that finds problems stops the build, and the phases after it do
65//! not run. A later phase working on unsound declarations would report the
66//! consequences of the earlier problems as problems of their own: for
67//! example, a feature that failed to register leaves every reference to its
68//! entities undeclared. The author would then read many consequences instead of the
69//! few real problems. Within one phase, every error is collected and
70//! reported together ([`RegistryBuildError`]), so one build shows every
71//! problem of that phase. As a consequence, a problem that a later phase
72//! would find is reported only once the problems of the earlier phases are
73//! fixed.
74//!
75//! See also [`super::builder`] for the methods a feature declares through,
76//! [`super::frozen`] for what the finished registry offers, and
77//! [`crate::model::digest`] for the digest.
78
79use std::collections::{BTreeMap, BTreeSet};
80use std::fmt;
81use std::sync::Arc;
82
83use crate::lang::input::InputResolver;
84use techy::error::{Diagnostic, DiagnosticInfo};
85use techy::source::{Source, SourceSpan};
86
87use crate::model::element::ElementSpec;
88use crate::model::names::{CapName, Name, StageName};
89use crate::model::names::FeatureName;
90use crate::lang::{FlmSource, FlmSpan};
91use crate::core::registry::builder::{BuildError, FeatureBuilder, HOST_FEATURE, Roster};
92use crate::model::digest::Fnv1a64;
93use crate::core::registry::feature::{FlmFeature, PackageEntry};
94use crate::core::registry::order::{self, FeatureChain};
95use crate::core::registry::entities::{PeerName, WorkflowDef};
96use crate::core::registry::frozen::FlmRegistry;
97use crate::core::registry::validate;
98use crate::core::services::{Contribution, SlotTarget};
99use crate::lang::guard::GuardPolicy;
100use crate::lang::mint::{ArgDef, BodyDef, ElementDef, SyntaxDef};
101use crate::lang::origin::FlmOrigin;
102use crate::lang::rules::FlmParsing;
103use crate::lang::structural::{self, StructuralElementSpecs, StructuralElements};
104use crate::lang::{FlmDiagnostics, FlmEvent, LangInputs, build_language};
105
106/// Everything a registry build takes besides the features: how source text is
107/// parsed, which structural elements the language starts from, the limits on
108/// recursion and diagnostics, how `\input` finds files, and the identity of the
109/// program.
110///
111/// The features decide what a registry can do; these inputs decide the
112/// setting in which the features are built. Start from [`RegistryInputs::new`],
113/// which sets every field to its default, change only the fields the program
114/// needs, and pass the value to [`RegistryBuilder::build`].
115///
116/// # Examples
117///
118/// ```
119/// use flm_core::core::registry::RegistryInputs;
120///
121/// let mut inputs = RegistryInputs::new();
122/// inputs.build_identity = Some("my-program 2.1".to_string());
123/// inputs.diagnostics_limit = Some(200);
124/// ```
125pub struct RegistryInputs {
126 /// The settings that decide how source text is split into tokens: whether
127 /// comments are recognized and which character starts one, and whether
128 /// `$` delimits mathematics.
129 pub parsing: FlmParsing,
130 /// The structural elements the language starts from, before features
131 /// attach aspects to them. The structural elements are the elements of
132 /// the node forms that no feature declares, such as text, groups and
133 /// paragraphs ([`StructuralElements`]).
134 pub structural: StructuralElementSpecs,
135 /// The policy of the recursion guard, which stops a parse or a tree
136 /// traversal that nests too deeply ([`crate::lang::guard`]).
137 pub guard: GuardPolicy,
138 /// The number of diagnostics one parse keeps; `None` keeps the default
139 /// limit of techy, the parsing library FLM is built on.
140 ///
141 /// The registry's build diagnostics (what the late-initialization hooks
142 /// report about the configuration they prepare) are a separate collection,
143 /// which always keeps techy's default limit.
144 pub diagnostics_limit: Option<usize>,
145 /// The input resolver used by every parse under this registry: the host's
146 /// implementation that finds and reads the file an `\input` command refers
147 /// to ([`crate::lang::input`]). The library performs no input or output of
148 /// its own, so a host that wants `\input` to work supplies a resolver, here
149 /// or for one assembly ([`assemble`](crate::model::assemble::assemble)).
150 /// With `None`, no file is included.
151 pub input_resolver: Option<Arc<dyn InputResolver>>,
152 /// A string that identifies the program this registry is built into, such
153 /// as its version or a hash of its binary.
154 ///
155 /// It is an input of the [registry digest](crate::model::digest), so a
156 /// cache that one program writes to disk is never read back by another.
157 /// Two programs can register the same features and still behave
158 /// differently, because a feature's behavior is code; the digest compares
159 /// declarations but not code, and this string represents the difference.
160 pub build_identity: Option<String>,
161}
162
163impl RegistryInputs {
164 /// Inputs with every field at its default: techy's default parsing
165 /// settings, the standard structural elements, the stack-budget guard
166 /// policy ([`GuardPolicy::StackBudget`]), techy's default diagnostics
167 /// limit, no input resolver and no build identity.
168 pub fn new() -> RegistryInputs {
169 RegistryInputs {
170 parsing: FlmParsing::default(),
171 structural: StructuralElementSpecs::default(),
172 guard: GuardPolicy::StackBudget,
173 diagnostics_limit: None,
174 input_resolver: None,
175 build_identity: None,
176 }
177 }
178}
179
180impl Default for RegistryInputs {
181 fn default() -> RegistryInputs {
182 RegistryInputs::new()
183 }
184}
185
186impl fmt::Debug for RegistryInputs {
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 f.debug_struct("RegistryInputs")
189 .field("parsing", &self.parsing)
190 .field("guard", &self.guard)
191 .field("diagnostics_limit", &self.diagnostics_limit)
192 .field("build_identity", &self.build_identity)
193 .finish_non_exhaustive()
194 }
195}
196
197/// A phase of the registry build: the one that failed, in a
198/// [`RegistryBuildError`]. The [module documentation](self) describes what
199/// each phase does.
200///
201/// `Display` writes the phase as the lowercase word used in the message of a
202/// [`RegistryBuildError`].
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub enum BuildPhase {
205 /// The features take their final order, they register (the first
206 /// registration round), and the service slots are assembled.
207 Collect,
208 /// The finalizers run (the second registration round).
209 Finalize,
210 /// The peer declarations are resolved, the checks over all the collected
211 /// declarations run, and the aspect attachments are merged. An error found
212 /// later, when the declarations are numbered after the late-initialization
213 /// phase, is also reported under this phase.
214 Validate,
215 /// The language that documents are parsed with
216 /// ([`FlmRegistry::lang`]) is built from the element declarations.
217 Language,
218 /// The late-initialization hooks run with the finished language.
219 LateInit,
220}
221
222impl fmt::Display for BuildPhase {
223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 f.write_str(match self {
225 BuildPhase::Collect => "collect",
226 BuildPhase::Finalize => "finalize",
227 BuildPhase::Validate => "validate",
228 BuildPhase::Language => "language",
229 BuildPhase::LateInit => "late-init",
230 })
231 }
232}
233
234/// The error of a failed registry build: the phase that failed, and every
235/// error that phase found.
236///
237/// A phase does not stop at its first problem, so `errors` usually holds
238/// several entries and one build shows every problem of the failing phase.
239/// The phases after it did not run, so the problems they would have found are
240/// not listed; the [module documentation](self) explains why.
241#[derive(Debug, Clone)]
242pub struct RegistryBuildError {
243 /// The phase that failed.
244 pub phase: BuildPhase,
245 /// Its errors, in the order they were found.
246 pub errors: Vec<BuildError>,
247}
248
249impl RegistryBuildError {
250 /// The errors as text, one per line, without the first line that
251 /// `Display` adds. Two builds that find the same problems return the same
252 /// text, so a test compares against this text.
253 pub fn render(&self) -> String {
254 self.errors.iter().map(|e| e.to_string()).collect::<Vec<_>>().join("\n")
255 }
256}
257
258impl fmt::Display for RegistryBuildError {
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260 write!(
261 f,
262 "the registry could not be built: the {} phase found {} error(s):\n{}",
263 self.phase,
264 self.errors.len(),
265 self.render()
266 )
267 }
268}
269
270impl std::error::Error for RegistryBuildError {}
271
272/// The builder of a registry: it collects the features a registry is to be
273/// built from, then builds the registry.
274///
275/// Add features one at a time with [`feature`](RegistryBuilder::feature), or a
276/// whole package at once with [`use_package`](RegistryBuilder::use_package).
277/// Add the chains of the feature order that the embedding program states with
278/// [`feature_order`](RegistryBuilder::feature_order).
279/// Add the embedding program's own contributions to service slots with
280/// [`contribute`](RegistryBuilder::contribute) and
281/// [`contribute_to`](RegistryBuilder::contribute_to), and the workflow fields it
282/// sets with [`workflow_fields`](RegistryBuilder::workflow_fields). Nothing is
283/// checked while the builder collects: [`build`](RegistryBuilder::build) runs
284/// every check.
285///
286/// For a plain list of features and default inputs, call [`build_registry`]
287/// instead.
288///
289/// # Examples
290///
291/// ```
292/// use std::sync::Arc;
293/// use flm_core::core::registry::{
294/// BuildError, FeatureBuilder, FeatureInfo, FlmFeature, RegistryBuilder, RegistryInputs,
295/// };
296///
297/// struct Empty;
298/// impl FlmFeature for Empty {
299/// fn info(&self) -> FeatureInfo { FeatureInfo::new("empty", "Empty") }
300/// fn register(&self, _b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> { Ok(()) }
301/// }
302///
303/// let mut builder = RegistryBuilder::new();
304/// builder.feature(Arc::new(Empty));
305/// let registry = builder.build(&RegistryInputs::new())?;
306/// assert!(registry.has_feature("empty"));
307/// # Ok::<(), flm_core::core::registry::RegistryBuildError>(())
308/// ```
309#[derive(Default)]
310pub struct RegistryBuilder {
311 packages_seen: BTreeSet<Name>,
312 features: Vec<Arc<dyn FlmFeature>>,
313 feature_order: Vec<FeatureChain>,
314 contributions: Vec<Contribution>,
315 workflow_fields: Vec<WorkflowDef>,
316}
317
318impl RegistryBuilder {
319 /// A builder that holds no feature, no chain of the feature order, no
320 /// contribution and no workflow field.
321 pub fn new() -> RegistryBuilder {
322 RegistryBuilder::default()
323 }
324
325 /// Adds a package's features: first those of the packages it uses, then its
326 /// own, each in the order the package lists them. Returns `&mut self`, for
327 /// chaining.
328 ///
329 /// The chains of the feature order that each of these packages states
330 /// ([`PackageEntry::feature_order`]) are added with its features, in the
331 /// same order. The builder skips a package whose name it has already
332 /// added, however often the package is passed here or used by other
333 /// packages, so no package's features or chains are added twice.
334 pub fn use_package(&mut self, entry: PackageEntry) -> &mut RegistryBuilder {
335 if !self.packages_seen.insert(entry.name.clone()) {
336 return self;
337 }
338 for used in entry.uses {
339 self.use_package(used);
340 }
341 self.features.extend(entry.features);
342 self.feature_order.extend(entry.feature_order);
343 self
344 }
345
346 /// Adds one feature, after the features already added. Returns
347 /// `&mut self`, for chaining.
348 ///
349 /// This method accepts two features of the same name; the build then
350 /// fails with [`BuildError::DuplicateFeature`].
351 pub fn feature(&mut self, feature: Arc<dyn FlmFeature>) -> &mut RegistryBuilder {
352 self.features.push(feature);
353 self
354 }
355
356 /// Adds one chain of the feature order on behalf of the embedding program,
357 /// such as a chain a document states. Returns `&mut self`, for chaining.
358 ///
359 /// The build combines the chains given here with those of the packages
360 /// ([`PackageEntry::feature_order`]) and places the features in their
361 /// final order before they register ([`super::order`]). A chain may name
362 /// features that the registry does not hold: the build ignores those
363 /// names.
364 ///
365 /// # Examples
366 ///
367 /// ```
368 /// use flm_core::core::registry::{FeatureChain, RegistryBuilder};
369 ///
370 /// let mut builder = RegistryBuilder::new();
371 /// builder.feature_order(FeatureChain::parse(
372 /// "mymacros < userdefs",
373 /// "front matter of doc.flm, line 4",
374 /// )?);
375 /// # Ok::<(), flm_core::core::registry::ChainError>(())
376 /// ```
377 pub fn feature_order(&mut self, chain: FeatureChain) -> &mut RegistryBuilder {
378 self.feature_order.push(chain);
379 self
380 }
381
382 /// Contributes `imp` to the [service slot](crate::core::services) whose
383 /// value type is `S`, on behalf of the embedding program instead of a
384 /// feature. Returns `&mut self`, for chaining.
385 ///
386 /// With this method, a host supplies an implementation that a feature
387 /// declared a service slot for and left to the embedding program, for example to
388 /// read files or to fetch the data at an address. The contribution is
389 /// attributed to [`HOST_FEATURE`] and comes after every contribution of a
390 /// feature.
391 ///
392 /// Use [`contribute_to`](RegistryBuilder::contribute_to) to give the service
393 /// slot by name instead of by value type.
394 pub fn contribute<S: ?Sized + std::any::Any + Send + Sync>(
395 &mut self,
396 imp: Arc<S>,
397 ) -> &mut RegistryBuilder {
398 self.contributions.push(Contribution::new(
399 HOST_FEATURE,
400 SlotTarget::ByType(crate::model::options::TypeKey::of::<S>()),
401 imp,
402 false,
403 ));
404 self
405 }
406
407 /// Contributes `imp` to the [service slot](crate::core::services) called
408 /// `slot`, on behalf of the embedding program. Returns `&mut self`, for
409 /// chaining.
410 ///
411 /// This method does what [`contribute`](RegistryBuilder::contribute) does,
412 /// for a service slot given by name instead of by value type.
413 pub fn contribute_to<S: ?Sized + std::any::Any + Send + Sync>(
414 &mut self,
415 slot: impl Into<Name>,
416 imp: Arc<S>,
417 ) -> &mut RegistryBuilder {
418 self.contributions.push(Contribution::new(
419 HOST_FEATURE,
420 SlotTarget::ByName(slot.into()),
421 imp,
422 false,
423 ));
424 self
425 }
426
427 /// Registers fields for the [workflow](WorkflowDef) called `def.name`, on
428 /// behalf of the embedding program instead of a feature. Returns
429 /// `&mut self`, for chaining.
430 ///
431 /// The build applies these fields as it applies those a feature registers
432 /// with [`FeatureBuilder::workflow_fields`], and after all of them: every
433 /// field that `def` declares replaces that field of the workflow of that
434 /// name, and when no feature registers a workflow of that name, `def` is
435 /// the workflow, attributed to [`HOST_FEATURE`]. A host that combines
436 /// settings from several sources of its own (for example, files of
437 /// settings that can change a workflow) uses this method to give the
438 /// library the resulting fields, once per workflow, without knowing
439 /// whether a feature registers a workflow of that name.
440 pub fn workflow_fields(&mut self, def: WorkflowDef) -> &mut RegistryBuilder {
441 self.workflow_fields.push(def);
442 self
443 }
444
445 /// Builds the registry from the collected features and the `inputs`, and
446 /// returns the frozen registry, ready to be shared by any number of
447 /// documents, plans and runs.
448 ///
449 /// The [module documentation](self) describes the five phases of the
450 /// build.
451 ///
452 /// # Errors
453 ///
454 /// A [`RegistryBuildError`] that gives the first phase that found
455 /// problems and lists every problem that phase found. The phases after it
456 /// did not run.
457 pub fn build(self, inputs: &RegistryInputs) -> Result<Arc<FlmRegistry>, RegistryBuildError> {
458 // A failed phase stops the build: the later phases need a sound roster,
459 // and running them would report the consequences of the earlier errors
460 // as problems of their own.
461 let mut roster = Roster::default();
462
463 // --- phase: collect (round one) --------------------------------------------------
464 // The features first take their final order, which every later step
465 // follows: wherever the registration order picks one of several
466 // competing items of different features (a definition, an element's
467 // owner, a style, the precedence in a slot), the feature placed last
468 // in the order the user states wins.
469 // A cycle is reported with the phase's other errors; the features
470 // then register in their implicit order.
471 let placement = order::place(self.features, &self.feature_order);
472 roster.errors.extend(placement.cycle);
473 for feature in &placement.features {
474 let info = feature.info();
475 let name = info.name.clone();
476 roster.features.push(info);
477 let mut builder = FeatureBuilder::round_one(&mut roster, name.clone());
478 let declared = match feature.settings() {
479 Some(decl) => decl.declare(&mut builder),
480 None => Ok(()),
481 };
482 if let Err(error) = declared.and_then(|()| feature.register(&mut builder)) {
483 roster.errors.push(match error {
484 BuildError::Feature { feature, detail } => {
485 BuildError::Feature { feature, detail }
486 }
487 other => {
488 BuildError::Feature { feature: name.clone(), detail: other.to_string() }
489 }
490 });
491 }
492 }
493 roster.contributions.extend(self.contributions);
494 let mut errors = std::mem::take(&mut roster.errors);
495 let final_order: Vec<FeatureName> = roster.features.iter().map(|info| info.name.clone()).collect();
496 let services = match crate::core::services::assemble(
497 std::mem::take(&mut roster.slots),
498 std::mem::take(&mut roster.contributions),
499 std::mem::take(&mut roster.requirements),
500 &final_order,
501 ) {
502 Ok(services) => Some(services),
503 Err(service_errors) => {
504 errors.extend(service_errors.into_iter().map(BuildError::Service));
505 None
506 }
507 };
508 if !errors.is_empty() {
509 return Err(RegistryBuildError { phase: BuildPhase::Collect, errors });
510 }
511 let services = services.expect("assembled without errors");
512
513 // --- phase: finalize (round two) -------------------------------------------------
514 let finalizers = std::mem::take(&mut roster.finalizers);
515 for (feature, finalizer) in finalizers {
516 let mut builder = FeatureBuilder::round_two(&mut roster, feature.clone(), &services);
517 if let Err(error) = finalizer.finalize(&mut builder) {
518 roster.errors.push(match error {
519 BuildError::ContributionAfterAssembly { feature, action } => {
520 BuildError::ContributionAfterAssembly { feature, action }
521 }
522 BuildError::Feature { feature, detail } => {
523 BuildError::Feature { feature, detail }
524 }
525 other => {
526 BuildError::Feature { feature: feature.clone(), detail: other.to_string() }
527 }
528 });
529 }
530 }
531 let errors = std::mem::take(&mut roster.errors);
532 if !errors.is_empty() {
533 return Err(RegistryBuildError { phase: BuildPhase::Finalize, errors });
534 }
535
536 // --- phase: validate ---------------------------------------------------------------
537 let mut build_diagnostics = FlmDiagnostics::new();
538 drop_members_of_undeclared_collections(&mut roster);
539 roster
540 .workflow_fields
541 .extend(self.workflow_fields.into_iter().map(|def| (FeatureName::from(HOST_FEATURE), def)));
542 apply_workflow_fields(&mut roster);
543 validate::merge_repeated_peers(&mut roster);
544 // The texts of element types are checked against the features that
545 // declare each type, which the peer element values set apart below
546 // do not.
547 let type_text_errors = validate::element_type_texts(&mut roster, &structural::NAMES);
548 // A value of an element type nobody declares is dropped before any
549 // check sees it; one Note per feature and element type.
550 for (feature, element) in validate::resolve_peer_element_values(&mut roster, &structural::NAMES) {
551 let name = PeerName::ElementType(element);
552 build_diagnostics.push(Diagnostic::note(
553 UnresolvedPeer {
554 feature: feature.to_string(),
555 kind: name.kind().to_string(),
556 name: name.name().to_string(),
557 rules: Vec::new(),
558 stages: Vec::new(),
559 },
560 declarations_span(&feature),
561 ));
562 }
563 // The peer declarations are resolved first: which of them stay
564 // unresolved decides which rules are set aside, and the roster-wide
565 // validation accepts a rule's reference to a name its own feature
566 // declared as a peer.
567 let validate::PeerResolution { errors: peer_errors, unresolved, set_aside, set_aside_stages } =
568 validate::resolve_peers(&roster, &structural::NAMES);
569 // A stage set aside is not registered: nothing sees it from here on.
570 // The table it writes is read only by the absent peer, so nothing the
571 // stage would compute is ever read.
572 remove_stages(&mut roster, &set_aside_stages);
573 let mut errors = validate::validate(&roster, &structural::NAMES);
574 errors.extend(peer_errors);
575 errors.extend(type_text_errors);
576 for (feature, name, rules) in unresolved {
577 let stages = set_aside_stages
578 .iter()
579 .filter(|(_, (owner, names))| *owner == feature && names.contains(&name))
580 .map(|(stage, _)| stage.to_string())
581 .collect();
582 build_diagnostics.push(Diagnostic::note(
583 UnresolvedPeer {
584 feature: feature.to_string(),
585 kind: name.kind().to_string(),
586 name: name.name().to_string(),
587 rules: rules.iter().map(ToString::to_string).collect(),
588 stages,
589 },
590 declarations_span(&feature),
591 ));
592 }
593 // The peer contributions were resolved when the slots were assembled,
594 // two phases earlier; the ones that found no slot are reported here,
595 // with the peer declarations they belong beside. One Note per feature
596 // and slot, however many values that feature offered to it: the other
597 // peer declarations get one Note per name because a feature may name
598 // one entity only once, and a slot holding many values must not be
599 // noisier for holding them.
600 let mut noted: BTreeSet<(&FeatureName, &Name)> = BTreeSet::new();
601 for peer in services.peer_contributions().iter().filter(|peer| !peer.resolved) {
602 if !noted.insert((&peer.owner, &peer.slot)) {
603 continue;
604 }
605 let name = PeerName::Slot(peer.slot.clone());
606 build_diagnostics.push(Diagnostic::note(
607 UnresolvedPeer {
608 feature: peer.owner.to_string(),
609 kind: name.kind().to_string(),
610 name: name.name().to_string(),
611 rules: Vec::new(),
612 stages: Vec::new(),
613 },
614 declarations_span(&peer.owner),
615 ));
616 }
617 let structural = match attach_aspects(&mut roster, inputs.structural.clone()) {
618 Ok(structural) => Some(structural),
619 Err(attach_errors) => {
620 errors.extend(attach_errors);
621 None
622 }
623 };
624 if let Some(structural) = &structural {
625 errors.extend(validate::native_implications(&roster, structural));
626 }
627 if !errors.is_empty() {
628 return Err(RegistryBuildError { phase: BuildPhase::Validate, errors });
629 }
630 let structural = Arc::new(structural.expect("attached without errors"));
631
632 // --- phase: the language --------------------------------------------------------------
633 let lang = build_language(LangInputs {
634 elements: roster.elements.clone(),
635 fallbacks: roster.fallbacks.clone(),
636 scoped_packages: roster.scoped_packages.clone(),
637 peer_scoped_packages: roster
638 .peer_scoped_packages
639 .iter()
640 .map(|record| (record.owner.clone(), record.name.clone()))
641 .collect(),
642 overrides: roster.overrides.clone(),
643 explicitly_before: placement.explicitly_before,
644 parsing: inputs.parsing.clone(),
645 structural: Arc::clone(&structural),
646 guard: inputs.guard,
647 diagnostics_limit: inputs.diagnostics_limit,
648 input_resolver: inputs.input_resolver.clone(),
649 });
650 if !lang.is_sound() {
651 return Err(RegistryBuildError {
652 phase: BuildPhase::Language,
653 errors: lang.errors().iter().cloned().map(BuildError::Lang).collect(),
654 });
655 }
656
657 // --- phase: late init ----------------------------------------------------------------
658 let late_inits = std::mem::take(&mut roster.late_inits);
659 let mut errors = Vec::new();
660 for (feature, hook) in late_inits {
661 if let Err(error) = hook.late_init(&lang, &mut build_diagnostics) {
662 errors.push(BuildError::LateInit { feature, detail: error.detail });
663 }
664 }
665 if !errors.is_empty() {
666 return Err(RegistryBuildError { phase: BuildPhase::LateInit, errors });
667 }
668
669 // --- digest and freeze ----------------------------------------------------------------
670 let digest = digest_of_roster(&roster, inputs, &structural);
671 match FlmRegistry::assemble(
672 roster,
673 structural,
674 lang,
675 services,
676 digest,
677 build_diagnostics,
678 set_aside,
679 ) {
680 Ok(registry) => Ok(Arc::new(registry)),
681 Err(errors) => Err(RegistryBuildError { phase: BuildPhase::Validate, errors }),
682 }
683 }
684}
685
686/// Condition `flm.registry.unresolved-peer`: a feature made a [peer
687/// declaration](super::PeerName) of an entity (a backend, a presentation
688/// element, a table, a service slot, a scoped package, an element type or an
689/// argument role) that no feature of the registry declares.
690///
691/// It is a Note among the registry's [build
692/// diagnostics](FlmRegistry::build_diagnostics), never a failure: a feature
693/// that ships a lowering rule for a backend this registry does not hold is
694/// doing something ordinary. A name that stays unresolved on a registry that
695/// does hold the other feature is misspelled in one of the two features.
696///
697/// Recovery: what the build does depends on the kind of entity.
698///
699/// - Every lowering rule of the feature that depends on the name is set aside:
700/// listed on the registry, never selected by a plan and never counted by the
701/// check that a backend can write every element; the rest of the feature
702/// takes part as usual. [`FlmRegistry::set_aside_rules`] lists the rules set
703/// aside. A rule that reads an unresolved peer table only optionally is not
704/// among them: it runs and finds the table absent.
705/// - Every stage of the feature that writes an unresolved peer table is set
706/// aside too, and not registered at all; the Note lists it.
707/// - For an unresolved service slot, every value the feature contributed to it
708/// is dropped, and nothing else changes; one Note covers the service slot, however
709/// many values the feature offered it, and [`FlmRegistry::peer_slots`] lists
710/// every contribution.
711/// - For an unresolved scoped package, every environment body and argument of
712/// the feature that refers to it gets no definitions from it, so a command
713/// the package would define is an unknown command there.
714/// - For an unresolved element type, every value the feature declared of it is
715/// dropped, so its commands are unknown commands; one Note covers the element
716/// type, however many values the feature declared.
717/// - For an unresolved argument role, nothing changes: the feature's arguments
718/// keep the role, of which the registry holds no description.
719///
720/// A registry that holds the missing feature reports nothing and treats the
721/// rules like any other.
722#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
723#[diagnostic(id = "flm.registry.unresolved-peer")]
724pub struct UnresolvedPeer {
725 /// The feature that made the peer declaration.
726 pub feature: String,
727 /// The kind of the entity the declaration refers to: `backend`, `element`,
728 /// `table`, `slot`, `scoped package`, `element type` or `argument role`
729 /// ([`PeerName::kind`]).
730 pub kind: String,
731 /// The name that resolved to nothing.
732 pub name: String,
733 /// The names of the rules of that feature that are set aside because they
734 /// depend on the name, in registration order.
735 pub rules: Vec<String>,
736 /// The names of the stages of that feature that are set aside, and not
737 /// registered, because they write the table of that name; in name order.
738 pub stages: Vec<String>,
739}
740
741impl fmt::Display for UnresolvedPeer {
742 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743 write!(
744 f,
745 "feature `{}` refers to the {} `{}` and expects another feature to declare it, \
746 but no feature of this registry declares it",
747 self.feature, self.kind, self.name
748 )?;
749 // An argument role changes nothing anywhere when it stays unresolved:
750 // the condition is the whole message. The word is the one
751 // `PeerName::kind` gives for `PeerName::ArgumentRole`.
752 if self.kind == "argument role" {
753 return Ok(());
754 }
755 f.write_str("; ")?;
756 // A slot names no rule at all: what happened to the value is what a
757 // reader needs to be told. The word is the one `PeerName::kind` gives
758 // for `PeerName::Slot`.
759 if self.kind == "slot" {
760 return write!(f, "the value contributed to it is dropped");
761 }
762 // A scoped package names no rule either: what the feature's bodies and
763 // arguments naming it see is what a reader needs. The word is the one
764 // `PeerName::kind` gives for `PeerName::ScopedPackage`.
765 if self.kind == "scoped package" {
766 return write!(f, "the environment bodies and arguments that refer to it get no definitions from it");
767 }
768 // An element type names no rule either: the sentence states the
769 // condition the feature's commands need. The word is the one
770 // `PeerName::kind` gives for `PeerName::ElementType`.
771 if self.kind == "element type" {
772 return write!(f, "the feature's commands of that element type are not defined");
773 }
774 // An empty list is the ordinary case for a table only optional reads
775 // name: nothing is set aside, and the sentence says what happens
776 // instead rather than ending in `[]`.
777 if self.rules.is_empty() && self.stages.is_empty() {
778 return write!(f, "no rule of that feature depends on it");
779 }
780 if !self.rules.is_empty() {
781 write!(f, "the rules depending on it are set aside: [{}]", self.rules.join(", "))?;
782 }
783 if !self.stages.is_empty() {
784 if !self.rules.is_empty() {
785 f.write_str("; ")?;
786 }
787 write!(f, "the stages writing it are set aside: [{}]", self.stages.join(", "))?;
788 }
789 Ok(())
790 }
791}
792
793/// Removes from the collected declarations `roster` every stage whose name is
794/// a key of `names`, with every ordering edge placed on it, and updates the
795/// positions of the backends' stages so that they still refer to the same
796/// stages. A backend's own stage is never removed, because it writes its
797/// backend's tables.
798fn remove_stages<T>(roster: &mut Roster, names: &BTreeMap<StageName, T>) {
799 let backend_stages: BTreeSet<usize> = roster
800 .backends
801 .iter()
802 .flat_map(|backend| [backend.lowering, backend.emit, backend.final_stage])
803 .collect();
804 let mut kept_before: Vec<usize> = Vec::with_capacity(roster.stages.len());
805 let mut kept = 0;
806 let mut index = 0;
807 roster.stages.retain(|record| {
808 kept_before.push(kept);
809 let keep = backend_stages.contains(&index) || !names.contains_key(&record.decl.name);
810 index += 1;
811 if keep {
812 kept += 1;
813 }
814 keep
815 });
816 for backend in &mut roster.backends {
817 backend.lowering = kept_before[backend.lowering];
818 backend.emit = kept_before[backend.emit];
819 backend.final_stage = kept_before[backend.final_stage];
820 }
821 let registered: BTreeSet<StageName> = roster.stages.iter().map(|record| record.decl.name.clone()).collect();
822 roster
823 .orderings
824 .retain(|(_, ordering)| registered.contains(&ordering.stage) || !names.contains_key(&ordering.stage));
825}
826
827/// The span that a build diagnostic about the declarations of `feature`
828/// carries: the start of an empty synthetic source whose origin label gives
829/// the feature, because a declaration made in code has no source text.
830fn declarations_span(feature: &FeatureName) -> FlmSpan {
831 let origin = FlmOrigin::synthetic(format!("declarations of feature `{feature}`"));
832 let source: Arc<FlmSource> = Arc::new(Source::new(String::new()).with_origin(origin));
833 SourceSpan::new(&source, 0..0)
834}
835
836/// Applies the fields registered for workflows by name
837/// ([`FeatureBuilder::workflow_fields`](super::FeatureBuilder::workflow_fields),
838/// then [`RegistryBuilder::workflow_fields`]) to the workflows of those names,
839/// in registration order. Fields for a name under which no feature registers
840/// a workflow become that workflow.
841fn apply_workflow_fields(roster: &mut Roster) {
842 for (owner, fields) in std::mem::take(&mut roster.workflow_fields) {
843 match roster.workflows.iter_mut().find(|(_, def)| def.name == fields.name) {
844 Some((_, def)) => def.replace_declared_fields(fields),
845 None => roster.workflows.push((owner, fields)),
846 }
847 }
848}
849
850/// Drops every member added to a collection that no feature of this registry
851/// declares, so that the checks that follow see only members of declared
852/// collections.
853///
854/// No diagnostic is recorded. A feature that ships a check adds it to a
855/// collection another feature declares; dropping the member lets the feature
856/// be registered without the other one, and reporting it would refuse
857/// ordinary registries.
858fn drop_members_of_undeclared_collections(roster: &mut Roster) {
859 let declared: BTreeSet<CapName> =
860 roster.collections.iter().map(|(_, def)| def.name.clone()).collect();
861 roster.members.retain(|(_, collection, _)| declared.contains(collection));
862}
863
864impl fmt::Debug for RegistryBuilder {
865 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
866 f.debug_struct("RegistryBuilder")
867 .field("packages", &self.packages_seen)
868 .field("features", &self.features.iter().map(|x| x.info().name).collect::<Vec<_>>())
869 .field("contributions", &self.contributions.len())
870 .field("workflow_fields", &self.workflow_fields.iter().map(|def| &def.name).collect::<Vec<_>>())
871 .finish()
872 }
873}
874
875/// Merges the aspects that features attach to elements into the element
876/// values themselves, and returns the frozen structural elements.
877///
878/// An element value is shared and immutable, so an aspect cannot be added in
879/// place: every value whose element type has attachments is copied with the
880/// aspects added, and the new shared value replaces the old one everywhere
881/// in the collected declarations `roster`. Values without attachments keep
882/// their identity, so the usual case copies nothing. The aspects of the
883/// structural elements are added to their specifications
884/// (`structural_specs`), before these are frozen.
885///
886/// # Errors
887///
888/// One [`BuildError::AspectCollision`] for each aspect attached to an element
889/// that already carries it, all returned together.
890fn attach_aspects(
891 roster: &mut Roster,
892 mut structural_specs: StructuralElementSpecs,
893) -> Result<StructuralElements, Vec<BuildError>> {
894 let mut errors: Vec<BuildError> = Vec::new();
895 let attachments = std::mem::take(&mut roster.attachments);
896 if attachments.is_empty() {
897 return Ok(StructuralElements::new(structural_specs));
898 }
899
900 // Structural elements: attach on the mutable specs.
901 for attachment in &attachments {
902 if let Some(spec) = structural_specs.get_mut(attachment.element.as_str()) {
903 if spec
904 .aspects
905 .insert_erased(
906 attachment.aspect_id,
907 attachment.aspect_name,
908 Arc::clone(&attachment.imp),
909 )
910 .is_err()
911 {
912 errors.push(BuildError::AspectCollision {
913 feature: attachment.owner.clone(),
914 element: attachment.element.clone(),
915 aspect: attachment.aspect_name,
916 });
917 }
918 }
919 }
920
921 // Feature elements: rebuild the values whose names have attachments.
922 let mut rebuilt: std::collections::BTreeMap<usize, Arc<ElementSpec>> =
923 std::collections::BTreeMap::new();
924 let mut rebuild = |element: &Arc<ElementSpec>, errors: &mut Vec<BuildError>| {
925 let key = Arc::as_ptr(element) as usize;
926 if rebuilt.contains_key(&key) {
927 return;
928 }
929 let mine: Vec<&_> = attachments.iter().filter(|a| a.element == element.name).collect();
930 if mine.is_empty() {
931 return;
932 }
933 let mut spec: ElementSpec = (**element).clone();
934 for attachment in mine {
935 if spec
936 .aspects
937 .insert_erased(
938 attachment.aspect_id,
939 attachment.aspect_name,
940 Arc::clone(&attachment.imp),
941 )
942 .is_err()
943 {
944 errors.push(BuildError::AspectCollision {
945 feature: attachment.owner.clone(),
946 element: attachment.element.clone(),
947 aspect: attachment.aspect_name,
948 });
949 }
950 }
951 rebuilt.insert(key, Arc::new(spec));
952 };
953 for def in &roster.elements {
954 rebuild(&def.element, &mut errors);
955 }
956 for package in &roster.scoped_packages {
957 for def in &package.elements {
958 rebuild(&def.element, &mut errors);
959 }
960 }
961 for fallback in &roster.fallbacks {
962 rebuild(&fallback.element, &mut errors);
963 }
964 for record in &roster.presentation {
965 rebuild(&record.element, &mut errors);
966 }
967 if !errors.is_empty() {
968 return Err(errors);
969 }
970 let rebuilt_of =
971 |element: &Arc<ElementSpec>| rebuilt.get(&(Arc::as_ptr(element) as usize)).map(Arc::clone);
972 let remap = |element: &mut Arc<ElementSpec>| {
973 if let Some(new) = rebuilt_of(element) {
974 *element = new;
975 }
976 };
977 for def in &mut roster.elements {
978 remap(&mut def.element);
979 }
980 for package in &mut roster.scoped_packages {
981 for def in &mut package.elements {
982 remap(&mut def.element);
983 }
984 }
985 for fallback in &mut roster.fallbacks {
986 remap(&mut fallback.element);
987 }
988 for record in &mut roster.presentation {
989 remap(&mut record.element);
990 }
991 Ok(StructuralElements::new(structural_specs))
992}
993
994// The digest is a cache key and a stamp on data a host supplies, so an input left
995// out would let a document be reused under a registry that produces a different
996// tree. A feature feeds in its own configuration as explicit bytes, since a
997// configuration may hold shared pointers, which have no stable hash.
998/// Computes the [registry digest](crate::model::digest): a hash of
999/// everything about this build that can change what processing produces.
1000///
1001/// The inputs, in order: the versions of this crate and of techy, the host's
1002/// build identity, the parsing settings, the structural elements with their
1003/// aspects, every feature's name and version, the element declarations
1004/// (owner, callable names, syntax, element type name, aspects, modes and
1005/// whether the declaration is weak; the
1006/// syntax covers the parser identity, mode, layout, opaque wrapper, scoped
1007/// packages and state events of each argument and body, as [`digest_syntax`]
1008/// lists), the
1009/// fallbacks, the scoped packages, the overrides, the rewrite stages with their
1010/// refinements, the ordering edges, the option declarations, and every
1011/// feature's own digest input. What stages compute and what backends emit are
1012/// not inputs: they follow from these inputs.
1013///
1014/// The only `Debug` texts used as inputs are those of plain derived data
1015/// (techy's parse mode, FLM's state events ([`FlmEvent`]), and the parsing,
1016/// argument-layout and body declarations), never of a value whose `Debug` text could contain a pointer
1017/// address, which would differ between two runs of the same program.
1018fn digest_of_roster(
1019 roster: &Roster,
1020 inputs: &RegistryInputs,
1021 structural: &StructuralElements,
1022) -> u64 {
1023 let mut hasher = Fnv1a64::new();
1024 hasher.write_str(env!("CARGO_PKG_VERSION"));
1025 hasher.write_str(techy::VERSION);
1026 hasher.write_str(inputs.build_identity.as_deref().unwrap_or(""));
1027 hasher.write_str(&format!("{:?}", inputs.parsing));
1028 for element in structural.all() {
1029 hasher.write_str(element.name.as_str());
1030 let mut aspects: Vec<&str> = element.aspects.entries().map(|(_, name, _)| name).collect();
1031 aspects.sort_unstable();
1032 for aspect in aspects {
1033 hasher.write_str(aspect);
1034 }
1035 }
1036 for info in &roster.features {
1037 hasher.write_str(info.name.as_str());
1038 hasher.write_str(info.version.as_deref().unwrap_or(""));
1039 }
1040 let digest_def = |hasher: &mut Fnv1a64, def: &ElementDef| {
1041 hasher.write_str(def.owner.as_str());
1042 for name in &def.names {
1043 hasher.write_str(name.as_str());
1044 }
1045 digest_syntax(hasher, &def.syntax);
1046 hasher.write_str(def.element.name.as_str());
1047 let mut aspects: Vec<&str> =
1048 def.element.aspects.entries().map(|(_, name, _)| name).collect();
1049 aspects.sort_unstable();
1050 for aspect in aspects {
1051 hasher.write_str(aspect);
1052 }
1053 // The mark is appended to the modes' text, in one input.
1054 let weak = if def.weak { " weak" } else { "" };
1055 hasher.write_str(&format!("{:?}{weak}", def.modes));
1056 };
1057 for def in &roster.elements {
1058 digest_def(&mut hasher, def);
1059 }
1060 for fallback in &roster.fallbacks {
1061 hasher.write_str(fallback.owner.as_str());
1062 for mode in &fallback.modes {
1063 hasher.write_str(&format!("{mode:?}"));
1064 }
1065 hasher.write_str(&fallback.kind.to_string());
1066 hasher.write_str(fallback.element.name.as_str());
1067 }
1068 for package in &roster.scoped_packages {
1069 hasher.write_str(package.owner.as_str());
1070 hasher.write_str(package.name.as_str());
1071 for def in &package.elements {
1072 digest_def(&mut hasher, def);
1073 }
1074 }
1075 for over in &roster.overrides {
1076 hasher.write_str(over.owner.as_str());
1077 hasher.write_str(&over.kind.to_string());
1078 hasher.write_str(over.name.as_str());
1079 }
1080 for record in &roster.stages {
1081 if let Some(rewrite) = &record.rewrite {
1082 hasher.write_str(rewrite.name.as_str());
1083 hasher.write_str(rewrite.publishes.as_str());
1084 hasher.write_str(&format!("{:?}", rewrite.refines));
1085 hasher.write_u64(u64::from(rewrite.default));
1086 }
1087 }
1088 for (owner, ordering) in &roster.orderings {
1089 hasher.write_str(owner.as_str());
1090 hasher.write_str(ordering.stage.as_str());
1091 hasher.write_str("after");
1092 for capability in &ordering.after {
1093 hasher.write_str(capability.as_str());
1094 }
1095 hasher.write_str("before");
1096 for capability in &ordering.before {
1097 hasher.write_str(capability.as_str());
1098 }
1099 }
1100 for decl in &roster.options {
1101 decl.key.write_digest(&mut hasher);
1102 hasher.write_str(decl.bind.label());
1103 }
1104 for input in &roster.digest_inputs {
1105 hasher.write_str(input.owner.as_str());
1106 hasher.write_bytes(&input.bytes);
1107 hasher.write_bytes(&[0xfe]);
1108 }
1109 hasher.value()
1110}
1111
1112/// Adds the form of a declared syntax to the digest: its kind, its trigger
1113/// characters where it has some, and for each argument its name, its parser's
1114/// identity ([`FlmArgumentParser::identity`](crate::lang::mint::FlmArgumentParser::identity),
1115/// which for a tack-on argument covers each field's name, arguments and
1116/// repeatability), its mode, its layout, whether it is declared with an
1117/// opaque wrapper, its scoped packages and its state events; and for a body
1118/// its layout, whether
1119/// it is declared with an opaque wrapper, its parser's identity
1120/// ([`FlmBodyParser::identity`](crate::lang::mint::FlmBodyParser::identity)),
1121/// its mode, its scoped packages and its state events. Documentation strings
1122/// change no parse
1123/// and are not inputs.
1124///
1125/// A parser that a feature defines is an input through its identity; what
1126/// its code does beyond that is an input only through the feature's version
1127/// and the host's build identity.
1128fn digest_syntax(hasher: &mut Fnv1a64, syntax: &SyntaxDef) {
1129 match syntax {
1130 SyntaxDef::Macro { args } => {
1131 hasher.write_str("macro");
1132 digest_args(hasher, args);
1133 }
1134 SyntaxDef::Inclusion { args } => {
1135 hasher.write_str("inclusion");
1136 digest_args(hasher, args);
1137 }
1138 SyntaxDef::Environment { args, body } => {
1139 hasher.write_str("environment");
1140 digest_args(hasher, args);
1141 digest_body(hasher, body);
1142 }
1143 SyntaxDef::Specials { trigger, args } => {
1144 hasher.write_str("specials");
1145 hasher.write_str(trigger);
1146 digest_args(hasher, args);
1147 }
1148 SyntaxDef::Synthesized => hasher.write_str("synthesized"),
1149 }
1150}
1151
1152/// Adds a list of arguments to the digest: for each argument, its name, its
1153/// parser's identity (preceded by its length), its mode, its layout, whether
1154/// it is declared with an opaque wrapper, its scoped packages and its state
1155/// events, as [`digest_body`] does for a body; see [`digest_syntax`].
1156fn digest_args(hasher: &mut Fnv1a64, args: &[ArgDef]) {
1157 for arg in args {
1158 hasher.write_str(arg.name.as_deref().unwrap_or(""));
1159 let identity = arg.kind.identity();
1160 hasher.write_u64(identity.len() as u64);
1161 hasher.write_bytes(&identity);
1162 hasher.write_str(&format!("{:?}", arg.mode));
1163 hasher.write_str(&format!("{:?}", arg.layout));
1164 hasher.write_u64(u64::from(arg.opaque_wrapper));
1165 for package in &arg.scoped {
1166 hasher.write_str(package.as_str());
1167 }
1168 digest_events(hasher, &arg.events);
1169 }
1170}
1171
1172/// Adds a body declaration to the digest: its layout, whether it is declared
1173/// with an opaque wrapper, its parser's identity (or the fact that it has
1174/// none), its mode, its scoped packages and its state events; see
1175/// [`digest_syntax`].
1176fn digest_body(hasher: &mut Fnv1a64, body: &BodyDef) {
1177 hasher.write_str(&format!("{:?}", body.layout));
1178 hasher.write_u64(u64::from(body.opaque_wrapper));
1179 match &body.parser {
1180 None => hasher.write_u64(0),
1181 Some(parser) => {
1182 let identity = parser.identity();
1183 hasher.write_u64(1 + identity.len() as u64);
1184 hasher.write_bytes(&identity);
1185 }
1186 }
1187 hasher.write_str(&format!("{:?}", body.mode));
1188 for package in &body.scoped {
1189 hasher.write_str(package.as_str());
1190 }
1191 digest_events(hasher, &body.events);
1192}
1193
1194/// Adds the state events of an argument or a body declaration to the
1195/// digest: their number, then each event, in the order they are declared.
1196fn digest_events(hasher: &mut Fnv1a64, events: &[FlmEvent]) {
1197 hasher.write_u64(events.len() as u64);
1198 for event in events {
1199 hasher.write_str(&format!("{event:?}"));
1200 }
1201}
1202
1203/// Builds a registry from `features` alone, with the default inputs
1204/// ([`RegistryInputs::new`]).
1205///
1206/// This function creates a [`RegistryBuilder`], adds each feature in order
1207/// and calls [`build`](RegistryBuilder::build). Use the builder itself when the
1208/// program has packages to use, service contributions or workflow fields of
1209/// its own to give, or inputs to set.
1210///
1211/// # Errors
1212///
1213/// A [`RegistryBuildError`], exactly as [`RegistryBuilder::build`] reports it.
1214///
1215/// # Examples
1216///
1217/// ```
1218/// use std::sync::Arc;
1219/// use flm_core::core::registry::{
1220/// BuildError, FeatureBuilder, FeatureInfo, FlmFeature, build_registry,
1221/// };
1222///
1223/// struct Empty;
1224/// impl FlmFeature for Empty {
1225/// fn info(&self) -> FeatureInfo { FeatureInfo::new("empty", "Empty") }
1226/// fn register(&self, _b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> { Ok(()) }
1227/// }
1228///
1229/// let registry = build_registry([Arc::new(Empty) as Arc<dyn FlmFeature>])?;
1230/// assert_eq!(registry.features().len(), 1);
1231/// # Ok::<(), flm_core::core::registry::RegistryBuildError>(())
1232/// ```
1233pub fn build_registry(
1234 features: impl IntoIterator<Item = Arc<dyn FlmFeature>>,
1235) -> Result<Arc<FlmRegistry>, RegistryBuildError> {
1236 let mut builder = RegistryBuilder::new();
1237 for feature in features {
1238 builder.feature(feature);
1239 }
1240 builder.build(&RegistryInputs::new())
1241}