Skip to main content

configbuilder_pattern_loader/
dependency_order_macro.rs

1/// Load a set of optional feature sections in dependency order.
2///
3/// Computes a topological load order from each type's [`OptionalSection::requires`]
4/// declarations and calls [`FeatureRegistryOps::load`] in that order. All loaded
5/// values are discarded; use `registry.records()` after the call to inspect results.
6///
7/// Returns `Err(ConfigError::Validation)` if a dependency cycle is detected.
8/// The first load failure propagates and stops further loading.
9///
10/// # Examples
11///
12/// ```rust,no_run
13/// use configbuilder_pattern_loader::{load_in_order, DefaultLoader, FeatureRegistry, FeatureRegistryOps as _, OptionalSection};
14///
15/// # #[derive(serde::Deserialize)] struct CacheConfig;
16/// # impl OptionalSection for CacheConfig { fn section_name() -> &'static str { "cache" } }
17/// # #[derive(serde::Deserialize)] struct BrokerConfig;
18/// # impl OptionalSection for BrokerConfig { fn section_name() -> &'static str { "broker" } }
19/// # fn real_loader() -> DefaultLoader { unimplemented!() }
20/// let loader = real_loader();
21/// let mut registry = FeatureRegistry::new();
22///
23/// load_in_order!(&mut registry, &loader, CacheConfig, BrokerConfig)
24///     .expect("dependency order must be acyclic");
25///
26/// registry.validate_dependencies().expect("all dependencies satisfied");
27/// println!("{}", registry.summary());
28/// ```
29#[macro_export]
30macro_rules! load_in_order {
31    ($registry:expr, $loader:expr, $($ty:ty),+ $(,)?) => {{
32        use $crate::{FeatureRegistryOps as _, OptionalSection as _, TopologyOps as _};
33
34        let _names: &[&str] = &[$(<$ty as OptionalSection>::section_name()),+];
35        let _requires: &[&[&str]] = &[$(<$ty as OptionalSection>::requires()),+];
36
37        match $crate::Topology.sort(_names, _requires) {
38            Err(_msg) => Err(_msg),
39            Ok(_order) => {
40                let mut _result: Result<(), $crate::ConfigError> = Ok(());
41                'load_loop: for &_idx in &_order {
42                    let mut _j: usize = 0;
43                    $(
44                        if _idx == _j {
45                            if let Err(_e) = $registry.load::<$ty>($loader) {
46                                _result = Err(_e);
47                                break 'load_loop;
48                            }
49                        }
50                        _j += 1;
51                    )+
52                }
53                _result
54            }
55        }
56    }};
57}