mads-core 0.9.1

Framework-neutral dependency injection, configuration, and lifecycle core for MADS.rs
Documentation
//! Deterministic discovery and lookup of statically registered metadata.

use std::any::TypeId;
use std::sync::OnceLock;

use crate::{
    Diagnostic, Error, MADS001, MADS002, MADS003, Module, ModuleDescriptor, ProviderDescriptor,
    Result,
};

inventory::collect!(ProviderDescriptor);
inventory::collect!(ModuleDescriptor);

/// Provides deterministic access to statically registered providers and modules.
pub struct Catalog;

impl Catalog {
    /// Returns every registered provider in deterministic declaration order.
    pub fn providers() -> Vec<&'static ProviderDescriptor> {
        provider_cache().clone()
    }

    /// Returns every registered module in deterministic declaration order.
    pub fn modules() -> Vec<&'static ModuleDescriptor> {
        let mut modules: Vec<_> = inventory::iter::<ModuleDescriptor>.into_iter().collect();
        modules.sort_by(|left, right| {
            left.type_name()
                .cmp(right.type_name())
                .then_with(|| compare_locations(left.location(), right.location()))
        });
        modules
    }

    /// Selects the single static module descriptor registered for `M`.
    #[allow(clippy::result_large_err)]
    pub fn module_for<M: Module>() -> Result<&'static ModuleDescriptor> {
        let type_id = TypeId::of::<M>();
        let modules: Vec<_> = Self::modules()
            .into_iter()
            .filter(|descriptor| descriptor.type_id() == type_id)
            .collect();

        match modules.as_slice() {
            [] => Err(Error::new(
                Diagnostic::new(
                    MADS003,
                    "missing module metadata",
                    "no statically declared module exists for this type",
                )
                .with_subject(std::any::type_name::<M>()),
            )),
            [module] => Ok(module),
            [first, rest @ ..]
                if rest
                    .iter()
                    .all(|module| module_exact_identity(first, module)) =>
            {
                Err(Error::new(
                    Diagnostic::new(
                        MADS001,
                        "duplicate module declaration",
                        "the same module declaration was registered more than once",
                    )
                    .with_subject(std::any::type_name::<M>()),
                ))
            }
            _ => Err(Error::new(
                Diagnostic::new(
                    MADS002,
                    "ambiguous module declaration",
                    "multiple module declarations describe the same module type",
                )
                .with_subject(std::any::type_name::<M>()),
            )),
        }
    }

    /// Selects the single static provider registered for `T`.
    #[allow(clippy::result_large_err)]
    pub fn provider_for<T>() -> Result<&'static ProviderDescriptor>
    where
        T: Send + Sync + 'static,
    {
        let type_id = TypeId::of::<T>();
        let providers: Vec<_> = provider_cache()
            .iter()
            .copied()
            .filter(|descriptor| descriptor.type_id() == type_id)
            .collect();

        match providers.as_slice() {
            [] => Err(Error::new(
                Diagnostic::new(
                    MADS003,
                    "missing provider",
                    "no statically declared provider exists for this type",
                )
                .with_subject(std::any::type_name::<T>()),
            )),
            [provider] => Ok(provider),
            [first, rest @ ..] if rest.iter().all(|provider| exact_identity(first, provider)) => {
                Err(Error::new(
                    Diagnostic::new(
                        MADS001,
                        "duplicate provider declaration",
                        "the same provider declaration was registered more than once",
                    )
                    .with_subject(std::any::type_name::<T>()),
                ))
            }
            _ => Err(Error::new(
                Diagnostic::new(
                    MADS002,
                    "ambiguous provider binding",
                    "multiple provider declarations produce the same concrete type",
                )
                .with_subject(std::any::type_name::<T>()),
            )),
        }
    }
}

fn provider_cache() -> &'static Vec<&'static ProviderDescriptor> {
    static PROVIDERS: OnceLock<Vec<&'static ProviderDescriptor>> = OnceLock::new();
    PROVIDERS.get_or_init(|| {
        let mut providers: Vec<_> = inventory::iter::<ProviderDescriptor>.into_iter().collect();
        providers.sort_by(|left, right| {
            left.type_name()
                .cmp(right.type_name())
                .then_with(|| left.kind().cmp(&right.kind()))
                .then_with(|| compare_locations(left.location(), right.location()))
        });
        providers
    })
}

fn compare_locations(
    left: crate::SourceLocation,
    right: crate::SourceLocation,
) -> std::cmp::Ordering {
    left.file
        .cmp(right.file)
        .then_with(|| left.line.cmp(&right.line))
        .then_with(|| left.column.cmp(&right.column))
}

fn exact_identity(left: &ProviderDescriptor, right: &ProviderDescriptor) -> bool {
    left.type_id() == right.type_id()
        && left.kind() == right.kind()
        && left.type_name() == right.type_name()
        && left.namespace() == right.namespace()
        && left.visibility() == right.visibility()
        && left.location() == right.location()
        && left.dependencies().len() == right.dependencies().len()
        && left
            .dependencies()
            .iter()
            .zip(right.dependencies())
            .all(|(left, right)| left.type_id() == right.type_id())
}

fn module_exact_identity(left: &ModuleDescriptor, right: &ModuleDescriptor) -> bool {
    left.type_id() == right.type_id()
        && left.type_name() == right.type_name()
        && left.namespace() == right.namespace()
        && left.location() == right.location()
        && left.imports().len() == right.imports().len()
        && left
            .imports()
            .iter()
            .zip(right.imports())
            .all(|(left, right)| {
                left.type_id() == right.type_id() && left.type_name() == right.type_name()
            })
}