Skip to main content

mads_core/
catalog.rs

1//! Deterministic discovery and lookup of statically registered metadata.
2
3use std::any::TypeId;
4use std::sync::OnceLock;
5
6use crate::{
7    Diagnostic, Error, MADS001, MADS002, MADS003, Module, ModuleDescriptor, ProviderDescriptor,
8    Result,
9};
10
11inventory::collect!(ProviderDescriptor);
12inventory::collect!(ModuleDescriptor);
13
14/// Provides deterministic access to statically registered providers and modules.
15pub struct Catalog;
16
17impl Catalog {
18    /// Returns every registered provider in deterministic declaration order.
19    pub fn providers() -> Vec<&'static ProviderDescriptor> {
20        provider_cache().clone()
21    }
22
23    /// Returns every registered module in deterministic declaration order.
24    pub fn modules() -> Vec<&'static ModuleDescriptor> {
25        let mut modules: Vec<_> = inventory::iter::<ModuleDescriptor>.into_iter().collect();
26        modules.sort_by(|left, right| {
27            left.type_name()
28                .cmp(right.type_name())
29                .then_with(|| compare_locations(left.location(), right.location()))
30        });
31        modules
32    }
33
34    /// Selects the single static module descriptor registered for `M`.
35    #[allow(clippy::result_large_err)]
36    pub fn module_for<M: Module>() -> Result<&'static ModuleDescriptor> {
37        let type_id = TypeId::of::<M>();
38        let modules: Vec<_> = Self::modules()
39            .into_iter()
40            .filter(|descriptor| descriptor.type_id() == type_id)
41            .collect();
42
43        match modules.as_slice() {
44            [] => Err(Error::new(
45                Diagnostic::new(
46                    MADS003,
47                    "missing module metadata",
48                    "no statically declared module exists for this type",
49                )
50                .with_subject(std::any::type_name::<M>()),
51            )),
52            [module] => Ok(module),
53            [first, rest @ ..]
54                if rest
55                    .iter()
56                    .all(|module| module_exact_identity(first, module)) =>
57            {
58                Err(Error::new(
59                    Diagnostic::new(
60                        MADS001,
61                        "duplicate module declaration",
62                        "the same module declaration was registered more than once",
63                    )
64                    .with_subject(std::any::type_name::<M>()),
65                ))
66            }
67            _ => Err(Error::new(
68                Diagnostic::new(
69                    MADS002,
70                    "ambiguous module declaration",
71                    "multiple module declarations describe the same module type",
72                )
73                .with_subject(std::any::type_name::<M>()),
74            )),
75        }
76    }
77
78    /// Selects the single static provider registered for `T`.
79    #[allow(clippy::result_large_err)]
80    pub fn provider_for<T>() -> Result<&'static ProviderDescriptor>
81    where
82        T: Send + Sync + 'static,
83    {
84        let type_id = TypeId::of::<T>();
85        let providers: Vec<_> = provider_cache()
86            .iter()
87            .copied()
88            .filter(|descriptor| descriptor.type_id() == type_id)
89            .collect();
90
91        match providers.as_slice() {
92            [] => Err(Error::new(
93                Diagnostic::new(
94                    MADS003,
95                    "missing provider",
96                    "no statically declared provider exists for this type",
97                )
98                .with_subject(std::any::type_name::<T>()),
99            )),
100            [provider] => Ok(provider),
101            [first, rest @ ..] if rest.iter().all(|provider| exact_identity(first, provider)) => {
102                Err(Error::new(
103                    Diagnostic::new(
104                        MADS001,
105                        "duplicate provider declaration",
106                        "the same provider declaration was registered more than once",
107                    )
108                    .with_subject(std::any::type_name::<T>()),
109                ))
110            }
111            _ => Err(Error::new(
112                Diagnostic::new(
113                    MADS002,
114                    "ambiguous provider binding",
115                    "multiple provider declarations produce the same concrete type",
116                )
117                .with_subject(std::any::type_name::<T>()),
118            )),
119        }
120    }
121}
122
123fn provider_cache() -> &'static Vec<&'static ProviderDescriptor> {
124    static PROVIDERS: OnceLock<Vec<&'static ProviderDescriptor>> = OnceLock::new();
125    PROVIDERS.get_or_init(|| {
126        let mut providers: Vec<_> = inventory::iter::<ProviderDescriptor>.into_iter().collect();
127        providers.sort_by(|left, right| {
128            left.type_name()
129                .cmp(right.type_name())
130                .then_with(|| left.kind().cmp(&right.kind()))
131                .then_with(|| compare_locations(left.location(), right.location()))
132        });
133        providers
134    })
135}
136
137fn compare_locations(
138    left: crate::SourceLocation,
139    right: crate::SourceLocation,
140) -> std::cmp::Ordering {
141    left.file
142        .cmp(right.file)
143        .then_with(|| left.line.cmp(&right.line))
144        .then_with(|| left.column.cmp(&right.column))
145}
146
147fn exact_identity(left: &ProviderDescriptor, right: &ProviderDescriptor) -> bool {
148    left.type_id() == right.type_id()
149        && left.kind() == right.kind()
150        && left.type_name() == right.type_name()
151        && left.namespace() == right.namespace()
152        && left.visibility() == right.visibility()
153        && left.location() == right.location()
154        && left.dependencies().len() == right.dependencies().len()
155        && left
156            .dependencies()
157            .iter()
158            .zip(right.dependencies())
159            .all(|(left, right)| left.type_id() == right.type_id())
160}
161
162fn module_exact_identity(left: &ModuleDescriptor, right: &ModuleDescriptor) -> bool {
163    left.type_id() == right.type_id()
164        && left.type_name() == right.type_name()
165        && left.namespace() == right.namespace()
166        && left.location() == right.location()
167        && left.imports().len() == right.imports().len()
168        && left
169            .imports()
170            .iter()
171            .zip(right.imports())
172            .all(|(left, right)| {
173                left.type_id() == right.type_id() && left.type_name() == right.type_name()
174            })
175}