flm_core/core/services.rs
1//! Services: values that one feature supplies for another feature, or for the
2//! program embedding the library, to use, and the service slots through which
3//! they are declared, supplied and read.
4//!
5//! A service is a value that can be shared across threads (behavior behind a
6//! trait object, or plain data) which one feature supplies for another
7//! feature, or for the embedding program, to use: something that fetches
8//! citation data, something that renders mathematics, or plain data another
9//! feature reads. A service slot is the declaration, by the feature that owns
10//! an interaction, of a dotted name, the type of the values the slot takes and
11//! its arity (at most one value, or any number, [`Arity`]); any feature, and
12//! the embedding program through the registry builder, may contribute a value
13//! to it, and the registry build assembles all contributions once. A
14//! contribution is a value a feature places in a service slot; a peer
15//! contribution is a contribution to a slot another feature owns, which the
16//! registry build drops with one Note when that feature is not registered.
17//! The section [services and service
18//! slots](crate::guide::concepts_overview#services-and-service-slots) of the
19//! concepts overview relates them to the rest of the library.
20//!
21//! A service slot makes the interaction safe: the feature that needs a service
22//! states what it needs and of which type, instead of checking at run time
23//! whether some other feature is present and then calling a method that may
24//! not exist.
25//!
26//! This module holds the values the registry build records and checks
27//! ([`SlotDecl`], [`Contribution`], [`SlotTarget`], [`ServiceRequirement`]),
28//! the assembly itself ([`assemble`], with its errors [`ServiceError`]), and
29//! the finished, read-only result: [`Services`], with the record of every peer
30//! contribution ([`PeerContribution`]). A feature does not build these values
31//! itself; it calls the methods of the feature builder listed below.
32//!
33//! # Declaring, contributing, reading
34//!
35//! - A feature declares a service slot with
36//! [`FeatureBuilder::service_slot`](crate::core::registry::FeatureBuilder::service_slot).
37//! - A feature contributes a value with
38//! [`FeatureBuilder::contribute`](crate::core::registry::FeatureBuilder::contribute)
39//! (the slot found by the value's type) or
40//! [`FeatureBuilder::contribute_to`](crate::core::registry::FeatureBuilder::contribute_to)
41//! (the slot given by name); the forms `contribute_first` and
42//! `contribute_first_to` place the value ahead of the others in a slot that
43//! takes several. Where a slot's order is a precedence, the values of the
44//! feature placed last in the feature order come first (see [the order of a
45//! slot's values](#the-order-of-a-slots-values)). The embedding program contributes through
46//! [`RegistryBuilder::contribute`](crate::core::registry::RegistryBuilder::contribute)
47//! and
48//! [`RegistryBuilder::contribute_to`](crate::core::registry::RegistryBuilder::contribute_to),
49//! attributed to the name
50//! [`HOST_FEATURE`](crate::core::registry::HOST_FEATURE). The registry build
51//! checks contributions after every feature has registered, so a feature may
52//! contribute to a service slot that a feature registered later declares.
53//! - A contribution to a service slot that no feature declares is a registry
54//! build error, since it usually comes from a misspelled name. A feature that
55//! contributes to a service slot of another feature that may not be
56//! registered uses
57//! [`FeatureBuilder::peer_slot`](crate::core::registry::FeatureBuilder::peer_slot)
58//! instead: that peer contribution is dropped when no feature declares the
59//! slot, and the registry build records one Note. A feature can therefore
60//! offer a value to a feature that may not be registered.
61//! - A stage reads a service from its context, with
62//! [`StageCx::service`](crate::core::run::StageCx::service) for one value and
63//! [`StageCx::services`](crate::core::run::StageCx::services) for all of
64//! them. The read of one value returns an `Option`: an absent service is
65//! never a failure in the middle of a render, and the stage reports the
66//! absence as a diagnostic of its own.
67//! - A feature that cannot work in *any* plan without a service marks the
68//! service slot as required, with [`require_service`][req] (the slot found
69//! by type) or
70//! [`require_service_named`](crate::core::registry::FeatureBuilder::require_service_named);
71//! a required slot that receives no value is then an error of the registry
72//! build. A service that only some plans need stays an ordinary read that
73//! may return `None`, so that a program that never builds such a plan can
74//! still build its registry.
75//!
76//! # Service slots do not change once the registry is built
77//!
78//! [`assemble`] produces the [`Services`] of a registry, and nothing changes
79//! them afterwards: every run shares them, and no service is filled while a
80//! run is under way. A value that exists only after some work has been done
81//! (an index built by scanning a collection of documents, citation data
82//! fetched ahead of time) is not a service but an [external
83//! table](crate::core::run::Externals), installed when a run is constructed. A
84//! value that is empty at one moment and filled at another would make the
85//! result of a run depend on when a stage read it.
86//!
87//! A service implementation may keep state of its own behind a lock, on one
88//! condition: returning a stored result must give the same result as
89//! computing it again. Apart from such caches, nothing that a stage can reach
90//! changes while a run is under way.
91//!
92//! # Finding a service slot by type or by name
93//!
94//! A service slot is stored under its name, and the registry build checks the
95//! type of every contribution against the slot's declared type. A
96//! contribution or a read may still identify the slot by its value type
97//! alone, which works as long as exactly one slot has that type. Where two
98//! slots have the same type, the forms that take the slot's name
99//! ([`Services::service_named`], [`Services::services_named`],
100//! `contribute_to`) select one, and a contribution by type alone is refused
101//! as ambiguous ([`ServiceError::AmbiguousSlot`]). The reads by type alone
102//! take the slots of that type in name order: [`Services::service`] returns
103//! the value that takes precedence in the first such slot that holds one, and
104//! [`Services::services`] every value of every such slot.
105//!
106//! # The order of a slot's values
107//!
108//! A slot that takes several values holds them in two orders, and each read
109//! says which one it gives.
110//!
111//! - The **assembled order** ([`Services::services_named`]): the values
112//! contributed with `contribute_first` or `contribute_first_to` first, then
113//! the others, each group in the order the values were contributed (the
114//! features in their registration order, then the embedding program). A
115//! slot whose values form a list, such as definitions written one after the
116//! other, is read in this order.
117//! - The **order of precedence** ([`Services::services_by_precedence_named`]):
118//! the values contributed with `contribute_first` or `contribute_first_to`
119//! first, then the others; within each of these two groups, the values of
120//! the feature placed last in the feature order first, each feature's values
121//! in the order the feature contributed them, and the embedding program's
122//! values last. A slot whose values are asked in turn until one answers,
123//! such as the citation providers or the image converters, is read in this
124//! order, and the reads of one value ([`Services::service`],
125//! [`Services::service_named`]) give the first value in it: between
126//! features, the feature placed last wins.
127//!
128//! # Examples
129//!
130//! One feature declares a service slot, another feature contributes a value
131//! to it, and the finished registry returns the value:
132//!
133//! ```
134//! use std::sync::Arc;
135//!
136//! use flm_core::core::registry::{
137//! BuildError, FeatureBuilder, FeatureInfo, FlmFeature, build_registry,
138//! };
139//! use flm_core::core::services::Arity;
140//!
141//! // A service is usually behavior behind a trait object.
142//! trait Greeter: Send + Sync {
143//! fn greet(&self) -> String;
144//! }
145//!
146//! struct Hello;
147//! impl Greeter for Hello {
148//! fn greet(&self) -> String {
149//! "hello".to_string()
150//! }
151//! }
152//!
153//! struct Owner;
154//! impl FlmFeature for Owner {
155//! fn info(&self) -> FeatureInfo { FeatureInfo::new("owner", "Owner") }
156//! fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
157//! b.service_slot::<dyn Greeter>("owner.greeter", Arity::Single, "the greeter")
158//! }
159//! }
160//!
161//! struct Filler;
162//! impl FlmFeature for Filler {
163//! fn info(&self) -> FeatureInfo { FeatureInfo::new("filler", "Filler") }
164//! fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
165//! b.contribute_to("owner.greeter", Arc::new(Hello) as Arc<dyn Greeter>)
166//! }
167//! }
168//!
169//! let registry = build_registry([
170//! Arc::new(Owner) as Arc<dyn FlmFeature>,
171//! Arc::new(Filler) as Arc<dyn FlmFeature>,
172//! ])?;
173//!
174//! let greeter =
175//! registry.services().service::<dyn Greeter>().expect("contributed above");
176//! assert_eq!(greeter.greet(), "hello");
177//! # Ok::<(), flm_core::core::registry::RegistryBuildError>(())
178//! ```
179//!
180//! [req]: crate::core::registry::FeatureBuilder::require_service
181
182use std::any::Any;
183use std::cmp::Reverse;
184use std::collections::BTreeMap;
185use std::fmt;
186use std::sync::Arc;
187
188use crate::model::names::{FeatureName, Name};
189use crate::model::options::TypeKey;
190
191/// The arity of a service slot: how many values it takes.
192///
193/// A feature gives it when it declares the slot
194/// ([`FeatureBuilder::service_slot`](crate::core::registry::FeatureBuilder::service_slot)).
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
196pub enum Arity {
197 /// At most one value: the slot may stay empty, and a second contribution
198 /// is a registry build error ([`ServiceError::SingleSlotRefilled`]) that
199 /// identifies both contributing features; neither value replaces the other.
200 Single,
201 /// Any number of values: the values contributed with `contribute_first`
202 /// or `contribute_first_to` come first, then the others, each group in the
203 /// order the values were contributed. A read for precedence orders them
204 /// otherwise within each group (see [the order of a slot's
205 /// values](self#the-order-of-a-slots-values)).
206 OrderedMany,
207}
208
209/// A feature's declaration of one service slot: its name, the type of its
210/// values, its arity and its owner.
211///
212/// [`FeatureBuilder::service_slot`](crate::core::registry::FeatureBuilder::service_slot)
213/// records one; [`Services::slot`] and [`Services::slots`] return them from the
214/// finished registry.
215#[derive(Debug, Clone)]
216pub struct SlotDecl {
217 /// The service slot's dotted name, such as `flm.citations.providers`,
218 /// which stays the same across versions of the feature.
219 pub name: Name,
220 /// The type of the slot's values: usually a trait object type, since a
221 /// service is usually behavior.
222 pub ty: TypeKey,
223 /// How many values the slot takes.
224 pub arity: Arity,
225 /// The feature that declares the slot, and so owns the interaction.
226 pub owner: FeatureName,
227 /// A description of what the slot is for, for a person reading the
228 /// registry; empty when the feature gave none.
229 pub docs: String,
230}
231
232/// How a contribution or a requirement identifies its service slot: by the
233/// slot's value type, or by its name.
234#[derive(Debug, Clone, PartialEq, Eq)]
235pub enum SlotTarget {
236 /// The service slot whose values have this type. It identifies a slot only
237 /// when exactly one declared slot has the type; several such slots are
238 /// reported as [`ServiceError::AmbiguousSlot`], and none is chosen.
239 ByType(TypeKey),
240 /// The service slot with this name, regardless of its type.
241 ByName(Name),
242}
243
244impl fmt::Display for SlotTarget {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246 match self {
247 SlotTarget::ByType(ty) => write!(f, "the service slot of type `{ty}`"),
248 SlotTarget::ByName(name) => write!(f, "the service slot `{name}`"),
249 }
250 }
251}
252
253type ErasedService = Arc<dyn Any + Send + Sync>;
254
255/// A placed value with what decides its precedence: its group (`false` for
256/// the values contributed to come first), the position of its feature in the
257/// final order, reversed so that the feature placed last sorts first, and
258/// its place among the slot's contributions.
259type Ranked = (bool, Reverse<Option<usize>>, usize, ErasedService);
260
261/// One value offered to a service slot, as the registry builder records it.
262///
263/// The feature builder's `contribute` methods and
264/// [`FeatureBuilder::peer_slot`](crate::core::registry::FeatureBuilder::peer_slot)
265/// create these. [`assemble`] checks each one against the slot's declaration
266/// and, when it fits, places the value in the slot.
267pub struct Contribution {
268 /// The feature that contributes the value, or
269 /// [`HOST_FEATURE`](crate::core::registry::HOST_FEATURE) when the
270 /// embedding program contributes it through the registry builder.
271 pub owner: FeatureName,
272 /// The service slot the value is offered to.
273 pub target: SlotTarget,
274 /// The value itself, held type-erased.
275 pub value: ErasedService,
276 /// The type the value was contributed as, checked against the slot's
277 /// declared type.
278 pub ty: TypeKey,
279 /// Whether the value precedes, in a slot that takes several values, the
280 /// contributions that do not ask to come first.
281 pub prepend: bool,
282 /// Whether this is a **peer contribution**: a value offered to a service
283 /// slot another feature owns, which is dropped, rather than failing the
284 /// registry build, when no feature of the registry declares that slot.
285 ///
286 /// A plain contribution to a slot no feature declares is
287 /// [`ServiceError::UndeclaredSlot`], since it usually comes from a
288 /// misspelled name. A peer contribution states instead that the slot
289 /// belongs to another feature, which may or may not be registered: when no
290 /// feature declares the slot, [`assemble`] drops the value and records the
291 /// contribution as unresolved ([`Services::peer_contributions`]), and the
292 /// registry build reports one Note. Set it with [`Contribution::as_peer`].
293 ///
294 /// This applies only to a contribution that gives its slot's name
295 /// ([`SlotTarget::ByName`]). A contribution that identifies its slot by
296 /// type alone has no name the build could report as unresolved, so a type
297 /// that no slot has stays [`ServiceError::UndeclaredSlot`].
298 pub peer: bool,
299}
300
301impl Contribution {
302 /// Returns the contribution of the value `imp` to the service slot
303 /// `target`, by the feature `owner`; `prepend` says whether the value
304 /// comes first ([`Contribution::prepend`]).
305 ///
306 /// Write `S` as the type the slot declares: a trait object type, as in
307 /// `Contribution::new::<dyn Fetcher>(…)`, whenever the service is
308 /// behavior. A concrete `Arc<MyFetcher>` may still be passed as `imp`,
309 /// because Rust converts it at the call.
310 pub fn new<S: ?Sized + Any + Send + Sync>(
311 owner: impl Into<FeatureName>,
312 target: SlotTarget,
313 imp: Arc<S>,
314 prepend: bool,
315 ) -> Contribution {
316 // `S` may be unsized (a trait object), and an `Arc<dyn Trait>` cannot
317 // be erased to `dyn Any` — only a sized value can — so the sized
318 // `Arc<S>` is itself put behind one more `Arc`: the stored value is an
319 // `Arc<Arc<S>>` erased as `Arc<dyn Any>`, and `contents_of` downcasts
320 // it back to `Arc<S>`.
321 Contribution {
322 owner: owner.into(),
323 target,
324 value: Arc::new(imp),
325 ty: TypeKey::of::<S>(),
326 prepend,
327 peer: false,
328 }
329 }
330
331 /// Marks this contribution as a [peer contribution](Contribution::peer),
332 /// and returns it: the service slot belongs to another feature, and the
333 /// value is dropped, rather than the registry build failing, when no
334 /// feature declares the slot.
335 pub fn as_peer(mut self) -> Contribution {
336 self.peer = true;
337 self
338 }
339}
340
341impl fmt::Debug for Contribution {
342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343 f.debug_struct("Contribution")
344 .field("owner", &self.owner)
345 .field("target", &self.target)
346 .field("ty", &self.ty)
347 .field("prepend", &self.prepend)
348 .field("peer", &self.peer)
349 .finish()
350 }
351}
352
353/// A feature's statement that it cannot work in any plan unless a service
354/// slot receives at least one value; a required slot that receives none is a
355/// registry build error ([`ServiceError::RequiredSlotUnfilled`]).
356///
357/// [`FeatureBuilder::require_service`](crate::core::registry::FeatureBuilder::require_service)
358/// and
359/// [`FeatureBuilder::require_service_named`](crate::core::registry::FeatureBuilder::require_service_named)
360/// record one. A service that only some plans need is not required this way:
361/// the stage that needs it reads an `Option` and reports the absence itself,
362/// so that a program that never builds such a plan can still build its
363/// registry.
364#[derive(Debug, Clone)]
365pub struct ServiceRequirement {
366 /// The feature that requires the slot to be filled.
367 pub owner: FeatureName,
368 /// The service slot that must receive at least one value.
369 pub target: SlotTarget,
370}
371
372/// The record of one [peer contribution](Contribution::peer) in the finished
373/// registry: which feature offered a value to which service slot, and whether
374/// any feature of the registry declares that slot.
375///
376/// A feature makes a peer contribution with
377/// [`FeatureBuilder::peer_slot`](crate::core::registry::FeatureBuilder::peer_slot).
378/// Read the records through [`Services::peer_contributions`], or through
379/// [`FlmRegistry::peer_slots`](crate::core::registry::FlmRegistry::peer_slots)
380/// together with the other peer declarations, so that a misspelled slot name
381/// can be found on any registry that holds the feature.
382#[derive(Debug, Clone, PartialEq, Eq)]
383pub struct PeerContribution {
384 /// The feature that contributed the value.
385 pub owner: FeatureName,
386 /// The name of the service slot the value was offered to.
387 pub slot: Name,
388 /// The type the value was contributed as, which is the peer declaration's
389 /// signature: when the slot is declared, [`assemble`] checked this type
390 /// against the slot's own.
391 pub ty: TypeKey,
392 /// Whether some feature of this registry declares the slot. When `false`,
393 /// the value was dropped and the registry build recorded one Note.
394 pub resolved: bool,
395}
396
397/// A problem that makes [`assemble`] refuse the service slot declarations,
398/// contributions and requirements of a registry.
399///
400/// The registry build reports each one as a build error
401/// ([`BuildError::Service`](crate::core::registry::BuildError::Service)).
402/// Every variant identifies the features involved, so that the report says
403/// which feature to correct.
404#[derive(Debug, Clone, PartialEq, Eq)]
405pub enum ServiceError {
406 /// Two features declared a service slot under one name. A slot name
407 /// identifies one interaction, owned by one feature.
408 DuplicateSlot {
409 /// The name declared twice.
410 slot: Name,
411 /// The feature that declared it first.
412 first: FeatureName,
413 /// The feature that declared it again.
414 second: FeatureName,
415 },
416 /// A contribution or a requirement refers to a service slot that no
417 /// feature declares.
418 UndeclaredSlot {
419 /// The feature that contributed or required.
420 feature: FeatureName,
421 /// The service slot it refers to.
422 target: SlotTarget,
423 /// The name of every declared service slot, so that the report can
424 /// list the alternatives.
425 roster: Vec<Name>,
426 },
427 /// A contribution or a requirement identifies its service slot by type
428 /// alone, and several slots have that type. Giving the slot's name
429 /// removes the ambiguity.
430 AmbiguousSlot {
431 /// The feature that contributed or required.
432 feature: FeatureName,
433 /// The type it gave.
434 ty: TypeKey,
435 /// The service slots that have that type, in name order.
436 slots: Vec<Name>,
437 },
438 /// A value was contributed as a type other than the one its service slot
439 /// declares.
440 TypeMismatch {
441 /// The contributing feature.
442 feature: FeatureName,
443 /// The service slot contributed to.
444 slot: Name,
445 /// The type the slot declares.
446 declared: TypeKey,
447 /// The type the value was contributed as.
448 contributed: TypeKey,
449 },
450 /// A second value was contributed to a service slot that takes exactly
451 /// one ([`Arity::Single`]).
452 SingleSlotRefilled {
453 /// The service slot.
454 slot: Name,
455 /// The feature whose value fills it.
456 first: FeatureName,
457 /// The feature that contributed a second value.
458 second: FeatureName,
459 },
460 /// A service slot that a feature requires
461 /// ([`ServiceRequirement`]) received no value.
462 RequiredSlotUnfilled {
463 /// The empty service slot.
464 slot: Name,
465 /// The feature that requires it.
466 required_by: FeatureName,
467 },
468}
469
470impl fmt::Display for ServiceError {
471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 match self {
473 ServiceError::DuplicateSlot { slot, first, second } => {
474 write!(
475 f,
476 "service slot `{slot}` must be declared only once, but feature `{first}` \
477 declares it and feature `{second}` declares it again"
478 )
479 }
480 ServiceError::UndeclaredSlot { feature, target, roster } => write!(
481 f,
482 "feature `{feature}` refers to {target}, but no feature declares a service slot \
483 of that {}; declared service slots: [{}]",
484 match target {
485 SlotTarget::ByName(_) => "name",
486 SlotTarget::ByType(_) => "type",
487 },
488 roster.iter().map(|name| name.as_str()).collect::<Vec<_>>().join(", ")
489 ),
490 ServiceError::AmbiguousSlot { feature, ty, slots } => write!(
491 f,
492 "feature `{feature}` must refer to a service slot by name when several slots \
493 have the type `{ty}` ([{}])",
494 slots.iter().map(|name| name.as_str()).collect::<Vec<_>>().join(", ")
495 ),
496 ServiceError::TypeMismatch { feature, slot, declared, contributed } => write!(
497 f,
498 "a value contributed to service slot `{slot}` must have the slot's type \
499 `{declared}`, but feature `{feature}` contributes a `{contributed}`"
500 ),
501 ServiceError::SingleSlotRefilled { slot, first, second } => write!(
502 f,
503 "service slot `{slot}` takes at most one value, but feature `{first}` \
504 contributes one and feature `{second}` contributes another"
505 ),
506 ServiceError::RequiredSlotUnfilled { slot, required_by } => {
507 write!(
508 f,
509 "service slot `{slot}` must receive a value, because feature \
510 `{required_by}` requires it"
511 )
512 }
513 }
514 }
515}
516
517impl std::error::Error for ServiceError {}
518
519/// The service slots of a registry and the values contributed to them, fixed
520/// once the registry is built.
521///
522/// [`assemble`] produces it during the registry build, and
523/// [`FlmRegistry::services`](crate::core::registry::FlmRegistry::services)
524/// returns it. Every run shares it, and nothing changes it. Read a service by
525/// its type ([`Services::service`], [`Services::services`]) or, where two slots
526/// have one type, by slot name ([`Services::service_named`],
527/// [`Services::services_named`]). A stage normally reads a service through its
528/// context ([`StageCx::service`](crate::core::run::StageCx::service)) rather
529/// than here.
530#[derive(Default)]
531pub struct Services {
532 slots: BTreeMap<Name, SlotDecl>,
533 /// Each slot's values in the assembled order.
534 contents: BTreeMap<Name, Vec<ErasedService>>,
535 /// Each slot's values in the order of precedence.
536 ranked: BTreeMap<Name, Vec<ErasedService>>,
537 by_type: BTreeMap<TypeKey, Vec<Name>>,
538 peers: Vec<PeerContribution>,
539}
540
541impl Services {
542 /// Returns services with no slot and no value: what a registry holds when
543 /// no feature declares a service slot.
544 pub fn new() -> Services {
545 Services::default()
546 }
547
548 /// Returns the declaration of the service slot named `name`, or `None`
549 /// when no slot has that name.
550 pub fn slot(&self, name: &str) -> Option<&SlotDecl> {
551 self.slots.get(name)
552 }
553
554 /// Returns every declared service slot, in name order.
555 ///
556 /// The order does not depend on the order in which the features
557 /// registered, so a listing built from it is the same in every build.
558 pub fn slots(&self) -> impl Iterator<Item = &SlotDecl> + '_ {
559 self.slots.values()
560 }
561
562 /// Returns the names of the service slots whose values have the type `S`,
563 /// in name order.
564 ///
565 /// When it returns more than one name, a contribution by type alone is
566 /// refused as ambiguous, and a read by type alone takes the slots in this
567 /// order; the operations that take a slot name select one slot.
568 pub fn slots_of<S: ?Sized + Any>(&self) -> &[Name] {
569 self.by_type.get(&TypeKey::of::<S>()).map(Vec::as_slice).unwrap_or(&[])
570 }
571
572 fn contents_of<S: ?Sized + Any + Send + Sync>(
573 &self,
574 name: &str,
575 ) -> impl Iterator<Item = &S> + '_ {
576 self.shared_named::<S>(name).map(|arc| &**arc)
577 }
578
579 /// Returns one service of type `S`: of the service slots whose values have
580 /// that type, taken in name order, the first that holds a value gives the
581 /// value that takes precedence in it (the first in the order of
582 /// [`Services::services_by_precedence_named`]).
583 ///
584 /// Write `S` as the type the slot declares:
585 /// `services.service::<dyn Fetcher>()`. Returns `None` when no slot has the
586 /// type, or when every such slot is empty; an absent service is a normal
587 /// result, and the caller decides what to do about it.
588 ///
589 /// See also [`Services::service_named`], for a slot named directly.
590 pub fn service<S: ?Sized + Any + Send + Sync>(&self) -> Option<&S> {
591 self.slots_of::<S>().iter().find_map(|name| self.service_named::<S>(name))
592 }
593
594 /// Returns every service of type `S`: the values of every service slot
595 /// whose values have that type, the slots taken in name order and the
596 /// values of each slot in their assembled order (see [`Arity::OrderedMany`]).
597 pub fn services<S: ?Sized + Any + Send + Sync>(&self) -> impl Iterator<Item = &S> + '_ {
598 self.slots_of::<S>().iter().flat_map(|name| self.contents_of::<S>(name))
599 }
600
601 /// Returns the value of the service slot named `name` that takes
602 /// precedence, read as an `S`: the first in the order of
603 /// [`Services::services_by_precedence_named`], so that between features,
604 /// the value of the feature placed last in the feature order.
605 ///
606 /// Returns `None` when the slot does not exist, holds no value, or holds
607 /// values of another type.
608 pub fn service_named<S: ?Sized + Any + Send + Sync>(&self, name: &str) -> Option<&S> {
609 self.services_by_precedence_named::<S>(name).next()
610 }
611
612 /// Returns the value of the service slot named `name` that takes
613 /// precedence, as [`Services::service_named`] does, as the shared pointer
614 /// it was contributed as.
615 ///
616 /// Use it to keep that value beyond the borrow of the services, as
617 /// [`Services::shared_named`] does for every value of a slot.
618 pub fn shared_service_named<S: ?Sized + Any + Send + Sync>(&self, name: &str) -> Option<&Arc<S>> {
619 self.ranked.get(name).into_iter().flatten().find_map(|value| value.downcast_ref::<Arc<S>>())
620 }
621
622 /// Returns every value of the service slot named `name`, read as `S`, in
623 /// their assembled order: the values contributed with `contribute_first`
624 /// or `contribute_first_to` come first, then the others, each group in the
625 /// order the values were contributed. Returns nothing when the slot does
626 /// not exist or holds values of another type.
627 pub fn services_named<S: ?Sized + Any + Send + Sync>(
628 &self,
629 name: &str,
630 ) -> impl Iterator<Item = &S> + '_ {
631 self.contents_of::<S>(name)
632 }
633
634 /// Returns every value of the service slot named `name`, read as `S`, in
635 /// the order of precedence: the values contributed with
636 /// `contribute_first` or `contribute_first_to` first, then the others;
637 /// within each of these two groups, the values of the feature placed last
638 /// in the feature order first, each feature's values in the order the
639 /// feature contributed them, and the embedding program's values last.
640 /// Returns nothing when the slot does not exist or holds values of another
641 /// type.
642 ///
643 /// Read a slot in this order where its values are asked in turn until one
644 /// answers, so that between features, the feature placed last wins (see
645 /// [the order of a slot's values](self#the-order-of-a-slots-values)).
646 pub fn services_by_precedence_named<S: ?Sized + Any + Send + Sync>(
647 &self,
648 name: &str,
649 ) -> impl Iterator<Item = &S> + '_ {
650 self.ranked
651 .get(name)
652 .into_iter()
653 .flatten()
654 .filter_map(|value| value.downcast_ref::<Arc<S>>())
655 .map(|arc| &**arc)
656 }
657
658 /// Returns every value of the service slot named `name`, read as `S`, in
659 /// the order of [`Services::services_named`], each as the shared pointer
660 /// it was contributed as.
661 ///
662 /// Use it to keep a service beyond the registry build. A lowering rule,
663 /// for example, has no access to the registry's services while it runs,
664 /// so a finalizer ([`Finalizer`](crate::core::registry::Finalizer)) hands
665 /// it the values of a slot: the pointer is cloned, and the value itself is
666 /// shared, not copied.
667 pub fn shared_named<S: ?Sized + Any + Send + Sync>(
668 &self,
669 name: &str,
670 ) -> impl Iterator<Item = &Arc<S>> + '_ {
671 self.contents
672 .get(name)
673 .into_iter()
674 .flatten()
675 .filter_map(|value| value.downcast_ref::<Arc<S>>())
676 }
677
678 /// Returns how many values the service slot named `name` holds: zero for
679 /// a slot that is empty or does not exist.
680 pub fn count(&self, name: &str) -> usize {
681 self.contents.get(name).map(Vec::len).unwrap_or(0)
682 }
683
684 /// Returns the record of every [peer contribution](Contribution::peer)
685 /// the features made, in the order they made them, each stating whether
686 /// its service slot is declared.
687 ///
688 /// A peer contribution whose slot no feature declares has `resolved` set
689 /// to `false`, and its value was dropped when the slots were assembled.
690 /// Every peer contribution has its own record, while the registry build
691 /// reports one Note per feature and slot.
692 pub fn peer_contributions(&self) -> &[PeerContribution] {
693 &self.peers
694 }
695}
696
697impl fmt::Debug for Services {
698 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
699 f.debug_map().entries(self.slots.keys().map(|name| (name, self.count(name)))).finish()
700 }
701}
702
703// Resolves a target to the name of the slot it means, against the declared
704// slots: a name is checked for existence, a type must be carried by exactly one
705// slot.
706fn resolve_target(
707 feature: &FeatureName,
708 target: &SlotTarget,
709 slots: &BTreeMap<Name, SlotDecl>,
710 by_type: &BTreeMap<TypeKey, Vec<Name>>,
711) -> Result<Name, ServiceError> {
712 match target {
713 SlotTarget::ByName(name) => {
714 if slots.contains_key(name) {
715 Ok(name.clone())
716 } else {
717 Err(ServiceError::UndeclaredSlot {
718 feature: feature.clone(),
719 target: target.clone(),
720 roster: slots.keys().cloned().collect(),
721 })
722 }
723 }
724 SlotTarget::ByType(ty) => match by_type.get(ty).map(Vec::as_slice) {
725 Some([name]) => Ok(name.clone()),
726 Some(names) if names.len() > 1 => Err(ServiceError::AmbiguousSlot {
727 feature: feature.clone(),
728 ty: *ty,
729 slots: names.to_vec(),
730 }),
731 _ => Err(ServiceError::UndeclaredSlot {
732 feature: feature.clone(),
733 target: target.clone(),
734 roster: slots.keys().cloned().collect(),
735 }),
736 },
737 }
738}
739
740/// Assembles the [`Services`] of a registry from the service slots the
741/// features declared, the values they contributed and the slots they require.
742///
743/// The registry build calls it once, after every feature has registered;
744/// a feature does not call it. Each contribution is matched to its service
745/// slot, checked against the slot's declared type and arity, and placed: the
746/// values contributed with `contribute_first` or `contribute_first_to` come
747/// first, then the others, each group in the order the values were
748/// contributed. `features` gives the features in their final order, from
749/// which the order of precedence of each slot's values follows (see [the
750/// order of a slot's values](self#the-order-of-a-slots-values)); a
751/// contribution whose owner is not among them, such as the embedding
752/// program's, comes after every feature's in its group. Each requirement is
753/// then checked against the filled slots.
754///
755/// A [peer contribution](Contribution::peer), a value offered to a slot
756/// another feature owns, is the only contribution that a missing slot does
757/// not make an error: its value is dropped and the contribution is recorded as
758/// unresolved ([`Services::peer_contributions`]), for the registry build to
759/// report as a Note. Every peer contribution, dropped or not, is recorded
760/// there.
761///
762/// # Errors
763///
764/// Returns every problem found, not only the first, so that a registry can be
765/// corrected in one pass. The problems are in the order they were found: the
766/// declarations first, then the contributions, then the requirements, each in
767/// registration order. See [`ServiceError`] for each problem.
768pub fn assemble(
769 decls: Vec<SlotDecl>,
770 contributions: Vec<Contribution>,
771 requirements: Vec<ServiceRequirement>,
772 features: &[FeatureName],
773) -> Result<Services, Vec<ServiceError>> {
774 let mut errors = Vec::new();
775 let mut slots: BTreeMap<Name, SlotDecl> = BTreeMap::new();
776 let mut by_type: BTreeMap<TypeKey, Vec<Name>> = BTreeMap::new();
777 for decl in decls {
778 if let Some(existing) = slots.get(&decl.name) {
779 errors.push(ServiceError::DuplicateSlot {
780 slot: decl.name.clone(),
781 first: existing.owner.clone(),
782 second: decl.owner.clone(),
783 });
784 continue;
785 }
786 by_type.entry(decl.ty).or_default().push(decl.name.clone());
787 slots.insert(decl.name.clone(), decl);
788 }
789 for names in by_type.values_mut() {
790 names.sort();
791 }
792
793 let mut prepends: BTreeMap<Name, Vec<ErasedService>> = BTreeMap::new();
794 let mut appends: BTreeMap<Name, Vec<ErasedService>> = BTreeMap::new();
795 let mut ranking: BTreeMap<Name, Vec<Ranked>> = BTreeMap::new();
796 let mut single_filled: BTreeMap<Name, FeatureName> = BTreeMap::new();
797 let mut peers: Vec<PeerContribution> = Vec::new();
798 for contribution in contributions {
799 let name = match resolve_target(&contribution.owner, &contribution.target, &slots, &by_type)
800 {
801 Ok(name) => name,
802 Err(error) => {
803 // A peer contribution names a slot another feature owns: when
804 // nobody declares it, the value is dropped and recorded as
805 // unresolved, rather than the build failing over a name this
806 // feature does not own. Only a contribution that names its
807 // slot can be one; see `Contribution::peer`.
808 match (contribution.peer, &contribution.target, &error) {
809 (true, SlotTarget::ByName(slot), ServiceError::UndeclaredSlot { .. }) => {
810 peers.push(PeerContribution {
811 owner: contribution.owner.clone(),
812 slot: slot.clone(),
813 ty: contribution.ty,
814 resolved: false,
815 });
816 }
817 _ => errors.push(error),
818 }
819 continue;
820 }
821 };
822 if contribution.peer {
823 peers.push(PeerContribution {
824 owner: contribution.owner.clone(),
825 slot: name.clone(),
826 ty: contribution.ty,
827 resolved: true,
828 });
829 }
830 let decl = &slots[&name];
831 if decl.ty != contribution.ty {
832 errors.push(ServiceError::TypeMismatch {
833 feature: contribution.owner,
834 slot: name,
835 declared: decl.ty,
836 contributed: contribution.ty,
837 });
838 continue;
839 }
840 if decl.arity == Arity::Single {
841 if let Some(first) = single_filled.get(&name) {
842 errors.push(ServiceError::SingleSlotRefilled {
843 slot: name,
844 first: first.clone(),
845 second: contribution.owner,
846 });
847 continue;
848 }
849 single_filled.insert(name.clone(), contribution.owner.clone());
850 }
851 let position = features.iter().position(|feature| *feature == contribution.owner);
852 let entry = ranking.entry(name.clone()).or_default();
853 let seq = entry.len();
854 entry.push((!contribution.prepend, Reverse(position), seq, Arc::clone(&contribution.value)));
855 let bucket = if contribution.prepend { &mut prepends } else { &mut appends };
856 bucket.entry(name).or_default().push(contribution.value);
857 }
858 let ranked: BTreeMap<Name, Vec<ErasedService>> = ranking
859 .into_iter()
860 .map(|(name, mut values)| {
861 values.sort_by_key(|(group, position, seq, _)| (*group, *position, *seq));
862 (name, values.into_iter().map(|(_, _, _, value)| value).collect())
863 })
864 .collect();
865 let mut contents: BTreeMap<Name, Vec<ErasedService>> = BTreeMap::new();
866 for (name, mut values) in prepends {
867 values.extend(appends.remove(&name).unwrap_or_default());
868 contents.insert(name, values);
869 }
870 contents.extend(appends);
871
872 for requirement in requirements {
873 match resolve_target(&requirement.owner, &requirement.target, &slots, &by_type) {
874 Ok(name) => {
875 if contents.get(&name).map(Vec::is_empty).unwrap_or(true) {
876 errors.push(ServiceError::RequiredSlotUnfilled {
877 slot: name,
878 required_by: requirement.owner,
879 });
880 }
881 }
882 Err(error) => errors.push(error),
883 }
884 }
885
886 if errors.is_empty() {
887 Ok(Services { slots, contents, ranked, by_type, peers })
888 } else {
889 Err(errors)
890 }
891}
892
893#[cfg(test)]
894mod tests {
895 use super::*;
896
897 trait Greeter: Send + Sync {
898 fn greet(&self) -> &'static str;
899 }
900
901 struct Hello;
902
903 impl Greeter for Hello {
904 fn greet(&self) -> &'static str {
905 "hello"
906 }
907 }
908
909 fn slot(name: &str, arity: Arity) -> SlotDecl {
910 SlotDecl {
911 name: name.into(),
912 ty: TypeKey::of::<dyn Greeter>(),
913 arity,
914 owner: "a".into(),
915 docs: String::new(),
916 }
917 }
918
919 #[test]
920 fn a_contribution_by_type_lands_in_the_one_slot_of_that_type() {
921 let services = assemble(
922 vec![slot("x.greeter", Arity::Single)],
923 vec![Contribution::new::<dyn Greeter>(
924 "b",
925 SlotTarget::ByType(TypeKey::of::<dyn Greeter>()),
926 Arc::new(Hello),
927 false,
928 )],
929 Vec::new(),
930 &[],
931 )
932 .unwrap();
933 assert_eq!(services.service::<dyn Greeter>().map(Greeter::greet), Some("hello"));
934 assert_eq!(
935 services.service_named::<dyn Greeter>("x.greeter").map(Greeter::greet),
936 Some("hello")
937 );
938 assert!(services.service::<String>().is_none());
939 }
940
941 #[test]
942 fn a_contribution_by_type_is_ambiguous_when_two_slots_carry_it() {
943 let errors = assemble(
944 vec![slot("x.a", Arity::Single), slot("x.b", Arity::Single)],
945 vec![Contribution::new::<dyn Greeter>(
946 "b",
947 SlotTarget::ByType(TypeKey::of::<dyn Greeter>()),
948 Arc::new(Hello),
949 false,
950 )],
951 Vec::new(),
952 &[],
953 )
954 .unwrap_err();
955 assert!(
956 matches!(&errors[0], ServiceError::AmbiguousSlot { slots, .. } if slots.len() == 2)
957 );
958 }
959
960 #[test]
961 fn a_required_unfilled_slot_is_an_error() {
962 let errors = assemble(
963 vec![slot("x.greeter", Arity::Single)],
964 Vec::new(),
965 vec![ServiceRequirement {
966 owner: "a".into(),
967 target: SlotTarget::ByName("x.greeter".into()),
968 }],
969 &[],
970 )
971 .unwrap_err();
972 assert!(
973 matches!(
974 &errors[0],
975 ServiceError::RequiredSlotUnfilled { slot, .. } if slot == "x.greeter"
976 )
977 );
978 }
979
980 #[test]
981 fn a_read_for_precedence_takes_the_feature_placed_last_first_in_each_group() {
982 let value = |owner: &str, text: &'static str, prepend: bool| {
983 Contribution::new::<String>(
984 owner,
985 SlotTarget::ByName("x.list".into()),
986 Arc::new(text.to_string()),
987 prepend,
988 )
989 };
990 let decl = SlotDecl {
991 name: "x.list".into(),
992 ty: TypeKey::of::<String>(),
993 arity: Arity::OrderedMany,
994 owner: "a".into(),
995 docs: String::new(),
996 };
997 let services = assemble(
998 vec![decl],
999 vec![
1000 value("a", "a1", false),
1001 value("a", "a-first", true),
1002 value("a", "a2", false),
1003 value("b", "b1", false),
1004 value("b", "b-first", true),
1005 value("b", "b2", false),
1006 value("host", "host1", false),
1007 ],
1008 Vec::new(),
1009 &["a".into(), "b".into()],
1010 )
1011 .unwrap();
1012 let assembled: Vec<&str> = services.services_named::<String>("x.list").map(String::as_str).collect();
1013 assert_eq!(assembled, ["a-first", "b-first", "a1", "a2", "b1", "b2", "host1"]);
1014 let ranked: Vec<&str> =
1015 services.services_by_precedence_named::<String>("x.list").map(String::as_str).collect();
1016 assert_eq!(ranked, ["b-first", "a-first", "b1", "b2", "a1", "a2", "host1"]);
1017 assert_eq!(services.service_named::<String>("x.list").map(String::as_str), Some("b-first"));
1018 assert_eq!(services.service::<String>().map(String::as_str), Some("b-first"));
1019 }
1020}