Skip to main content

flm_core/core/registry/
feature.rs

1//! Features, the units a registry is built from, and packages, the named
2//! bundles in which features are shipped and registered together.
3//!
4//! A **feature** is a Rust value that contributes a related bundle of things to
5//! a registry (elements, stages, tables, lowering rules, backends, services,
6//! settings) through the feature builder. It implements [`FlmFeature`]: its
7//! [`register`](FlmFeature::register) method calls methods of a
8//! [`FeatureBuilder`], each of which records one declaration. A feature is
9//! usually constructed from a plain Rust value of its own, its
10//! [configuration](crate::guide::concepts_overview#settings-options-and-configuration)
11//! (for example `Refs::new(RefsConfig { .. })`), so the compiler checks the
12//! configuration instead of a schema. The finished registry does not keep the
13//! feature value; it keeps only its [`FeatureInfo`]: its name, title,
14//! documentation and optional version.
15//!
16//! A **package** is a named bundle of features together with the packages it
17//! builds on. This module defines three forms of a package:
18//!
19//! - A [`PackageEntry`] is a package ready to register: the packages it uses
20//!   and its own features, in order.
21//!   [`RegistryBuilder::use_package`](super::RegistryBuilder::use_package)
22//!   registers the features of an entry and of the packages it uses, each
23//!   package once, however often it is listed.
24//! - A [`PackageFactory`] is a package known before it is built: its name, the
25//!   names of the packages it uses, its features each with the declaration of
26//!   its settings ([`crate::core::settings`]), and the function that builds the
27//!   package's entry from the final settings. A program that reads settings
28//!   as data reads them with the declarations the factory lists, then builds
29//!   the package.
30//! - A [`PackageCatalog`] finds the factory of a package from the package's
31//!   name: first among the factories compiled into the program, then through
32//!   [`PackageResolver`] implementations, asked in order, only when no compiled
33//!   factory has that name. A resolver may perform input and output (for
34//!   example, find a package file on a search path). This crate performs no
35//!   input or output itself, so it declares the trait and implements none.
36//!
37//! See also [features and
38//! packages](crate::guide::concepts_overview#features-and-packages) for the
39//! concepts, and [`super::build`] for how a set of features becomes a
40//! registry.
41
42use std::collections::{BTreeMap, BTreeSet};
43use std::fmt;
44use std::sync::Arc;
45
46use crate::model::names::{FeatureName, Name};
47use crate::core::registry::builder::{BuildError, FeatureBuilder};
48use crate::core::registry::order::FeatureChain;
49use crate::core::settings::cascade::Reach;
50use crate::core::settings::{PackageSettings, SettingsDecl};
51
52/// The description of a feature that a registry keeps: the feature's name,
53/// title, documentation and optional version.
54///
55/// A feature returns this value from [`FlmFeature::info`]. The finished
56/// registry returns it from
57/// [`FlmRegistry::features`](super::FlmRegistry::features) and
58/// [`FlmRegistry::feature`](super::FlmRegistry::feature) after the build,
59/// when the registry no longer holds the feature value.
60///
61/// It is written to data with `Serialize`; see [serialized
62/// forms](crate::core::registry#serialized-forms).
63///
64/// # Examples
65///
66/// ```
67/// use flm_core::core::registry::FeatureInfo;
68///
69/// let info = FeatureInfo::new("refs", "Cross-references")
70///     .docs("Labels, references, and the table that resolves them.")
71///     .version("1.0");
72/// assert_eq!(info.name, "refs");
73/// ```
74#[derive(Debug, Clone, PartialEq, Eq)]
75#[derive(serde::Serialize, schemars::JsonSchema)]
76pub struct FeatureInfo {
77    /// The feature's registered name, unique within one registry. Every
78    /// declaration the feature makes is attributed to this name. By
79    /// convention, the names of the entities a feature declares contain it:
80    /// the `refs` feature's resolve stage is `flm.refs.resolve`.
81    pub name: FeatureName,
82    /// A short human-readable title.
83    pub title: String,
84    /// Documentation prose about the feature as a whole.
85    pub docs: String,
86    /// A free-form version string, for attribution. It is an input of the
87    /// [registry digest](crate::model::digest), so two registries whose
88    /// features differ only in version have different digests, and data
89    /// cached under one is not read back under the other.
90    pub version: Option<String>,
91}
92
93impl FeatureInfo {
94    /// The description of the feature `name`, titled `title`, with no
95    /// documentation and no version.
96    pub fn new(name: impl Into<FeatureName>, title: impl Into<String>) -> FeatureInfo {
97        FeatureInfo { name: name.into(), title: title.into(), docs: String::new(), version: None }
98    }
99
100    /// Sets the documentation prose. Returns `self`, for chaining.
101    pub fn docs(mut self, docs: impl Into<String>) -> FeatureInfo {
102        self.docs = crate::kept_docs(docs);
103        self
104    }
105
106    /// Sets the version string. Returns `self`, for chaining.
107    pub fn version(mut self, version: impl Into<String>) -> FeatureInfo {
108        self.version = Some(version.into());
109        self
110    }
111}
112
113/// A feature: a Rust value that contributes a related bundle of things to a
114/// registry (elements, stages, tables, lowering rules, backends, services,
115/// settings) through the feature builder.
116///
117/// Implement this trait on a value that holds the feature's configuration.
118/// [`info`](FlmFeature::info) describes the feature, and
119/// [`register`](FlmFeature::register) declares what it contributes by calling
120/// methods of the [`FeatureBuilder`] it is handed. Then give the value to
121/// [`RegistryBuilder::feature`](super::RegistryBuilder::feature), or add it to
122/// a [`PackageEntry`]. The trait requires `Send + Sync` so that packages,
123/// which hold their features, can be built and shared across threads.
124///
125/// # Examples
126///
127/// ```
128/// use std::sync::Arc;
129/// use flm_core::core::registry::{
130///     BuildError, CapabilityDef, FeatureBuilder, FeatureInfo, FlmFeature, build_registry,
131/// };
132///
133/// struct Counting;
134///
135/// impl FlmFeature for Counting {
136///     fn info(&self) -> FeatureInfo {
137///         FeatureInfo::new("counting", "Counting")
138///     }
139///
140///     fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
141///         b.capability(CapabilityDef::new("counting.done").docs("Counting has run."))
142///     }
143/// }
144///
145/// let registry = build_registry([Arc::new(Counting) as Arc<dyn FlmFeature>])?;
146/// assert!(registry.has_feature("counting"));
147/// assert!(registry.capability_named("counting.done").is_some());
148/// # Ok::<(), flm_core::core::registry::RegistryBuildError>(())
149/// ```
150pub trait FlmFeature: Send + Sync {
151    /// The feature's name, title, documentation and version.
152    ///
153    /// The build calls this method once, before the feature registers. Two
154    /// features that return the same name make the build fail with
155    /// [`BuildError::DuplicateFeature`].
156    fn info(&self) -> FeatureInfo;
157
158    /// Declares everything the feature contributes, by calling methods of `b`.
159    ///
160    /// This is the first of the build's two registration rounds. Every method
161    /// of [`FeatureBuilder`] may be called here, in any order, regardless of
162    /// what other features declare: nothing is checked or resolved until every
163    /// feature has registered, so a feature never needs to know which other
164    /// features are present or which registered first. A feature that must
165    /// read what other features contributed to service slots registers a
166    /// [`Finalizer`](super::Finalizer), which runs in the second round.
167    ///
168    /// # Errors
169    ///
170    /// Return a [`BuildError`] (usually the one a builder method returned) to
171    /// refuse registration. The build records a [`BuildError::Feature`]
172    /// unchanged, and wraps any other error in a [`BuildError::Feature`]
173    /// attributed to this feature. The other features still register, and the
174    /// build then fails at the end of the collect phase, the first of its five
175    /// phases (see [`super::build`]).
176    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError>;
177
178    /// The declaration of the settings the feature takes as data (its
179    /// configuration and its option types, each with its binding), or `None`
180    /// for a feature that takes no settings as data. The default
181    /// implementation returns `None`. See [`crate::core::settings`].
182    ///
183    /// The registry build declares the option types listed in this
184    /// declaration, with their bindings and documentation, before it calls
185    /// [`register`](FlmFeature::register); `register` must not declare them
186    /// again, or the build reports a duplicate option type. A
187    /// [`PackageFactory`] lists this declaration next to the feature's name.
188    /// The name [`ENABLED_KEY`](crate::core::settings::ENABLED_KEY) is
189    /// reserved for switching a feature on or off: a [`SettingsDecl`] refuses
190    /// a key of that name.
191    fn settings(&self) -> Option<SettingsDecl> {
192        None
193    }
194}
195
196/// The error a package's build function returns when it cannot build the
197/// package from the given settings; see [`PackageFactory::build`].
198#[derive(Debug, Clone, PartialEq, Eq)]
199pub struct PackageError {
200    /// What failed, as text for a person to read.
201    pub detail: String,
202}
203
204impl PackageError {
205    /// An error whose text is `detail`.
206    pub fn new(detail: impl Into<String>) -> PackageError {
207        PackageError { detail: detail.into() }
208    }
209}
210
211impl fmt::Display for PackageError {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        f.write_str(&self.detail)
214    }
215}
216
217impl std::error::Error for PackageError {}
218
219/// One feature of a [`PackageFactory`]: the feature's name, and the
220/// declaration of its settings if it takes settings as data, as the feature
221/// returns them from [`FlmFeature::info`] and [`FlmFeature::settings`].
222#[derive(Debug, Clone)]
223pub struct PackageFeature {
224    /// The feature's registered name.
225    pub name: FeatureName,
226    /// The declaration of the feature's settings; `None` for a feature that
227    /// takes none.
228    pub settings: Option<SettingsDecl>,
229}
230
231/// The function a [`PackageFactory`] builds its package with.
232type BuildFn = dyn Fn(&PackageSettings) -> Result<PackageEntry, PackageError> + Send + Sync;
233
234/// A package known before it is built: its name, the names of the packages it
235/// uses, its features each with the declaration of its settings, and the
236/// function that builds the package's [`PackageEntry`] from the final
237/// settings.
238///
239/// A factory serves a program that chooses packages by name and reads their
240/// settings as data, for example from a document's front matter. The program
241/// reads the settings written for the package's features with the
242/// declarations the factory lists ([`settings`](PackageFactory::settings)),
243/// combines them over all its sources, and then builds the package once with
244/// [`build`](PackageFactory::build). The factory lists the packages it uses by
245/// name only: the program builds each of them from its own factory, so the
246/// entry that `build` returns should use no package. A package that holds the
247/// standard features builds them in its build function with
248/// [`crate::stdlib::add_features_from_settings`].
249///
250/// The factory finds its features by building the package once, when it is
251/// created, from empty settings: it lists each feature of that entry, in
252/// order, with the name and the settings declaration the feature returns. A
253/// feature that the package includes only under some settings is therefore
254/// not listed.
255///
256/// # Examples
257///
258/// ```
259/// use std::sync::Arc;
260/// use flm_core::core::registry::{
261///     BuildError, FeatureBuilder, FeatureInfo, FlmFeature, PackageEntry, PackageFactory,
262/// };
263/// use flm_core::core::settings::PackageSettings;
264///
265/// struct Empty;
266/// impl FlmFeature for Empty {
267///     fn info(&self) -> FeatureInfo { FeatureInfo::new("empty", "Empty") }
268///     fn register(&self, _b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> { Ok(()) }
269/// }
270///
271/// let factory = PackageFactory::new("mine", |settings: &PackageSettings| {
272///     let mut entry = PackageEntry::new("mine");
273///     if !settings.is_off("empty") {
274///         entry = entry.feature(Arc::new(Empty));
275///     }
276///     Ok(entry)
277/// })?;
278///
279/// assert_eq!(factory.features().len(), 1);
280/// assert_eq!(factory.features()[0].name, "empty");
281/// let entry = factory.build(&PackageSettings::new())?;
282/// assert_eq!(entry.features.len(), 1);
283/// # Ok::<(), flm_core::core::registry::PackageError>(())
284/// ```
285#[derive(Clone)]
286pub struct PackageFactory {
287    name: Name,
288    uses: Vec<Name>,
289    features: Vec<PackageFeature>,
290    build: Arc<BuildFn>,
291}
292
293impl PackageFactory {
294    /// The factory of the package `name`, whose entry the function `build`
295    /// builds; the package uses no other package until
296    /// [`uses`](PackageFactory::uses) adds one.
297    ///
298    /// `build` receives the final settings of the package's features and
299    /// returns the package's entry; it should leave out every feature the
300    /// settings switch off ([`PackageSettings::is_off`]). This constructor
301    /// calls `build` once, with empty settings, and lists the features of the
302    /// entry it returns (see [`features`](PackageFactory::features)).
303    ///
304    /// # Errors
305    ///
306    /// The [`PackageError`] that `build` returns for empty settings.
307    pub fn new(
308        name: impl Into<Name>,
309        build: impl Fn(&PackageSettings) -> Result<PackageEntry, PackageError> + Send + Sync + 'static,
310    ) -> Result<PackageFactory, PackageError> {
311        let features = build(&PackageSettings::new())?
312            .features
313            .iter()
314            .map(|feature| PackageFeature { name: feature.info().name, settings: feature.settings() })
315            .collect();
316        Ok(PackageFactory { name: name.into(), uses: Vec::new(), features, build: Arc::new(build) })
317    }
318
319    /// Adds the name of a package this package uses, after those already
320    /// added. Returns `self`, for chaining.
321    pub fn uses(mut self, package: impl Into<Name>) -> PackageFactory {
322        self.uses.push(package.into());
323        self
324    }
325
326    /// The package's name.
327    pub fn name(&self) -> &Name {
328        &self.name
329    }
330
331    /// The names of the packages this one uses, in the order listed.
332    pub fn used(&self) -> &[Name] {
333        &self.uses
334    }
335
336    /// The package's features, in the package's order: the features of the
337    /// entry built from empty settings, each with its name and its settings
338    /// declaration.
339    pub fn features(&self) -> &[PackageFeature] {
340        &self.features
341    }
342
343    /// The declaration of the settings of the feature `feature`, or `None`
344    /// when the package does not hold that feature or the feature takes no
345    /// settings as data.
346    pub fn settings(&self, feature: &str) -> Option<&SettingsDecl> {
347        self.features
348            .iter()
349            .find(|entry| entry.name == feature)
350            .and_then(|entry| entry.settings.as_ref())
351    }
352
353    /// Builds the package's entry from the final settings of its features, by
354    /// calling the function given to [`new`](PackageFactory::new).
355    ///
356    /// # Errors
357    ///
358    /// The [`PackageError`] that the package's build function returns.
359    pub fn build(&self, settings: &PackageSettings) -> Result<PackageEntry, PackageError> {
360        (self.build)(settings)
361    }
362}
363
364impl fmt::Debug for PackageFactory {
365    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366        f.debug_struct("PackageFactory")
367            .field("name", &self.name)
368            .field("uses", &self.uses)
369            .field("features", &self.features.iter().map(|entry| &entry.name).collect::<Vec<_>>())
370            .finish()
371    }
372}
373
374/// A failure of a [`PackageResolver`] that recognized a package name but could
375/// not produce the package's factory (for example, an unreadable file or a
376/// malformed definition): what failed and, for a failure in a file, where.
377///
378/// A resolver that has no package of that name returns `Ok(None)` instead; that
379/// is not a failure.
380///
381/// # Examples
382///
383/// ```
384/// use flm_core::core::registry::ResolveError;
385///
386/// let error = ResolveError::new("the file is not valid YAML").in_file("mystyle.yaml").at(3, 5);
387/// assert_eq!((error.line, error.column), (Some(3), Some(5)));
388/// ```
389#[derive(Debug, Clone, PartialEq, Eq)]
390pub struct ResolveError {
391    /// What failed, as text for a person to read.
392    pub detail: String,
393    /// The file the failure is in, written the way the resolver shows files
394    /// to a person, when the failure is in a file.
395    pub file: Option<String>,
396    /// The line in that file, counted from 1, when known.
397    pub line: Option<u32>,
398    /// The column in that line, counted from 1, when known.
399    pub column: Option<u32>,
400}
401
402impl ResolveError {
403    /// The failure `detail`, not located in any file.
404    pub fn new(detail: impl Into<String>) -> ResolveError {
405        ResolveError { detail: detail.into(), file: None, line: None, column: None }
406    }
407
408    /// The same failure, located in the file `file`. Returns `self`, for
409    /// chaining.
410    pub fn in_file(mut self, file: impl Into<String>) -> ResolveError {
411        self.file = Some(file.into());
412        self
413    }
414
415    /// The same failure, located at `line` and `column` (both counted from 1)
416    /// of its file. Returns `self`, for chaining.
417    pub fn at(mut self, line: u32, column: u32) -> ResolveError {
418        self.line = Some(line);
419        self.column = Some(column);
420        self
421    }
422}
423
424impl fmt::Display for ResolveError {
425    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426        f.write_str(&self.detail)
427    }
428}
429
430impl std::error::Error for ResolveError {}
431
432/// A source of packages that are not compiled into the program: given a
433/// package name, it returns the package's [`PackageFactory`].
434///
435/// A [`PackageCatalog`] asks its resolvers, in the order they were added, only
436/// when none of its compiled factories has the name asked for. A resolver may
437/// read files or otherwise reach outside the program. The library performs no
438/// input or output of its own, so this crate declares the trait and implements
439/// none: a program that finds packages on a search path implements it and adds
440/// the implementation with [`PackageCatalog::add_resolver`].
441pub trait PackageResolver: Send + Sync {
442    /// The factory of the package `name`, or `Ok(None)` when this resolver has
443    /// no package of that name.
444    ///
445    /// # Errors
446    ///
447    /// Every [`ResolveError`] found when the resolver recognized the name but
448    /// could not produce a factory; a file may hold several problems. An error
449    /// stops the catalog's search: later resolvers are not asked.
450    fn resolve(&self, name: &str) -> Result<Option<PackageFactory>, Vec<ResolveError>>;
451
452    /// The package names this resolver can resolve, or `None` when it cannot
453    /// list them. A program calls this method to show which packages are
454    /// available; nothing in this crate calls it. The default implementation
455    /// returns `None`.
456    fn list(&self) -> Option<Vec<Name>> {
457        None
458    }
459}
460
461/// A lookup from a package's name to the package's [`PackageFactory`]: first
462/// among the factories compiled into the program, then through
463/// [`PackageResolver`] implementations, asked in order, only when no compiled
464/// factory has the name.
465///
466/// A program builds a catalog to accept package names chosen at run time, for
467/// example from a document's front matter. The registry build never consults
468/// a catalog: a catalog only finds factories. The program then builds each
469/// package from its factory and passes the entry to
470/// [`RegistryBuilder::use_package`](super::RegistryBuilder::use_package), like
471/// any other package. Looking up a compiled package never asks a resolver, so
472/// a document that lists only compiled packages causes no input or output.
473///
474/// # Examples
475///
476/// ```
477/// use flm_core::core::registry::{PackageCatalog, PackageEntry, PackageFactory};
478///
479/// let mut catalog = PackageCatalog::new();
480/// catalog.add_compiled(PackageFactory::new("mine", |_| Ok(PackageEntry::new("mine")))?);
481///
482/// let found = catalog.resolve("mine").expect("no resolver to fail").expect("added above");
483/// assert_eq!(found.name(), "mine");
484/// assert!(catalog.resolve("absent").expect("no resolver to fail").is_none());
485/// # Ok::<(), Box<dyn std::error::Error>>(())
486/// ```
487#[derive(Default, Clone)]
488pub struct PackageCatalog {
489    compiled: BTreeMap<Name, PackageFactory>,
490    resolvers: Vec<Arc<dyn PackageResolver>>,
491}
492
493impl PackageCatalog {
494    /// A catalog with no factories and no resolvers.
495    pub fn new() -> PackageCatalog {
496        PackageCatalog::default()
497    }
498
499    /// Adds a factory compiled into the program, replacing any compiled
500    /// factory already added under the same name. Returns `&mut self`, for
501    /// chaining.
502    pub fn add_compiled(&mut self, factory: PackageFactory) -> &mut PackageCatalog {
503        self.compiled.insert(factory.name.clone(), factory);
504        self
505    }
506
507    /// Adds a resolver, to be asked after every resolver already added.
508    /// Returns `&mut self`, for chaining.
509    pub fn add_resolver(&mut self, resolver: Arc<dyn PackageResolver>) -> &mut PackageCatalog {
510        self.resolvers.push(resolver);
511        self
512    }
513
514    /// The names of the compiled factories, in name order. The resolvers are
515    /// not asked; [`PackageResolver::list`] lists the package names a resolver
516    /// can resolve, when it can list them.
517    pub fn compiled_names(&self) -> impl Iterator<Item = &Name> + '_ {
518        self.compiled.keys()
519    }
520
521    /// The factory of the package `name`: the compiled factory of that name if
522    /// there is one, otherwise the factory returned by the first resolver that
523    /// knows the name. `Ok(None)` when no compiled factory and no resolver
524    /// knows the name.
525    ///
526    /// # Errors
527    ///
528    /// The [`ResolveError`]s of the first resolver that fails; later resolvers
529    /// are not asked.
530    pub fn resolve(&self, name: &str) -> Result<Option<PackageFactory>, Vec<ResolveError>> {
531        if let Some(factory) = self.compiled.get(name) {
532            return Ok(Some(factory.clone()));
533        }
534        for resolver in &self.resolvers {
535            if let Some(factory) = resolver.resolve(name)? {
536                return Ok(Some(factory));
537            }
538        }
539        Ok(None)
540    }
541}
542
543impl PackageCatalog {
544    /// The factories of the packages listed in `names` and of every package
545    /// they use, directly or not, in the order in which the packages should
546    /// register: each package after the packages it uses, in the order it
547    /// lists them, and each package once, however often it is listed or used.
548    /// The names are taken in the order given.
549    ///
550    /// A package is identified by its factory's [name](PackageFactory::name),
551    /// so two names that lead to one factory (for example, a resolver that
552    /// finds one file under two spellings) are one package. A package that uses
553    /// itself, directly or through others, is accepted: the walk skips a
554    /// package it has already found or is currently walking the uses of.
555    /// Packages that use each other therefore register in the order the walk
556    /// reaches them, and every other package still registers after the
557    /// packages it uses.
558    ///
559    /// # Errors
560    ///
561    /// Every problem found, each a [`UseError`] that identifies the package at
562    /// fault and the position in `names` of the name whose walk reached it:
563    /// a name that neither the compiled factories nor the resolvers know, or a
564    /// resolver's failure.
565    ///
566    /// # Examples
567    ///
568    /// ```
569    /// use flm_core::core::registry::{PackageCatalog, PackageEntry, PackageFactory};
570    ///
571    /// let mut catalog = PackageCatalog::new();
572    /// catalog.add_compiled(PackageFactory::new("base", |_| Ok(PackageEntry::new("base")))?);
573    /// catalog.add_compiled(PackageFactory::new("mine", |_| Ok(PackageEntry::new("mine")))?.uses("base"));
574    ///
575    /// let found = catalog.resolve_all(&["mine", "base"]).expect("both known");
576    /// let names: Vec<&str> = found.iter().map(|factory| factory.name().as_str()).collect();
577    /// assert_eq!(names, ["base", "mine"]);
578    /// assert_eq!(catalog.resolve_all(&["absent"]).unwrap_err()[0].index, 0);
579    /// # Ok::<(), Box<dyn std::error::Error>>(())
580    /// ```
581    pub fn resolve_all(&self, names: &[&str]) -> Result<Vec<PackageFactory>, Vec<UseError>> {
582        let mut walk = UseWalk { catalog: self, path: Vec::new(), found: Vec::new(), errors: Vec::new() };
583        for (index, name) in names.iter().enumerate() {
584            walk.add(index, name);
585        }
586        if walk.errors.is_empty() { Ok(walk.found) } else { Err(walk.errors) }
587    }
588}
589
590impl PackageCatalog {
591    /// Which package each of `factories` reaches: for each factory, by its
592    /// name, the names of the factories of the packages it uses, directly or
593    /// through others. Each used name is resolved through this catalog (a name
594    /// that does not resolve is left out: [`resolve_all`](PackageCatalog::resolve_all)
595    /// reported it). A package in a loop reaches itself.
596    ///
597    /// A package is identified by its factory's name, so two spellings of one
598    /// package (two names a resolver finds one factory for) reach and are
599    /// reached as one; of two factories met under one name (one given here,
600    /// one the catalog finds), the first met is kept. A host gives the result to the settings cascade
601    /// ([`Cascade::with_reach`](crate::core::settings::cascade::Cascade::with_reach)),
602    /// in which a package wins over the packages it reaches.
603    ///
604    /// # Examples
605    ///
606    /// ```
607    /// use flm_core::core::registry::{PackageCatalog, PackageEntry, PackageFactory};
608    ///
609    /// let factory = |name: &str| PackageFactory::new(name, |_| Ok(PackageEntry::new("p")));
610    /// let mut catalog = PackageCatalog::new();
611    /// catalog.add_compiled(factory("base")?);
612    /// catalog.add_compiled(factory("mid")?.uses("base"));
613    /// let mine = factory("mine")?.uses("mid");
614    ///
615    /// let reach = catalog.reach(&[mine]);
616    /// let reached: Vec<&str> = reach["mine"].iter().map(|name| name.as_str()).collect();
617    /// assert_eq!(reached, ["base", "mid"]);
618    /// # Ok::<(), flm_core::core::registry::PackageError>(())
619    /// ```
620    pub fn reach(&self, factories: &[PackageFactory]) -> Reach {
621        // The names of the factories each package met uses directly, resolved.
622        let mut direct: BTreeMap<Name, Vec<Name>> = BTreeMap::new();
623        let mut pending: Vec<PackageFactory> = factories.to_vec();
624        while let Some(factory) = pending.pop() {
625            if direct.contains_key(factory.name()) {
626                continue;
627            }
628            let mut used = Vec::new();
629            for name in factory.used() {
630                if let Ok(Some(found)) = self.resolve(name.as_str()) {
631                    used.push(found.name().clone());
632                    if !direct.contains_key(found.name()) {
633                        pending.push(found);
634                    }
635                }
636            }
637            direct.insert(factory.name().clone(), used);
638        }
639        factories
640            .iter()
641            .map(|factory| {
642                let mut reached = BTreeSet::new();
643                let mut next: Vec<&Name> = direct[factory.name()].iter().collect();
644                while let Some(name) = next.pop() {
645                    if reached.insert(name.clone()) {
646                        next.extend(direct.get(name).into_iter().flatten());
647                    }
648                }
649                (factory.name().clone(), reached)
650            })
651            .collect()
652    }
653}
654
655/// The state of the walk that [`PackageCatalog::resolve_all`] makes over the
656/// packages and the packages they use.
657// A loop of packages is skipped, not refused: its one harmful content, two
658// packages disagreeing on a value, is a problem of the settings, reported there.
659struct UseWalk<'c> {
660    catalog: &'c PackageCatalog,
661    /// The names of the factories of the packages being added, each package
662    /// using the next.
663    path: Vec<Name>,
664    found: Vec<PackageFactory>,
665    errors: Vec<UseError>,
666}
667
668impl UseWalk<'_> {
669    /// Whether the package whose factory has the name `name` was added
670    /// already or is being added.
671    fn met(&self, name: &str) -> bool {
672        self.found.iter().any(|factory| factory.name() == name) || self.path.iter().any(|entry| entry == name)
673    }
674
675    /// Adds the package `name` after the packages it uses, unless it was added
676    /// already or is being added; `index` is the position, in the names given
677    /// to `resolve_all`, of the name the walk started from.
678    fn add(&mut self, index: usize, name: &str) {
679        if self.met(name) {
680            return;
681        }
682        let used_by = self.path.last().cloned();
683        let error = |kind: UseErrorKind| UseError { index, package: Name::from(name), used_by: used_by.clone(), kind };
684        let factory = match self.catalog.resolve(name) {
685            Ok(Some(factory)) => factory,
686            Ok(None) => {
687                let known = self.catalog.compiled_names().cloned().collect();
688                self.errors.push(error(UseErrorKind::Unknown { known }));
689                return;
690            }
691            Err(failures) => {
692                self.errors.extend(failures.into_iter().map(|failure| error(UseErrorKind::Resolver(failure))));
693                return;
694            }
695        };
696        // The name asked for may be another spelling of a package met already.
697        if self.met(factory.name()) {
698            return;
699        }
700        self.path.push(factory.name().clone());
701        for used in factory.used() {
702            self.add(index, used.as_str());
703        }
704        self.path.pop();
705        self.found.push(factory);
706    }
707}
708
709/// A problem found by [`PackageCatalog::resolve_all`]: the package at fault,
710/// the position of the name whose walk reached it, and what is wrong.
711#[derive(Debug, Clone, PartialEq, Eq)]
712pub struct UseError {
713    /// The position, in the names given to `resolve_all`, of the name whose
714    /// walk reached the problem: the problem is in that name's package, or in
715    /// a package it uses, directly or not.
716    pub index: usize,
717    /// The package at fault.
718    pub package: Name,
719    /// The package that builds on the package at fault, or `None` when the
720    /// package at fault is one of the names given to `resolve_all`.
721    pub used_by: Option<Name>,
722    /// What is wrong.
723    pub kind: UseErrorKind,
724}
725
726/// What is wrong in a [`UseError`].
727#[derive(Debug, Clone, PartialEq, Eq)]
728pub enum UseErrorKind {
729    /// No compiled factory and no resolver knows the name; `known` lists the
730    /// names of the compiled factories.
731    Unknown {
732        /// The names of the compiled factories, in name order.
733        known: Vec<Name>,
734    },
735    /// A resolver knew the name and failed.
736    Resolver(ResolveError),
737}
738
739impl fmt::Display for UseError {
740    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
741        let package = &self.package;
742        let joined = |names: &[Name]| names.iter().map(Name::as_str).collect::<Vec<_>>().join("`, `");
743        match &self.kind {
744            UseErrorKind::Unknown { known } => {
745                match &self.used_by {
746                    Some(used_by) => write!(
747                        f,
748                        "package `{used_by}` builds on the package `{package}`, but no package of \
749                         that name is compiled into the program or can be loaded; packages \
750                         compiled into the program: `{}`",
751                        joined(known)
752                    ),
753                    None => write!(
754                        f,
755                        "the package `{package}` is requested, but no package of that name is \
756                         compiled into the program or can be loaded; packages compiled into the \
757                         program: `{}`",
758                        joined(known)
759                    ),
760                }
761            }
762            UseErrorKind::Resolver(failure) => match &self.used_by {
763                Some(used_by) => write!(
764                    f,
765                    "the package `{package}`, which package `{used_by}` builds on, could not be \
766                     loaded: {failure}"
767                ),
768                None => write!(f, "the package `{package}` could not be loaded: {failure}"),
769            },
770        }
771    }
772}
773
774impl std::error::Error for UseError {}
775
776impl fmt::Debug for PackageCatalog {
777    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
778        f.debug_struct("PackageCatalog")
779            .field("compiled", &self.compiled.keys().collect::<Vec<_>>())
780            .field("resolvers", &self.resolvers.len())
781            .finish()
782    }
783}
784
785/// A package ready to register: a named bundle of features together with the
786/// packages it builds on.
787///
788/// A package is the unit in which features are shipped and registered
789/// together; [`crate::stdlib::add_features`] adds the standard features to a
790/// package. Pass a package to
791/// [`RegistryBuilder::use_package`](super::RegistryBuilder::use_package),
792/// which adds the features of the packages it uses first, then its own
793/// features, in order, together with the chains of the feature order each
794/// package states. The registry builder adds a package at most once,
795/// however many times it is passed or used, so two packages may each use a
796/// third and its features are still registered once. The order in which the
797/// features are added is their implicit order; the chains may change it
798/// ([`super::order`]).
799///
800/// # Examples
801///
802/// ```
803/// use std::sync::Arc;
804/// use flm_core::core::registry::{
805///     BuildError, FeatureBuilder, FeatureInfo, FlmFeature, PackageEntry,
806/// };
807///
808/// struct Base;
809/// impl FlmFeature for Base {
810///     fn info(&self) -> FeatureInfo { FeatureInfo::new("base", "Base") }
811///     fn register(&self, _b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> { Ok(()) }
812/// }
813///
814/// let base = PackageEntry::new("base").feature(Arc::new(Base));
815/// let mine = PackageEntry::new("mine").uses(base);
816/// assert_eq!(mine.uses.len(), 1);
817/// ```
818#[derive(Clone)]
819pub struct PackageEntry {
820    /// The package's name. The registry builder recognizes a package it has
821    /// already registered by this name, so it treats two entries of the same
822    /// name as the same package.
823    pub name: Name,
824    /// The packages this package uses; their features are registered before
825    /// this package's own features.
826    pub uses: Vec<PackageEntry>,
827    /// The package's own features, in the order they are added to the
828    /// registry builder.
829    pub features: Vec<Arc<dyn FlmFeature>>,
830    /// The chains of the feature order that the package states, such as
831    /// `math-mathjax < phfqit` for a package whose definitions are to apply
832    /// over those of `math-mathjax`. They may name the features of any
833    /// package; the registry build combines them with every other chain it is
834    /// given ([`super::order`]).
835    pub feature_order: Vec<FeatureChain>,
836}
837
838impl PackageEntry {
839    /// A package called `name`, which uses no package and holds no feature
840    /// yet.
841    pub fn new(name: impl Into<Name>) -> PackageEntry {
842        PackageEntry {
843            name: name.into(),
844            uses: Vec::new(),
845            features: Vec::new(),
846            feature_order: Vec::new(),
847        }
848    }
849
850    /// Adds a package this package uses, after those already added. Returns
851    /// `self`, for chaining.
852    pub fn uses(mut self, package: PackageEntry) -> PackageEntry {
853        self.uses.push(package);
854        self
855    }
856
857    /// Adds one of this package's own features, after those already added.
858    /// Returns `self`, for chaining.
859    pub fn feature(mut self, feature: Arc<dyn FlmFeature>) -> PackageEntry {
860        self.features.push(feature);
861        self
862    }
863
864    /// Adds one chain of the feature order that this package states, after
865    /// those already added. Returns `self`, for chaining.
866    ///
867    /// # Examples
868    ///
869    /// ```
870    /// use flm_core::core::registry::{FeatureChain, PackageEntry};
871    ///
872    /// let chain = FeatureChain::parse("math-mathjax < mine", "package mine")?;
873    /// let mine = PackageEntry::new("mine").feature_order(chain);
874    /// assert_eq!(mine.feature_order.len(), 1);
875    /// # Ok::<(), flm_core::core::registry::ChainError>(())
876    /// ```
877    pub fn feature_order(mut self, chain: FeatureChain) -> PackageEntry {
878        self.feature_order.push(chain);
879        self
880    }
881}
882
883impl fmt::Debug for PackageEntry {
884    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885        f.debug_struct("PackageEntry")
886            .field("name", &self.name)
887            .field("uses", &self.uses.iter().map(|p| &p.name).collect::<Vec<_>>())
888            .field("features", &self.features.iter().map(|x| x.info().name).collect::<Vec<_>>())
889            .field("feature_order", &self.feature_order.iter().map(ToString::to_string).collect::<Vec<_>>())
890            .finish()
891    }
892}
893
894#[cfg(test)]
895mod tests {
896    use super::*;
897
898    /// A resolver that knows the factories it holds under one or more names each.
899    struct Spellings(Vec<(&'static str, PackageFactory)>);
900
901    impl PackageResolver for Spellings {
902        fn resolve(&self, name: &str) -> Result<Option<PackageFactory>, Vec<ResolveError>> {
903            Ok(self.0.iter().find(|(spelling, _)| *spelling == name).map(|(_, factory)| factory.clone()))
904        }
905    }
906
907    fn factory(name: &str, uses: &[&str]) -> PackageFactory {
908        let mut factory = PackageFactory::new(name, |_| Ok(PackageEntry::new("p"))).unwrap();
909        for used in uses {
910            factory = factory.uses(*used);
911        }
912        factory
913    }
914
915    fn names(reach: &Reach, from: &str) -> Vec<String> {
916        reach[from].iter().map(|name| name.to_string()).collect()
917    }
918
919    #[test]
920    fn the_reach_follows_uses_through_others_and_a_loop_reaches_itself() {
921        let mut catalog = PackageCatalog::new();
922        // `a` uses `b`, which uses `c` and the unknown `nosuch`; `c` uses `b`, a loop.
923        catalog.add_compiled(factory("b", &["c", "nosuch"]));
924        catalog.add_compiled(factory("c", &["b"]));
925        let (a, d) = (factory("a", &["b"]), factory("d", &[]));
926        let reach = catalog.reach(&[a, d, factory("b", &["c", "nosuch"])]);
927        assert_eq!(names(&reach, "a"), ["b", "c"]);
928        assert_eq!(names(&reach, "b"), ["b", "c"]);
929        assert!(reach["d"].is_empty());
930        // Only the factories given are keys.
931        assert_eq!(reach.keys().map(Name::as_str).collect::<Vec<_>>(), ["a", "b", "d"]);
932    }
933
934    #[test]
935    fn the_reach_keys_two_spellings_of_one_package_by_its_factory_name() {
936        let shared = factory("lib/shared.yaml", &[]);
937        let mut catalog = PackageCatalog::new();
938        catalog.add_resolver(Arc::new(Spellings(vec![("shared", shared.clone()), ("./lib/shared", shared)])));
939        let one = factory("one.yaml", &["shared"]);
940        let two = factory("two.yaml", &["./lib/shared", "shared"]);
941        let reach = catalog.reach(&[one, two]);
942        assert_eq!(names(&reach, "one.yaml"), ["lib/shared.yaml"]);
943        assert_eq!(names(&reach, "two.yaml"), ["lib/shared.yaml"]);
944    }
945}