Skip to main content

rustclamp_kernel/
lib.rs

1//! Typed capability resolution for Clamp applications.
2
3#![forbid(unsafe_code)]
4#![deny(missing_docs)]
5
6use std::collections::{BTreeMap, BTreeSet, VecDeque};
7use std::error::Error;
8use std::fmt;
9use std::marker::PhantomData;
10use std::sync::Arc;
11
12use rustclamp_core::{
13    ApplicationId, Capability, CapabilityId, Contribution, ContributionId, ContributionTarget,
14    ContributionTargetId, ExecutionId, Module, ModuleId, ProcessId, Provides, Qualifier,
15    QualifierId, Requires,
16};
17
18/// A caller-owned application blueprint containing process roots and module relations.
19///
20/// The blueprint describes declarations only. [`ApplicationBlueprint::project`]
21/// derives the reachable module set for one process without constructing modules.
22pub struct ApplicationBlueprint {
23    application: ApplicationId,
24    modules: BTreeSet<ModuleId>,
25    executions: BTreeMap<ExecutionId, ModuleId>,
26    processes: BTreeMap<ProcessId, Vec<ExecutionId>>,
27    providers: Vec<(ModuleId, CapabilityId, Option<QualifierId>)>,
28    requirements: Vec<(ModuleId, CapabilityId, Option<QualifierId>, bool)>,
29    selections: Vec<(ModuleId, CapabilityId, Option<QualifierId>, ModuleId)>,
30    defaults: Vec<(ModuleId, CapabilityId, Option<QualifierId>, ModuleId)>,
31    replacements: Vec<(CapabilityId, Option<QualifierId>, ModuleId, ModuleId)>,
32    exclusions: BTreeSet<ModuleId>,
33    target_consumptions: Vec<(ModuleId, ContributionTargetId, QualifierId)>,
34    contributions: Vec<(
35        ModuleId,
36        ContributionTargetId,
37        QualifierId,
38        ContributionId,
39        bool,
40    )>,
41}
42
43impl ApplicationBlueprint {
44    /// Creates an empty architecture blueprint with a stable identity.
45    pub fn new(application: ApplicationId) -> Self {
46        Self {
47            application,
48            modules: BTreeSet::new(),
49            executions: BTreeMap::new(),
50            processes: BTreeMap::new(),
51            providers: Vec::new(),
52            requirements: Vec::new(),
53            selections: Vec::new(),
54            defaults: Vec::new(),
55            replacements: Vec::new(),
56            exclusions: BTreeSet::new(),
57            target_consumptions: Vec::new(),
58            contributions: Vec::new(),
59        }
60    }
61
62    /// Declares a module that may be included in one or more process projections.
63    pub fn add_module(&mut self, module: ModuleId) -> &mut Self {
64        self.modules.insert(module);
65        self
66    }
67
68    /// Declares an execution root implemented by a module.
69    pub fn add_execution(&mut self, execution: ExecutionId, module: ModuleId) -> &mut Self {
70        self.executions.insert(execution, module);
71        self
72    }
73
74    /// Declares one or more execution roots for a runnable process projection.
75    pub fn add_process(&mut self, process: ProcessId, roots: Vec<ExecutionId>) -> &mut Self {
76        self.processes.insert(process, roots);
77        self
78    }
79
80    /// Declares a process with one execution root: the module, its execution, and
81    /// the process that runs only that execution.
82    pub fn add_root(
83        &mut self,
84        process: ProcessId,
85        execution: ExecutionId,
86        module: ModuleId,
87    ) -> &mut Self {
88        self.add_module(module)
89            .add_execution(execution, module)
90            .add_process(process, vec![execution])
91    }
92
93    /// Connects a module requirement to its already selected capability provider.
94    pub fn require_provider(
95        &mut self,
96        consumer: ModuleId,
97        capability: CapabilityId,
98        qualifier: Option<QualifierId>,
99        provider: ModuleId,
100    ) -> &mut Self {
101        self.provide_capability(provider, capability, qualifier)
102            .require_capability(consumer, capability, qualifier, false)
103            .select_provider(consumer, capability, qualifier, provider);
104        self
105    }
106
107    /// Declares that a module provides a capability for an optional qualifier.
108    pub fn provide_capability(
109        &mut self,
110        module: ModuleId,
111        capability: CapabilityId,
112        qualifier: Option<QualifierId>,
113    ) -> &mut Self {
114        self.providers.push((module, capability, qualifier));
115        self
116    }
117
118    /// Declares a capability requirement. Optional requirements do not activate a provider.
119    pub fn require_capability(
120        &mut self,
121        consumer: ModuleId,
122        capability: CapabilityId,
123        qualifier: Option<QualifierId>,
124        optional: bool,
125    ) -> &mut Self {
126        self.requirements
127            .push((consumer, capability, qualifier, optional));
128        self
129    }
130
131    /// Selects a provider for one module requirement.
132    pub fn select_provider(
133        &mut self,
134        consumer: ModuleId,
135        capability: CapabilityId,
136        qualifier: Option<QualifierId>,
137        provider: ModuleId,
138    ) -> &mut Self {
139        self.selections
140            .push((consumer, capability, qualifier, provider));
141        self
142    }
143
144    /// Declares a default provider for one module requirement.
145    pub fn default_provider(
146        &mut self,
147        consumer: ModuleId,
148        capability: CapabilityId,
149        qualifier: Option<QualifierId>,
150        provider: ModuleId,
151    ) -> &mut Self {
152        self.defaults
153            .push((consumer, capability, qualifier, provider));
154        self
155    }
156
157    /// Replaces one provider with another for a capability and qualifier.
158    pub fn replace_provider(
159        &mut self,
160        capability: CapabilityId,
161        qualifier: Option<QualifierId>,
162        replaced: ModuleId,
163        replacement: ModuleId,
164    ) -> &mut Self {
165        self.replacements
166            .push((capability, qualifier, replaced, replacement));
167        self
168    }
169
170    /// Excludes a module from provider selection and process reachability.
171    pub fn exclude_module(&mut self, module: ModuleId) -> &mut Self {
172        self.exclusions.insert(module);
173        self
174    }
175
176    /// Declares that a module consumes a qualified contribution target.
177    pub fn consume_target(
178        &mut self,
179        consumer: ModuleId,
180        target: ContributionTargetId,
181        qualifier: QualifierId,
182    ) -> &mut Self {
183        self.target_consumptions.push((consumer, target, qualifier));
184        self
185    }
186
187    /// Declares that a module contributes to a qualified target.
188    pub fn add_contribution(
189        &mut self,
190        contributor: ModuleId,
191        target: ContributionTargetId,
192        qualifier: QualifierId,
193        contribution: ContributionId,
194    ) -> &mut Self {
195        self.contributions
196            .push((contributor, target, qualifier, contribution, true));
197        self
198    }
199
200    /// Declares an optional contribution that may be discarded without a target.
201    pub fn add_optional_contribution(
202        &mut self,
203        contributor: ModuleId,
204        target: ContributionTargetId,
205        qualifier: QualifierId,
206        contribution: ContributionId,
207    ) -> &mut Self {
208        self.contributions
209            .push((contributor, target, qualifier, contribution, false));
210        self
211    }
212
213    /// Derives the reachable module projection from a process's execution roots.
214    pub fn project(&self, process: ProcessId) -> Result<ProcessProjection, ProjectionError> {
215        let application = self.application;
216        let mut providers_by_capability =
217            BTreeMap::<(CapabilityId, Option<QualifierId>), Vec<ModuleId>>::new();
218        for (module, capability, qualifier) in &self.providers {
219            providers_by_capability
220                .entry((*capability, *qualifier))
221                .or_default()
222                .push(*module);
223        }
224        for providers in providers_by_capability.values_mut() {
225            providers.sort_unstable();
226            providers.dedup();
227        }
228        let mut requirements_by_owner =
229            BTreeMap::<ModuleId, Vec<(CapabilityId, Option<QualifierId>, bool)>>::new();
230        for (consumer, capability, qualifier, optional) in &self.requirements {
231            requirements_by_owner.entry(*consumer).or_default().push((
232                *capability,
233                *qualifier,
234                *optional,
235            ));
236        }
237        let mut selections = BTreeMap::new();
238        for (consumer, capability, qualifier, provider) in &self.selections {
239            selections
240                .entry((*consumer, *capability, *qualifier))
241                .or_insert(*provider);
242        }
243        let mut defaults =
244            BTreeMap::<(ModuleId, CapabilityId, Option<QualifierId>), Vec<ModuleId>>::new();
245        for (consumer, capability, qualifier, provider) in &self.defaults {
246            defaults
247                .entry((*consumer, *capability, *qualifier))
248                .or_default()
249                .push(*provider);
250        }
251        for providers in defaults.values_mut() {
252            providers.sort_unstable();
253            providers.dedup();
254        }
255        let mut targets_by_owner =
256            BTreeMap::<ModuleId, Vec<(ContributionTargetId, QualifierId)>>::new();
257        let mut consumers_by_target =
258            BTreeMap::<(ContributionTargetId, QualifierId), Vec<ModuleId>>::new();
259        for (consumer, target, qualifier) in &self.target_consumptions {
260            targets_by_owner
261                .entry(*consumer)
262                .or_default()
263                .push((*target, *qualifier));
264            consumers_by_target
265                .entry((*target, *qualifier))
266                .or_default()
267                .push(*consumer);
268        }
269        let mut contributions_by_target =
270            BTreeMap::<(ContributionTargetId, QualifierId), Vec<(ModuleId, ContributionId)>>::new();
271        for (contributor, target, qualifier, contribution, _) in &self.contributions {
272            contributions_by_target
273                .entry((*target, *qualifier))
274                .or_default()
275                .push((*contributor, *contribution));
276        }
277        let replacements = self
278            .replacements
279            .iter()
280            .map(|(capability, qualifier, old, new)| ((*capability, *qualifier, *old), *new))
281            .collect::<BTreeMap<_, _>>();
282        let replacement_sources = self
283            .replacements
284            .iter()
285            .map(|(capability, qualifier, old, new)| ((*capability, *qualifier, *new), *old))
286            .collect::<BTreeMap<_, _>>();
287        let roots = self
288            .processes
289            .get(&process)
290            .ok_or(ProjectionError::MissingProcess {
291                application,
292                process,
293            })?;
294        if roots.is_empty() {
295            return Err(ProjectionError::EmptyProcessRoots {
296                application,
297                process,
298            });
299        }
300        let mut roots = roots.clone();
301        roots.sort_unstable();
302
303        let mut pending = VecDeque::new();
304        let mut reached = BTreeMap::<ModuleId, IncludedModule>::new();
305        let mut edges = Vec::<(ModuleId, ModuleId)>::new();
306        let mut resolved_requirements = Vec::new();
307        let mut resolved_contributions = Vec::new();
308        for execution in &roots {
309            let module = self.executions.get(execution).copied().ok_or(
310                ProjectionError::MissingExecution {
311                    application,
312                    process,
313                    execution: *execution,
314                },
315            )?;
316            self.ensure_module(application, process, module)?;
317            if self.exclusions.contains(&module) {
318                return Err(ProjectionError::ExcludedRoot {
319                    application,
320                    process,
321                    module,
322                });
323            }
324            if let std::collections::btree_map::Entry::Vacant(entry) = reached.entry(module) {
325                entry.insert(IncludedModule {
326                    module,
327                    path: vec![module],
328                    reason: InclusionReason::ExecutionRoot {
329                        execution: *execution,
330                    },
331                });
332                pending.push_back(module);
333            }
334        }
335
336        while let Some(consumer) = pending.pop_front() {
337            let mut next = Vec::<(ModuleId, InclusionReason)>::new();
338            for (capability, qualifier, optional) in
339                requirements_by_owner.get(&consumer).into_iter().flatten()
340            {
341                let requirement_key = (consumer, *capability, *qualifier);
342                let explicit = selections.get(&requirement_key).copied();
343                let defaults = defaults.get(&requirement_key).cloned().unwrap_or_default();
344                if explicit.is_none() && defaults.len() > 1 {
345                    return Err(ProjectionError::AmbiguousProvider {
346                        application,
347                        process,
348                        required_by: consumer,
349                        capability: *capability,
350                        qualifier: *qualifier,
351                        candidates: defaults,
352                    });
353                }
354                let selection = if explicit.is_some() {
355                    ProviderSelection::Explicit
356                } else if !defaults.is_empty() {
357                    ProviderSelection::Default
358                } else {
359                    ProviderSelection::Unique
360                };
361                let selected = explicit.or_else(|| defaults.first().copied());
362                let mut candidates = providers_by_capability
363                    .get(&(*capability, *qualifier))
364                    .cloned()
365                    .unwrap_or_default();
366                if let Some(chosen) = selected {
367                    let provider = replacements
368                        .get(&(*capability, *qualifier, chosen))
369                        .copied()
370                        .unwrap_or(chosen);
371                    if self.exclusions.contains(&provider) {
372                        return Err(ProjectionError::ExcludedProvider {
373                            application,
374                            process,
375                            required_by: consumer,
376                            capability: *capability,
377                            qualifier: *qualifier,
378                            provider,
379                        });
380                    }
381                    if (!candidates.contains(&chosen) && !candidates.contains(&provider))
382                        || !providers_by_capability
383                            .get(&(*capability, *qualifier))
384                            .is_some_and(|providers| providers.contains(&provider))
385                    {
386                        return Err(ProjectionError::UnavailableProvider {
387                            application,
388                            process,
389                            required_by: consumer,
390                            capability: *capability,
391                            qualifier: *qualifier,
392                            provider,
393                        });
394                    }
395                    next.push((
396                        provider,
397                        InclusionReason::CapabilityProvider {
398                            required_by: consumer,
399                            capability: *capability,
400                            qualifier: *qualifier,
401                            selection,
402                            replaced: (provider != chosen).then_some(chosen),
403                        },
404                    ));
405                    resolved_requirements.push(ResolvedRequirement {
406                        consumer,
407                        capability: *capability,
408                        qualifier: *qualifier,
409                        provider: Some(provider),
410                        optional: *optional,
411                        selection,
412                        replaced: (provider != chosen).then_some(chosen),
413                    });
414                    continue;
415                }
416                if *optional {
417                    resolved_requirements.push(ResolvedRequirement {
418                        consumer,
419                        capability: *capability,
420                        qualifier: *qualifier,
421                        provider: None,
422                        optional: true,
423                        selection: ProviderSelection::OptionalAbsent,
424                        replaced: None,
425                    });
426                    continue;
427                }
428                for candidate in &mut candidates {
429                    *candidate = replacements
430                        .get(&(*capability, *qualifier, *candidate))
431                        .copied()
432                        .unwrap_or(*candidate);
433                }
434                if let Some(provider) = candidates.iter().find(|candidate| {
435                    !providers_by_capability
436                        .get(&(*capability, *qualifier))
437                        .is_some_and(|providers| providers.contains(candidate))
438                }) {
439                    return Err(ProjectionError::UnavailableProvider {
440                        application,
441                        process,
442                        required_by: consumer,
443                        capability: *capability,
444                        qualifier: *qualifier,
445                        provider: *provider,
446                    });
447                }
448                candidates.retain(|module| {
449                    providers_by_capability
450                        .get(&(*capability, *qualifier))
451                        .is_some_and(|providers| providers.contains(module))
452                });
453                candidates.retain(|module| !self.exclusions.contains(module));
454                candidates.sort_unstable();
455                candidates.dedup();
456                match candidates.as_slice() {
457                    [] if providers_by_capability.contains_key(&(*capability, *qualifier)) => {
458                        let provider = providers_by_capability[&(*capability, *qualifier)][0];
459                        return Err(ProjectionError::ExcludedProvider {
460                            application,
461                            process,
462                            required_by: consumer,
463                            capability: *capability,
464                            qualifier: *qualifier,
465                            provider,
466                        });
467                    }
468                    [] => {
469                        return Err(ProjectionError::MissingProvider {
470                            application,
471                            process,
472                            required_by: consumer,
473                            capability: *capability,
474                            qualifier: *qualifier,
475                        });
476                    }
477                    [provider] => {
478                        let replaced = replacement_sources
479                            .get(&(*capability, *qualifier, *provider))
480                            .copied();
481                        next.push((
482                            *provider,
483                            InclusionReason::CapabilityProvider {
484                                required_by: consumer,
485                                capability: *capability,
486                                qualifier: *qualifier,
487                                selection: ProviderSelection::Unique,
488                                replaced,
489                            },
490                        ));
491                        resolved_requirements.push(ResolvedRequirement {
492                            consumer,
493                            capability: *capability,
494                            qualifier: *qualifier,
495                            provider: Some(*provider),
496                            optional: false,
497                            selection: ProviderSelection::Unique,
498                            replaced,
499                        });
500                    }
501                    _ => {
502                        return Err(ProjectionError::AmbiguousProvider {
503                            application,
504                            process,
505                            required_by: consumer,
506                            capability: *capability,
507                            qualifier: *qualifier,
508                            candidates,
509                        });
510                    }
511                }
512            }
513            for (target, qualifier) in targets_by_owner.get(&consumer).into_iter().flatten() {
514                for (contributor, contribution) in contributions_by_target
515                    .get(&(*target, *qualifier))
516                    .into_iter()
517                    .flatten()
518                {
519                    resolved_contributions.push(ResolvedContribution {
520                        consumer,
521                        contributor: *contributor,
522                        target: *target,
523                        qualifier: *qualifier,
524                        contribution: *contribution,
525                    });
526                    next.push((
527                        *contributor,
528                        InclusionReason::Contribution {
529                            consumed_by: consumer,
530                            target: *target,
531                            qualifier: *qualifier,
532                            contribution: *contribution,
533                        },
534                    ));
535                }
536            }
537            next.sort_unstable();
538
539            for (module, reason) in next {
540                if self.exclusions.contains(&module) {
541                    continue;
542                }
543                self.ensure_module(application, process, module)?;
544                edges.push((consumer, module));
545                if reached.contains_key(&module) {
546                    continue;
547                }
548                let mut path = reached[&consumer].path.clone();
549                path.push(module);
550                reached.insert(
551                    module,
552                    IncludedModule {
553                        module,
554                        path,
555                        reason,
556                    },
557                );
558                pending.push_back(module);
559            }
560        }
561
562        if let Some(path) = find_cycle(&edges) {
563            return Err(ProjectionError::DependencyCycle {
564                application,
565                process,
566                path,
567            });
568        }
569
570        let included_set = reached.keys().copied().collect::<BTreeSet<_>>();
571        for (contributor, target, qualifier, contribution, required) in &self.contributions {
572            if *required && included_set.contains(contributor) {
573                let consumed =
574                    consumers_by_target
575                        .get(&(*target, *qualifier))
576                        .is_some_and(|consumers| {
577                            consumers
578                                .iter()
579                                .any(|consumer| included_set.contains(consumer))
580                        });
581                if !consumed {
582                    return Err(ProjectionError::OrphanContribution {
583                        application,
584                        process,
585                        contributor: *contributor,
586                        target: *target,
587                        qualifier: *qualifier,
588                        contribution: *contribution,
589                    });
590                }
591            }
592        }
593
594        let included_modules = reached.into_values().collect::<Vec<_>>();
595        let included_set = included_modules
596            .iter()
597            .map(|entry| entry.module)
598            .collect::<BTreeSet<_>>();
599        let excluded_modules = self.modules.difference(&included_set).copied().collect();
600        let exclusions = self
601            .modules
602            .difference(&included_set)
603            .map(|module| ExcludedModule {
604                module: *module,
605                reason: if self.exclusions.contains(module) {
606                    ExclusionReason::Explicit
607                } else {
608                    ExclusionReason::Unreachable
609                },
610            })
611            .collect();
612
613        resolved_requirements.sort_unstable();
614        resolved_contributions.sort_unstable();
615
616        Ok(ProcessProjection {
617            application,
618            process,
619            roots,
620            included_modules,
621            excluded_modules,
622            exclusions,
623            requirements: resolved_requirements,
624            contributions: resolved_contributions,
625        })
626    }
627
628    /// Resolves one process and consumes the mutable blueprint at the freeze boundary.
629    pub fn freeze(self, process: ProcessId) -> Result<FrozenProcess, ProjectionError> {
630        Ok(self.freeze_processes(&[process])?.remove(0))
631    }
632
633    /// Resolves selected processes from one blueprint and consumes it at freeze.
634    pub fn freeze_processes(
635        self,
636        processes: &[ProcessId],
637    ) -> Result<Vec<FrozenProcess>, ProjectionError> {
638        processes
639            .iter()
640            .map(|process| self.project(*process).map(FrozenProcess::new))
641            .collect()
642    }
643
644    fn ensure_module(
645        &self,
646        application: ApplicationId,
647        process: ProcessId,
648        module: ModuleId,
649    ) -> Result<(), ProjectionError> {
650        if self.modules.contains(&module) {
651            Ok(())
652        } else {
653            Err(ProjectionError::MissingModule {
654                application,
655                process,
656                module,
657            })
658        }
659    }
660}
661
662fn find_cycle(edges: &[(ModuleId, ModuleId)]) -> Option<Vec<ModuleId>> {
663    fn visit(
664        node: ModuleId,
665        graph: &BTreeMap<ModuleId, Vec<ModuleId>>,
666        active: &mut Vec<ModuleId>,
667        complete: &mut BTreeSet<ModuleId>,
668    ) -> Option<Vec<ModuleId>> {
669        if let Some(start) = active.iter().position(|candidate| *candidate == node) {
670            let mut cycle = active[start..].to_vec();
671            cycle.push(node);
672            return Some(cycle);
673        }
674        if !complete.insert(node) {
675            return None;
676        }
677        active.push(node);
678        for next in graph.get(&node).into_iter().flatten() {
679            if let Some(cycle) = visit(*next, graph, active, complete) {
680                return Some(cycle);
681            }
682        }
683        active.pop();
684        None
685    }
686
687    let mut graph = BTreeMap::<ModuleId, Vec<ModuleId>>::new();
688    for (from, to) in edges {
689        graph.entry(*from).or_default().push(*to);
690    }
691    for neighbors in graph.values_mut() {
692        neighbors.sort_unstable();
693        neighbors.dedup();
694    }
695    let mut complete = BTreeSet::new();
696    let mut active = Vec::new();
697    for node in graph.keys().copied() {
698        if let Some(cycle) = visit(node, &graph, &mut active, &mut complete) {
699            return Some(cycle);
700        }
701    }
702    None
703}
704
705/// Why a module is included in a process projection.
706#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
707pub enum InclusionReason {
708    /// The module provides an execution root of the process.
709    ExecutionRoot {
710        /// The execution represented by the root.
711        execution: ExecutionId,
712    },
713    /// The module provides a capability required by an included consumer.
714    CapabilityProvider {
715        /// The module requiring this provider.
716        required_by: ModuleId,
717        /// The required capability identity.
718        capability: CapabilityId,
719        /// The capability qualifier, if present.
720        qualifier: Option<QualifierId>,
721        /// How this provider was selected.
722        selection: ProviderSelection,
723        /// The original provider when this one replaced it.
724        replaced: Option<ModuleId>,
725    },
726    /// The module contributes to a target consumed by an included module.
727    Contribution {
728        /// The module consuming the target.
729        consumed_by: ModuleId,
730        /// The consumed target identity.
731        target: ContributionTargetId,
732        /// The target qualifier.
733        qualifier: QualifierId,
734        /// The contribution kind identity.
735        contribution: ContributionId,
736    },
737}
738
739/// How a resolved provider was selected for a requirement.
740#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
741pub enum ProviderSelection {
742    /// One provider uniquely matched the requirement.
743    Unique,
744    /// A declared default selected the provider.
745    Default,
746    /// An explicit selection overrode defaults or automatic choice.
747    Explicit,
748    /// The optional requirement was not activated.
749    OptionalAbsent,
750}
751
752/// Why a declared module is absent from a process projection.
753#[derive(Clone, Copy, Debug, Eq, PartialEq)]
754pub enum ExclusionReason {
755    /// The blueprint explicitly excluded the module.
756    Explicit,
757    /// No selected root or relation reached the module.
758    Unreachable,
759}
760
761/// An omitted module and its projection-specific exclusion reason.
762#[derive(Clone, Copy, Debug, Eq, PartialEq)]
763pub struct ExcludedModule {
764    module: ModuleId,
765    reason: ExclusionReason,
766}
767
768impl ExcludedModule {
769    /// Returns the omitted module identity.
770    pub const fn module(&self) -> ModuleId {
771        self.module
772    }
773
774    /// Returns why the module is absent.
775    pub const fn reason(&self) -> ExclusionReason {
776        self.reason
777    }
778}
779
780/// A capability requirement and its selected provider in a process projection.
781#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
782pub struct ResolvedRequirement {
783    consumer: ModuleId,
784    capability: CapabilityId,
785    qualifier: Option<QualifierId>,
786    provider: Option<ModuleId>,
787    optional: bool,
788    selection: ProviderSelection,
789    replaced: Option<ModuleId>,
790}
791
792impl ResolvedRequirement {
793    /// Returns the module that owns the requirement.
794    pub const fn consumer(&self) -> ModuleId {
795        self.consumer
796    }
797    /// Returns the required capability identity.
798    pub const fn capability(&self) -> CapabilityId {
799        self.capability
800    }
801    /// Returns the required qualifier, if any.
802    pub const fn qualifier(&self) -> Option<QualifierId> {
803        self.qualifier
804    }
805    /// Returns the selected provider, or `None` for an inactive optional requirement.
806    pub const fn provider(&self) -> Option<ModuleId> {
807        self.provider
808    }
809    /// Returns whether the declared requirement is optional.
810    pub const fn optional(&self) -> bool {
811        self.optional
812    }
813    /// Returns how the provider was selected.
814    pub const fn selection(&self) -> ProviderSelection {
815        self.selection
816    }
817    /// Returns the provider identity replaced by the selected provider, if any.
818    pub const fn replaced_provider(&self) -> Option<ModuleId> {
819        self.replaced
820    }
821}
822
823/// A matching target contribution in the selected process projection.
824#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
825pub struct ResolvedContribution {
826    consumer: ModuleId,
827    contributor: ModuleId,
828    target: ContributionTargetId,
829    qualifier: QualifierId,
830    contribution: ContributionId,
831}
832
833impl ResolvedContribution {
834    /// Returns the module consuming the target.
835    pub const fn consumer(&self) -> ModuleId {
836        self.consumer
837    }
838    /// Returns the contributing module.
839    pub const fn contributor(&self) -> ModuleId {
840        self.contributor
841    }
842    /// Returns the target identity.
843    pub const fn target(&self) -> ContributionTargetId {
844        self.target
845    }
846    /// Returns the target qualifier.
847    pub const fn qualifier(&self) -> QualifierId {
848        self.qualifier
849    }
850    /// Returns the contribution kind identity.
851    pub const fn contribution(&self) -> ContributionId {
852        self.contribution
853    }
854}
855
856/// One reachable module and the deterministic path that made it reachable.
857#[derive(Clone, Debug, Eq, PartialEq)]
858pub struct IncludedModule {
859    module: ModuleId,
860    path: Vec<ModuleId>,
861    reason: InclusionReason,
862}
863
864impl IncludedModule {
865    /// Returns the included module identity.
866    pub const fn module(&self) -> ModuleId {
867        self.module
868    }
869
870    /// Returns the root-to-module inclusion path.
871    pub fn path(&self) -> &[ModuleId] {
872        &self.path
873    }
874
875    /// Returns the edge that included this module or the root execution.
876    pub const fn reason(&self) -> InclusionReason {
877        self.reason
878    }
879}
880
881/// A derived process projection. Its private structure cannot be mutated.
882#[derive(Clone, Debug, Eq, PartialEq)]
883pub struct ProcessProjection {
884    application: ApplicationId,
885    process: ProcessId,
886    roots: Vec<ExecutionId>,
887    included_modules: Vec<IncludedModule>,
888    excluded_modules: Vec<ModuleId>,
889    exclusions: Vec<ExcludedModule>,
890    requirements: Vec<ResolvedRequirement>,
891    contributions: Vec<ResolvedContribution>,
892}
893
894impl ProcessProjection {
895    /// Returns the application blueprint identity.
896    pub const fn application(&self) -> ApplicationId {
897        self.application
898    }
899
900    /// Returns the selected process identity.
901    pub const fn process(&self) -> ProcessId {
902        self.process
903    }
904
905    /// Returns the process's execution roots.
906    pub fn roots(&self) -> &[ExecutionId] {
907        &self.roots
908    }
909
910    /// Returns reachable modules with provenance paths.
911    pub fn included_modules(&self) -> &[IncludedModule] {
912        &self.included_modules
913    }
914
915    /// Returns declared modules excluded from this process projection.
916    pub fn excluded_modules(&self) -> &[ModuleId] {
917        &self.excluded_modules
918    }
919
920    /// Returns omitted modules with their exclusion reasons.
921    pub fn exclusions(&self) -> &[ExcludedModule] {
922        &self.exclusions
923    }
924
925    /// Returns requirements resolved for included modules.
926    pub fn requirements(&self) -> &[ResolvedRequirement] {
927        &self.requirements
928    }
929
930    /// Returns consumed contributions in this process projection.
931    pub fn contributions(&self) -> &[ResolvedContribution] {
932        &self.contributions
933    }
934
935    /// Returns whether a module is reachable in this projection.
936    pub fn includes(&self, module: ModuleId) -> bool {
937        self.included_modules
938            .iter()
939            .any(|entry| entry.module == module)
940    }
941}
942
943/// Compact structural input for initializing a selected runtime.
944#[derive(Clone, Debug, Eq, PartialEq)]
945pub struct RuntimeProjection {
946    modules: Vec<ModuleId>,
947    contributions: Vec<ResolvedContribution>,
948}
949
950impl RuntimeProjection {
951    /// Returns the selected module identities in deterministic order.
952    pub fn modules(&self) -> &[ModuleId] {
953        &self.modules
954    }
955
956    /// Returns target contribution work assigned to the consuming modules.
957    pub fn contributions(&self) -> &[ResolvedContribution] {
958        &self.contributions
959    }
960}
961
962/// A structurally immutable projection produced at the composition freeze boundary.
963///
964/// ```compile_fail
965/// use rustclamp_core::ModuleId;
966/// use rustclamp_kernel::FrozenProcess;
967/// fn mutate(frozen: &mut FrozenProcess) {
968///     frozen.add_module(ModuleId::new("late.module"));
969/// }
970/// ```
971#[derive(Clone, Debug, Eq, PartialEq)]
972pub struct FrozenProcess {
973    runtime: RuntimeProjection,
974    inspection: ProcessProjection,
975}
976
977impl FrozenProcess {
978    fn new(inspection: ProcessProjection) -> Self {
979        let runtime = RuntimeProjection {
980            modules: inspection
981                .included_modules()
982                .iter()
983                .map(IncludedModule::module)
984                .collect(),
985            contributions: inspection.contributions.clone(),
986        };
987        Self {
988            runtime,
989            inspection,
990        }
991    }
992
993    /// Returns the compact runtime projection derived from the resolved model.
994    pub const fn runtime(&self) -> &RuntimeProjection {
995        &self.runtime
996    }
997
998    /// Returns immutable resolution metadata for inspection.
999    pub const fn inspection(&self) -> &ProcessProjection {
1000        &self.inspection
1001    }
1002
1003    /// Resolves `consumer`'s unqualified requirement for `C` to the value of the
1004    /// provider this process selected at freeze time.
1005    ///
1006    /// The blueprint stays the single declaration of the edge: the caller supplies
1007    /// only the constructed values. An undeclared or inactive optional requirement
1008    /// fails with [`CompositionErrorKind::UndeclaredRequirement`]; a selected provider
1009    /// missing from `provisions` fails with
1010    /// [`CompositionErrorKind::ProviderSelectionUnavailable`].
1011    pub fn resolve<'value, C: Capability>(
1012        &self,
1013        consumer: ModuleId,
1014        provisions: &[Provision<'value, C>],
1015    ) -> Result<&'value C::Value, CompositionError> {
1016        self.resolve_frozen(
1017            consumer,
1018            C::ID,
1019            provisions
1020                .iter()
1021                .map(|provision| (provision.module, provision.value)),
1022            provisions.len(),
1023        )
1024    }
1025
1026    /// Like [`FrozenProcess::resolve`], but returns an owned [`Arc`] handle.
1027    ///
1028    /// The value can outlive the provisions slice and be moved into `'static`
1029    /// state (a server, a spawned task) without `Box::leak`.
1030    pub fn resolve_shared<C: Capability>(
1031        &self,
1032        consumer: ModuleId,
1033        provisions: &[SharedProvision<C>],
1034    ) -> Result<Arc<C::Value>, CompositionError> {
1035        self.resolve_frozen(
1036            consumer,
1037            C::ID,
1038            provisions
1039                .iter()
1040                .map(|provision| (provision.module, &provision.value)),
1041            provisions.len(),
1042        )
1043        .map(Arc::clone)
1044    }
1045
1046    /// Builds the value of the provider this process selected, after freeze.
1047    ///
1048    /// Only the selected provider's factory runs, so a provider whose
1049    /// construction can fail (opening a database) is built once, and only when
1050    /// the frozen process actually uses it. A factory failure is returned as
1051    /// [`FactoryError::Build`].
1052    pub fn resolve_with<C: Capability, E>(
1053        &self,
1054        consumer: ModuleId,
1055        provisions: Vec<FactoryProvision<C, E>>,
1056    ) -> Result<Arc<C::Value>, FactoryError<E>> {
1057        let selected = self
1058            .resolve_frozen(
1059                consumer,
1060                C::ID,
1061                provisions
1062                    .iter()
1063                    .map(|provision| (provision.module, provision)),
1064                provisions.len(),
1065            )
1066            .map_err(FactoryError::Composition)?
1067            .module;
1068        let provision = provisions
1069            .into_iter()
1070            .find(|provision| provision.module == selected)
1071            .expect("selected provision is among the candidates");
1072        (provision.factory)().map_err(FactoryError::Build)
1073    }
1074
1075    fn resolve_frozen<'value, V: ?Sized + 'value>(
1076        &self,
1077        consumer: ModuleId,
1078        capability: CapabilityId,
1079        provisions: impl Iterator<Item = (ModuleId, &'value V)> + Clone,
1080        count: usize,
1081    ) -> Result<&'value V, CompositionError> {
1082        // ponytail: unqualified only; add resolve_qualified when a process needs it.
1083        let provider = self
1084            .inspection
1085            .requirements()
1086            .iter()
1087            .find(|requirement| {
1088                requirement.consumer == consumer
1089                    && requirement.capability == capability
1090                    && requirement.qualifier.is_none()
1091            })
1092            .and_then(|requirement| requirement.provider);
1093        match provider {
1094            Some(provider) => Resolver::resolve_candidates(
1095                consumer,
1096                capability,
1097                None,
1098                provisions,
1099                count,
1100                Some(provider),
1101            ),
1102            None => Err(Resolver::error(
1103                CompositionErrorKind::UndeclaredRequirement,
1104                consumer,
1105                capability,
1106                None,
1107                provisions,
1108            )),
1109        }
1110    }
1111
1112    /// Builds target `T` (qualifier `Q`) from the contributions this process selected.
1113    ///
1114    /// The blueprint's `add_contribution` edges stay the single declaration:
1115    /// contributions from modules outside this process are dropped, and the rest
1116    /// must match the frozen edges exactly — an included module supplying an
1117    /// undeclared contribution, or a declared contributor supplying none, fails.
1118    pub fn compose<T: ContributionTarget, Q: Qualifier>(
1119        &self,
1120        target: &T,
1121        contributions: Vec<(ModuleId, T::Contribution)>,
1122    ) -> Result<T::Runtime, ComposeError<T::Error>> {
1123        self.compose_qualified(target, Q::ID, contributions)
1124    }
1125
1126    /// [`compose`](Self::compose), with the qualifier read from the blueprint's
1127    /// `add_contribution` edges for `T` instead of named again by the caller.
1128    ///
1129    /// Fails with [`ComposeError::AmbiguousQualifier`] when this process has
1130    /// edges into `T` under more than one qualifier, or none: name it with
1131    /// `compose::<T, Q>` then.
1132    pub fn compose_inferred<T: ContributionTarget>(
1133        &self,
1134        target: &T,
1135        contributions: Vec<(ModuleId, T::Contribution)>,
1136    ) -> Result<T::Runtime, ComposeError<T::Error>> {
1137        let qualifiers = self
1138            .inspection
1139            .contributions()
1140            .iter()
1141            .filter(|edge| edge.target == T::ID && edge.contribution == T::Contribution::ID)
1142            .map(|edge| edge.qualifier)
1143            .collect::<BTreeSet<_>>();
1144        match qualifiers.len() {
1145            1 => {
1146                let qualifier = *qualifiers.first().expect("one qualifier");
1147                self.compose_qualified(target, qualifier, contributions)
1148            }
1149            _ => Err(ComposeError::AmbiguousQualifier {
1150                target: T::ID,
1151                qualifiers: qualifiers.into_iter().collect(),
1152            }),
1153        }
1154    }
1155
1156    fn compose_qualified<T: ContributionTarget>(
1157        &self,
1158        target: &T,
1159        qualifier: QualifierId,
1160        contributions: Vec<(ModuleId, T::Contribution)>,
1161    ) -> Result<T::Runtime, ComposeError<T::Error>> {
1162        let declared = self
1163            .inspection
1164            .contributions()
1165            .iter()
1166            .filter(|edge| {
1167                edge.target == T::ID
1168                    && edge.qualifier == qualifier
1169                    && edge.contribution == T::Contribution::ID
1170            })
1171            .map(|edge| edge.contributor)
1172            .collect::<BTreeSet<_>>();
1173        let selected = contributions
1174            .into_iter()
1175            .filter(|(module, _)| self.inspection.includes(*module))
1176            .collect::<Vec<_>>();
1177        if let Some((module, _)) = selected
1178            .iter()
1179            .find(|(module, _)| !declared.contains(module))
1180        {
1181            return Err(ComposeError::UndeclaredContribution {
1182                target: T::ID,
1183                qualifier,
1184                contributor: *module,
1185            });
1186        }
1187        if let Some(module) = declared
1188            .iter()
1189            .find(|declared| !selected.iter().any(|(module, _)| module == *declared))
1190        {
1191            return Err(ComposeError::MissingContribution {
1192                target: T::ID,
1193                qualifier,
1194                contributor: *module,
1195            });
1196        }
1197        target.build(&selected).map_err(ComposeError::Target)
1198    }
1199}
1200
1201/// A structured failure while deriving a selected process projection.
1202#[derive(Clone, Debug, Eq, PartialEq)]
1203pub enum ProjectionError {
1204    /// The application has no declaration for the requested process.
1205    MissingProcess {
1206        /// The application identity.
1207        application: ApplicationId,
1208        /// The requested process identity.
1209        process: ProcessId,
1210    },
1211    /// The process is declared without an execution root.
1212    EmptyProcessRoots {
1213        /// The application identity.
1214        application: ApplicationId,
1215        /// The process identity with no roots.
1216        process: ProcessId,
1217    },
1218    /// A process root refers to an undeclared execution.
1219    MissingExecution {
1220        /// The application identity.
1221        application: ApplicationId,
1222        /// The selected process identity.
1223        process: ProcessId,
1224        /// The undeclared root execution.
1225        execution: ExecutionId,
1226    },
1227    /// A root or reachable edge refers to an undeclared module.
1228    MissingModule {
1229        /// The application identity.
1230        application: ApplicationId,
1231        /// The selected process identity.
1232        process: ProcessId,
1233        /// The undeclared module identity.
1234        module: ModuleId,
1235    },
1236    /// An included required capability has no provider.
1237    MissingProvider {
1238        /// Application identity.
1239        application: ApplicationId,
1240        /// Projected process identity.
1241        process: ProcessId,
1242        /// Requiring module.
1243        required_by: ModuleId,
1244        /// Required capability.
1245        capability: CapabilityId,
1246        /// Required qualifier, if any.
1247        qualifier: Option<QualifierId>,
1248    },
1249    /// An included requirement has multiple providers without an explicit selection.
1250    AmbiguousProvider {
1251        /// Application identity.
1252        application: ApplicationId,
1253        /// Projected process identity.
1254        process: ProcessId,
1255        /// Requiring module.
1256        required_by: ModuleId,
1257        /// Required capability.
1258        capability: CapabilityId,
1259        /// Required qualifier, if any.
1260        qualifier: Option<QualifierId>,
1261        /// Sorted matching provider modules.
1262        candidates: Vec<ModuleId>,
1263    },
1264    /// A selected provider is not declared for the requirement.
1265    UnavailableProvider {
1266        /// Application identity.
1267        application: ApplicationId,
1268        /// Projected process identity.
1269        process: ProcessId,
1270        /// Requiring module.
1271        required_by: ModuleId,
1272        /// Required capability.
1273        capability: CapabilityId,
1274        /// Required qualifier, if any.
1275        qualifier: Option<QualifierId>,
1276        /// Selected provider module.
1277        provider: ModuleId,
1278    },
1279    /// An included requirement selected an excluded provider.
1280    ExcludedProvider {
1281        /// Application identity.
1282        application: ApplicationId,
1283        /// Projected process identity.
1284        process: ProcessId,
1285        /// Requiring module.
1286        required_by: ModuleId,
1287        /// Required capability.
1288        capability: CapabilityId,
1289        /// Required qualifier, if any.
1290        qualifier: Option<QualifierId>,
1291        /// Excluded provider module.
1292        provider: ModuleId,
1293    },
1294    /// An execution root was explicitly excluded.
1295    ExcludedRoot {
1296        /// Application identity.
1297        application: ApplicationId,
1298        /// Projected process identity.
1299        process: ProcessId,
1300        /// Excluded root module.
1301        module: ModuleId,
1302    },
1303    /// A cycle exists in the selected process dependency graph.
1304    DependencyCycle {
1305        /// Application identity.
1306        application: ApplicationId,
1307        /// Projected process identity.
1308        process: ProcessId,
1309        /// Closed cycle path, with the first module repeated at the end.
1310        path: Vec<ModuleId>,
1311    },
1312    /// A reachable module declares a required contribution without a consumer.
1313    OrphanContribution {
1314        /// Application identity.
1315        application: ApplicationId,
1316        /// Projected process identity.
1317        process: ProcessId,
1318        /// Module declaring the contribution.
1319        contributor: ModuleId,
1320        /// Contribution target identity.
1321        target: ContributionTargetId,
1322        /// Contribution target qualifier.
1323        qualifier: QualifierId,
1324        /// Contribution kind identity.
1325        contribution: ContributionId,
1326    },
1327}
1328
1329impl fmt::Display for ProjectionError {
1330    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1331        let (application, process) = match self {
1332            Self::MissingProcess {
1333                application,
1334                process,
1335                ..
1336            }
1337            | Self::EmptyProcessRoots {
1338                application,
1339                process,
1340                ..
1341            }
1342            | Self::MissingExecution {
1343                application,
1344                process,
1345                ..
1346            }
1347            | Self::MissingModule {
1348                application,
1349                process,
1350                ..
1351            }
1352            | Self::MissingProvider {
1353                application,
1354                process,
1355                ..
1356            }
1357            | Self::AmbiguousProvider {
1358                application,
1359                process,
1360                ..
1361            }
1362            | Self::UnavailableProvider {
1363                application,
1364                process,
1365                ..
1366            }
1367            | Self::ExcludedProvider {
1368                application,
1369                process,
1370                ..
1371            }
1372            | Self::ExcludedRoot {
1373                application,
1374                process,
1375                ..
1376            }
1377            | Self::DependencyCycle {
1378                application,
1379                process,
1380                ..
1381            }
1382            | Self::OrphanContribution {
1383                application,
1384                process,
1385                ..
1386            } => (application.as_str(), process.as_str()),
1387        };
1388        write!(formatter, "process '{application}/{process}': ")?;
1389        match self {
1390            Self::MissingProcess { .. } => formatter.write_str("process is not declared"),
1391            Self::EmptyProcessRoots { .. } => formatter.write_str("process has no execution root"),
1392            Self::MissingExecution { execution, .. } => {
1393                write!(
1394                    formatter,
1395                    "execution '{}' is not declared",
1396                    execution.as_str()
1397                )
1398            }
1399            Self::MissingModule { module, .. } => {
1400                write!(formatter, "module '{}' is not declared", module.as_str())
1401            }
1402            Self::MissingProvider {
1403                required_by,
1404                capability,
1405                qualifier,
1406                ..
1407            } => {
1408                write!(
1409                    formatter,
1410                    "no provider for capability '{}'{} required by module '{}'",
1411                    capability.as_str(),
1412                    Qualified(*qualifier),
1413                    required_by.as_str()
1414                )
1415            }
1416            Self::AmbiguousProvider {
1417                required_by,
1418                capability,
1419                qualifier,
1420                candidates,
1421                ..
1422            } => {
1423                write!(
1424                    formatter,
1425                    "ambiguous providers for capability '{}'{} required by module '{}': {}",
1426                    capability.as_str(),
1427                    Qualified(*qualifier),
1428                    required_by.as_str(),
1429                    candidates
1430                        .iter()
1431                        .map(|module| module.as_str())
1432                        .collect::<Vec<_>>()
1433                        .join(", ")
1434                )
1435            }
1436            Self::UnavailableProvider {
1437                required_by,
1438                capability,
1439                qualifier,
1440                provider,
1441                ..
1442            } => {
1443                write!(
1444                    formatter,
1445                    "selected provider '{}' does not provide capability '{}'{} required by module '{}'",
1446                    provider.as_str(),
1447                    capability.as_str(),
1448                    Qualified(*qualifier),
1449                    required_by.as_str()
1450                )
1451            }
1452            Self::ExcludedProvider {
1453                required_by,
1454                capability,
1455                qualifier,
1456                provider,
1457                ..
1458            } => {
1459                write!(
1460                    formatter,
1461                    "selected provider '{}' for capability '{}'{} required by module '{}' is excluded",
1462                    provider.as_str(),
1463                    capability.as_str(),
1464                    Qualified(*qualifier),
1465                    required_by.as_str()
1466                )
1467            }
1468            Self::ExcludedRoot { module, .. } => {
1469                write!(formatter, "root module '{}' is excluded", module.as_str())
1470            }
1471            Self::DependencyCycle { path, .. } => {
1472                write!(
1473                    formatter,
1474                    "dependency cycle: {}",
1475                    path.iter()
1476                        .map(|module| module.as_str())
1477                        .collect::<Vec<_>>()
1478                        .join(" -> ")
1479                )
1480            }
1481            Self::OrphanContribution {
1482                contributor,
1483                target,
1484                qualifier,
1485                contribution,
1486                ..
1487            } => {
1488                write!(
1489                    formatter,
1490                    "required contribution '{}' from module '{}' has no consumer for target '{}' qualified as '{}'",
1491                    contribution.as_str(),
1492                    contributor.as_str(),
1493                    target.as_str(),
1494                    qualifier.as_str()
1495                )
1496            }
1497        }
1498    }
1499}
1500
1501impl Error for ProjectionError {}
1502
1503/// Renders an optional qualifier suffix in diagnostics.
1504struct Qualified(Option<QualifierId>);
1505
1506impl fmt::Display for Qualified {
1507    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1508        match self.0 {
1509            Some(qualifier) => write!(formatter, " qualified as '{}'", qualifier.as_str()),
1510            None => Ok(()),
1511        }
1512    }
1513}
1514
1515/// Caller-owned declarations for one typed contribution target and qualifier.
1516pub struct TargetComposition<T: ContributionTarget, Q: Qualifier> {
1517    contributions: Vec<(ModuleId, T::Contribution)>,
1518    target: PhantomData<(T, Q)>,
1519}
1520
1521impl<T: ContributionTarget, Q: Qualifier> TargetComposition<T, Q> {
1522    /// Creates a target composition from contributor identities and declarations.
1523    pub fn new(contributions: Vec<(ModuleId, T::Contribution)>) -> Self {
1524        Self {
1525            contributions,
1526            target: PhantomData,
1527        }
1528    }
1529
1530    /// Consumes declarations into the selected target's runtime form.
1531    ///
1532    /// If no target is selected, required declarations produce a structured
1533    /// unconsumed-contribution error. Optional declarations are discarded. An
1534    /// empty composition without a target is a no-op.
1535    pub fn build(
1536        self,
1537        target: Option<&T>,
1538    ) -> Result<Option<T::Runtime>, TargetCompositionError<T::Error>> {
1539        let Some(target) = target else {
1540            let mut contributors = self
1541                .contributions
1542                .iter()
1543                .filter(|_| T::Contribution::REQUIRED)
1544                .map(|(module, _)| *module)
1545                .collect::<Vec<_>>();
1546            if contributors.is_empty() {
1547                return Ok(None);
1548            }
1549            contributors.sort_unstable();
1550            return Err(TargetCompositionError::UnconsumedRequired {
1551                target: T::ID,
1552                contribution: T::Contribution::ID,
1553                qualifier: Q::ID,
1554                contributors,
1555            });
1556        };
1557
1558        target
1559            .build(&self.contributions)
1560            .map(Some)
1561            .map_err(TargetCompositionError::Target)
1562    }
1563}
1564
1565/// A target-owned build failure or an unconsumed required declaration.
1566#[derive(Debug, Eq, PartialEq)]
1567pub enum TargetCompositionError<E> {
1568    /// The active composition has required declarations but no matching target.
1569    UnconsumedRequired {
1570        /// The target that was expected to consume the declarations.
1571        target: ContributionTargetId,
1572        /// The contribution kind that was left unconsumed.
1573        contribution: ContributionId,
1574        /// The qualifier whose active composition contains the declarations.
1575        qualifier: QualifierId,
1576        /// Modules that contributed required declarations.
1577        contributors: Vec<ModuleId>,
1578    },
1579    /// The selected target rejected the declarations.
1580    Target(E),
1581}
1582
1583impl<E: fmt::Display> fmt::Display for TargetCompositionError<E> {
1584    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1585        match self {
1586            Self::UnconsumedRequired {
1587                target,
1588                contribution,
1589                qualifier,
1590                contributors,
1591            } => write!(
1592                formatter,
1593                "required contribution '{}' qualified as '{}' has no target '{}'; contributors: {}",
1594                contribution.as_str(),
1595                qualifier.as_str(),
1596                target.as_str(),
1597                contributors
1598                    .iter()
1599                    .map(|module| module.as_str())
1600                    .collect::<Vec<_>>()
1601                    .join(", ")
1602            ),
1603            Self::Target(error) => write!(formatter, "target rejected declarations: {error}"),
1604        }
1605    }
1606}
1607
1608impl<E: Error + 'static> Error for TargetCompositionError<E> {
1609    fn source(&self) -> Option<&(dyn Error + 'static)> {
1610        match self {
1611            Self::Target(error) => Some(error),
1612            Self::UnconsumedRequired { .. } => None,
1613        }
1614    }
1615}
1616
1617/// A mismatch between supplied contributions and the frozen process, or a target failure.
1618#[derive(Debug, Eq, PartialEq)]
1619pub enum ComposeError<E> {
1620    /// An included module supplied a contribution the frozen process does not declare.
1621    UndeclaredContribution {
1622        /// The target being composed.
1623        target: ContributionTargetId,
1624        /// The target qualifier.
1625        qualifier: QualifierId,
1626        /// The module whose contribution has no blueprint edge.
1627        contributor: ModuleId,
1628    },
1629    /// A contributor declared in the frozen process supplied no contribution.
1630    MissingContribution {
1631        /// The target being composed.
1632        target: ContributionTargetId,
1633        /// The target qualifier.
1634        qualifier: QualifierId,
1635        /// The declared module that supplied nothing.
1636        contributor: ModuleId,
1637    },
1638    /// [`FrozenProcess::compose_inferred`] found edges into the target under
1639    /// several qualifiers, or none, so it cannot pick one.
1640    AmbiguousQualifier {
1641        /// The target being composed.
1642        target: ContributionTargetId,
1643        /// The qualifiers the process's edges use, sorted; empty for none.
1644        qualifiers: Vec<QualifierId>,
1645    },
1646    /// The target rejected the selected contributions.
1647    Target(E),
1648}
1649
1650impl<E: fmt::Display> fmt::Display for ComposeError<E> {
1651    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1652        match self {
1653            Self::UndeclaredContribution {
1654                target,
1655                qualifier,
1656                contributor,
1657            } => write!(
1658                formatter,
1659                "module '{}' contributes to target '{}' qualified as '{}' without a blueprint edge in this process",
1660                contributor.as_str(),
1661                target.as_str(),
1662                qualifier.as_str()
1663            ),
1664            Self::MissingContribution {
1665                target,
1666                qualifier,
1667                contributor,
1668            } => write!(
1669                formatter,
1670                "module '{}' is declared to contribute to target '{}' qualified as '{}' but supplied nothing",
1671                contributor.as_str(),
1672                target.as_str(),
1673                qualifier.as_str()
1674            ),
1675            Self::AmbiguousQualifier { target, qualifiers } if qualifiers.is_empty() => write!(
1676                formatter,
1677                "target '{}' has no contribution edges in this process to infer a qualifier from",
1678                target.as_str()
1679            ),
1680            Self::AmbiguousQualifier { target, qualifiers } => write!(
1681                formatter,
1682                "target '{}' is contributed to under several qualifiers ({}); name one with compose::<T, Q>",
1683                target.as_str(),
1684                qualifiers
1685                    .iter()
1686                    .map(|qualifier| qualifier.as_str())
1687                    .collect::<Vec<_>>()
1688                    .join(", ")
1689            ),
1690            Self::Target(error) => write!(formatter, "target rejected contributions: {error}"),
1691        }
1692    }
1693}
1694
1695impl<E: Error + 'static> Error for ComposeError<E> {
1696    fn source(&self) -> Option<&(dyn Error + 'static)> {
1697        match self {
1698            Self::Target(error) => Some(error),
1699            Self::UndeclaredContribution { .. }
1700            | Self::MissingContribution { .. }
1701            | Self::AmbiguousQualifier { .. } => None,
1702        }
1703    }
1704}
1705
1706/// A capability implementation associated with the module that supplies it.
1707///
1708/// This is a graph relationship, not a provider base class. The value may be
1709/// borrowed from an object owned and constructed by the application.
1710pub struct Provision<'a, C: Capability> {
1711    module: ModuleId,
1712    value: &'a C::Value,
1713}
1714
1715impl<'a, C: Capability> Provision<'a, C> {
1716    /// Associates a module identity with a value implementing capability `C`.
1717    pub fn new(module: ModuleId, value: &'a C::Value) -> Self {
1718        Self { module, value }
1719    }
1720
1721    /// Creates a provision from a module's additive [`Provides`] contract.
1722    pub fn from_module<M: Provides<C>>(module: &'a M) -> Self {
1723        Self::new(<M as Module>::ID, module.provided_value())
1724    }
1725
1726    /// Returns the module identity associated with this provision.
1727    pub const fn module(&self) -> ModuleId {
1728        self.module
1729    }
1730
1731    /// Returns the provided capability value.
1732    pub const fn value(&self) -> &'a C::Value {
1733        self.value
1734    }
1735}
1736
1737/// A capability value owned through an [`Arc`], with no borrow to keep alive.
1738///
1739/// Use with [`FrozenProcess::resolve_shared`] when the resolved value must be
1740/// `'static` (shared state, spawned tasks).
1741pub struct SharedProvision<C: Capability> {
1742    module: ModuleId,
1743    value: Arc<C::Value>,
1744}
1745
1746impl<C: Capability> SharedProvision<C> {
1747    /// Associates a module identity with a shared value implementing capability `C`.
1748    pub fn new(module: ModuleId, value: Arc<C::Value>) -> Self {
1749        Self { module, value }
1750    }
1751
1752    /// Returns the module identity associated with this provision.
1753    pub const fn module(&self) -> ModuleId {
1754        self.module
1755    }
1756}
1757
1758/// A capability provision built on demand, for values whose construction can fail.
1759///
1760/// The factory runs only if [`FrozenProcess::resolve_with`] selects this module.
1761pub struct FactoryProvision<C: Capability, E> {
1762    module: ModuleId,
1763    factory: Box<dyn FnOnce() -> Result<Arc<C::Value>, E>>,
1764}
1765
1766impl<C: Capability, E> FactoryProvision<C, E> {
1767    /// Associates a module identity with a factory for capability `C`.
1768    pub fn new(
1769        module: ModuleId,
1770        factory: impl FnOnce() -> Result<Arc<C::Value>, E> + 'static,
1771    ) -> Self {
1772        Self {
1773            module,
1774            factory: Box::new(factory),
1775        }
1776    }
1777
1778    /// Returns the module identity associated with this provision.
1779    pub const fn module(&self) -> ModuleId {
1780        self.module
1781    }
1782}
1783
1784/// Why [`FrozenProcess::resolve_with`] failed.
1785#[derive(Debug, Eq, PartialEq)]
1786pub enum FactoryError<E> {
1787    /// The provider could not be selected.
1788    Composition(CompositionError),
1789    /// The selected provider's factory failed.
1790    Build(E),
1791}
1792
1793impl<E: fmt::Display> fmt::Display for FactoryError<E> {
1794    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1795        match self {
1796            Self::Composition(error) => error.fmt(formatter),
1797            Self::Build(error) => error.fmt(formatter),
1798        }
1799    }
1800}
1801
1802impl<E: Error + 'static> Error for FactoryError<E> {
1803    fn source(&self) -> Option<&(dyn Error + 'static)> {
1804        match self {
1805            Self::Composition(error) => Some(error),
1806            Self::Build(error) => Some(error),
1807        }
1808    }
1809}
1810
1811/// One module's requirement for a single typed capability.
1812pub struct CapabilityRequirement<C: Capability> {
1813    required_by: ModuleId,
1814    selected: Option<ModuleId>,
1815    capability: PhantomData<C>,
1816}
1817
1818impl<C: Capability> Copy for CapabilityRequirement<C> {}
1819
1820impl<C: Capability> Clone for CapabilityRequirement<C> {
1821    fn clone(&self) -> Self {
1822        *self
1823    }
1824}
1825
1826impl<C: Capability> CapabilityRequirement<C> {
1827    /// Declares a requirement with an optional explicit provider selection.
1828    pub const fn new(required_by: ModuleId, selected: Option<ModuleId>) -> Self {
1829        Self {
1830            required_by,
1831            selected,
1832            capability: PhantomData,
1833        }
1834    }
1835
1836    /// Creates a requirement from a module's additive [`Requires`] contract.
1837    pub fn from_module<M: Requires<C>>() -> Self {
1838        Self::new(<M as Module>::ID, M::SELECTED_PROVIDER)
1839    }
1840
1841    /// Returns the module that owns this requirement.
1842    pub const fn required_by(self) -> ModuleId {
1843        self.required_by
1844    }
1845
1846    /// Returns the explicitly selected provider, if one was declared.
1847    pub const fn selected_provider(self) -> Option<ModuleId> {
1848        self.selected
1849    }
1850}
1851
1852/// A caller-owned, single-capability composition snapshot.
1853///
1854/// This prototype stores declarations only; it does not construct modules or
1855/// keep global state. Edits return a new snapshot so callers can validate the
1856/// resulting graph before adopting it.
1857pub struct CapabilityComposition<'a, C: Capability> {
1858    provisions: Vec<Provision<'a, C>>,
1859    requirements: Vec<CapabilityRequirement<C>>,
1860}
1861
1862impl<'a, C: Capability> CapabilityComposition<'a, C> {
1863    /// Creates a composition snapshot from providers and consumer requirements.
1864    pub fn new(
1865        provisions: Vec<Provision<'a, C>>,
1866        requirements: Vec<CapabilityRequirement<C>>,
1867    ) -> Self {
1868        Self {
1869            provisions,
1870            requirements,
1871        }
1872    }
1873
1874    /// Removes a module's declarations and revalidates the remaining graph.
1875    ///
1876    /// Requirements owned by other modules remain, even when the removed module
1877    /// was their selected provider; validation then reports the broken edge.
1878    pub fn without_module(&self, module: ModuleId) -> Self {
1879        Self {
1880            provisions: self
1881                .provisions
1882                .iter()
1883                .filter(|provision| provision.module != module)
1884                .map(|provision| Provision::new(provision.module, provision.value))
1885                .collect(),
1886            requirements: self
1887                .requirements
1888                .iter()
1889                .copied()
1890                .filter(|requirement| requirement.required_by != module)
1891                .collect(),
1892        }
1893    }
1894
1895    /// Returns the active consumer requirements in this snapshot.
1896    pub fn requirements(&self) -> &[CapabilityRequirement<C>] {
1897        &self.requirements
1898    }
1899
1900    /// Replaces one provider for this capability while retaining module
1901    /// requirements and redirecting explicit selections to the replacement.
1902    /// Returns `None` when `replaced` does not currently provide this capability.
1903    pub fn replace_provider(
1904        &self,
1905        replaced: ModuleId,
1906        replacement: Provision<'a, C>,
1907    ) -> Option<Self> {
1908        if !self
1909            .provisions
1910            .iter()
1911            .any(|provision| provision.module == replaced)
1912        {
1913            return None;
1914        }
1915
1916        let mut provisions = self
1917            .provisions
1918            .iter()
1919            .filter(|provision| provision.module != replaced)
1920            .map(|provision| Provision::new(provision.module, provision.value))
1921            .collect::<Vec<_>>();
1922        let replacement_module = replacement.module;
1923        provisions.push(replacement);
1924        let requirements = self
1925            .requirements
1926            .iter()
1927            .map(|requirement| {
1928                CapabilityRequirement::new(
1929                    requirement.required_by,
1930                    (requirement.selected == Some(replaced))
1931                        .then_some(replacement_module)
1932                        .or(requirement.selected),
1933                )
1934            })
1935            .collect();
1936
1937        Some(Self::new(provisions, requirements))
1938    }
1939
1940    /// Resolves one declared requirement against this snapshot.
1941    pub fn resolve_requirement(
1942        &self,
1943        requirement: CapabilityRequirement<C>,
1944    ) -> Result<&'a C::Value, CompositionError> {
1945        Resolver::resolve::<C>(
1946            requirement.required_by,
1947            &self.provisions,
1948            requirement.selected,
1949        )
1950    }
1951
1952    /// Revalidates every consumer requirement in this snapshot.
1953    pub fn validate(&self) -> Result<(), CompositionError> {
1954        for requirement in &self.requirements {
1955            self.resolve_requirement(*requirement)?;
1956        }
1957        Ok(())
1958    }
1959}
1960
1961/// A capability provision distinguished by a compile-time qualifier type.
1962pub struct QualifiedProvision<'a, C: Capability, Q: Qualifier> {
1963    module: ModuleId,
1964    value: &'a C::Value,
1965    qualifier: PhantomData<Q>,
1966}
1967
1968impl<'a, C: Capability, Q: Qualifier> QualifiedProvision<'a, C, Q> {
1969    /// Associates a module and a typed qualifier with a capability value.
1970    pub fn new(module: ModuleId, value: &'a C::Value) -> Self {
1971        Self {
1972            module,
1973            value,
1974            qualifier: PhantomData,
1975        }
1976    }
1977
1978    /// Returns the module identity associated with this provision.
1979    pub const fn module(&self) -> ModuleId {
1980        self.module
1981    }
1982}
1983
1984/// The structured category of a capability composition failure.
1985#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1986pub enum CompositionErrorKind {
1987    /// No module provides a required capability.
1988    MissingProvider,
1989    /// More than one module provides the capability and none was selected.
1990    AmbiguousProviders,
1991    /// The selected module is not among the available provisions.
1992    ProviderSelectionUnavailable,
1993    /// The frozen process has no active requirement for this consumer and capability.
1994    UndeclaredRequirement,
1995}
1996
1997/// A composition failure with stable identities and candidate context.
1998#[derive(Clone, Debug, Eq, PartialEq)]
1999pub struct CompositionError {
2000    kind: CompositionErrorKind,
2001    required_by: ModuleId,
2002    capability: CapabilityId,
2003    qualifier: Option<QualifierId>,
2004    candidates: Vec<ModuleId>,
2005}
2006
2007impl CompositionError {
2008    fn new(
2009        kind: CompositionErrorKind,
2010        required_by: ModuleId,
2011        capability: CapabilityId,
2012        qualifier: Option<QualifierId>,
2013        candidates: Vec<ModuleId>,
2014    ) -> Self {
2015        Self {
2016            kind,
2017            required_by,
2018            capability,
2019            qualifier,
2020            candidates,
2021        }
2022    }
2023
2024    /// Returns the structured failure category.
2025    pub const fn kind(&self) -> CompositionErrorKind {
2026        self.kind
2027    }
2028
2029    /// Returns the module whose requirement could not be resolved.
2030    pub const fn required_by(&self) -> ModuleId {
2031        self.required_by
2032    }
2033
2034    /// Returns the stable identity of the missing or ambiguous capability.
2035    pub const fn capability(&self) -> CapabilityId {
2036        self.capability
2037    }
2038
2039    /// Returns the qualifier identity when the failed requirement was qualified.
2040    pub const fn qualifier(&self) -> Option<QualifierId> {
2041        self.qualifier
2042    }
2043
2044    /// Returns candidate module identities in stable sorted order.
2045    pub fn candidates(&self) -> &[ModuleId] {
2046        &self.candidates
2047    }
2048}
2049
2050impl fmt::Display for CompositionError {
2051    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2052        write!(
2053            formatter,
2054            "{:?} for capability '{}' required by module '{}'",
2055            self.kind,
2056            self.capability.as_str(),
2057            self.required_by.as_str()
2058        )?;
2059        if let Some(qualifier) = self.qualifier {
2060            write!(formatter, " qualified as '{}'", qualifier.as_str())?;
2061        }
2062        if !self.candidates.is_empty() {
2063            formatter.write_str("; candidates: ")?;
2064            for (index, candidate) in self.candidates.iter().enumerate() {
2065                if index > 0 {
2066                    formatter.write_str(", ")?;
2067                }
2068                formatter.write_str(candidate.as_str())?;
2069            }
2070        }
2071        Ok(())
2072    }
2073}
2074
2075impl Error for CompositionError {}
2076
2077/// A directed construction dependency from a module to a module it needs.
2078///
2079/// An edge `consumer -> dependency` means the dependency must be constructed
2080/// before the consumer. The graph only validates construction order; it does
2081/// not construct modules or support lazy/proxy edges.
2082#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2083pub struct ConstructionDependency {
2084    consumer: ModuleId,
2085    dependency: ModuleId,
2086}
2087
2088impl ConstructionDependency {
2089    /// Declares that `consumer` requires `dependency` during construction.
2090    pub const fn new(consumer: ModuleId, dependency: ModuleId) -> Self {
2091        Self {
2092            consumer,
2093            dependency,
2094        }
2095    }
2096
2097    /// Returns the module that has the dependency.
2098    pub const fn consumer(self) -> ModuleId {
2099        self.consumer
2100    }
2101
2102    /// Returns the module required during construction.
2103    pub const fn dependency(self) -> ModuleId {
2104        self.dependency
2105    }
2106}
2107
2108/// A caller-owned set of construction dependencies for cycle validation.
2109#[derive(Clone, Debug, Default)]
2110pub struct ConstructionGraph {
2111    dependencies: Vec<ConstructionDependency>,
2112}
2113
2114impl ConstructionGraph {
2115    /// Creates a graph from module-to-module construction dependencies.
2116    pub fn new(dependencies: Vec<ConstructionDependency>) -> Self {
2117        Self { dependencies }
2118    }
2119
2120    /// Returns the declared construction dependencies.
2121    pub fn dependencies(&self) -> &[ConstructionDependency] {
2122        &self.dependencies
2123    }
2124
2125    /// Rejects a construction cycle and returns its closed module path.
2126    ///
2127    /// For example, `A -> B -> C -> A` reports `[A, B, C, A]`. Traversal is
2128    /// sorted by stable module identity, so the selected diagnostic is
2129    /// independent of dependency registration order.
2130    pub fn validate(&self) -> Result<(), ConstructionCycle> {
2131        let mut adjacency = BTreeMap::<ModuleId, Vec<ModuleId>>::new();
2132        for edge in &self.dependencies {
2133            adjacency
2134                .entry(edge.consumer)
2135                .or_default()
2136                .push(edge.dependency);
2137            adjacency.entry(edge.dependency).or_default();
2138        }
2139
2140        // Deduplicate and sort once so traversal and diagnostics are stable.
2141        for dependencies in adjacency.values_mut() {
2142            dependencies.sort_unstable();
2143            dependencies.dedup();
2144        }
2145
2146        let mut states = BTreeMap::<ModuleId, VisitState>::new();
2147        let mut path = Vec::new();
2148        for module in adjacency.keys().copied() {
2149            if states
2150                .get(&module)
2151                .copied()
2152                .unwrap_or(VisitState::Unvisited)
2153                == VisitState::Unvisited
2154            {
2155                states.insert(module, VisitState::Visiting);
2156                path.push(module);
2157                let mut stack = vec![(module, 0usize)];
2158
2159                while let Some((current, next_index)) = stack.last_mut() {
2160                    let dependencies = &adjacency[current];
2161                    if *next_index == dependencies.len() {
2162                        let (finished, _) = stack.pop().expect("stack is non-empty");
2163                        path.pop();
2164                        states.insert(finished, VisitState::Visited);
2165                        continue;
2166                    }
2167
2168                    let dependency = dependencies[*next_index];
2169                    *next_index += 1;
2170                    match states
2171                        .get(&dependency)
2172                        .copied()
2173                        .unwrap_or(VisitState::Unvisited)
2174                    {
2175                        VisitState::Unvisited => {
2176                            states.insert(dependency, VisitState::Visiting);
2177                            path.push(dependency);
2178                            stack.push((dependency, 0));
2179                        }
2180                        VisitState::Visiting => {
2181                            let start = path
2182                                .iter()
2183                                .position(|item| *item == dependency)
2184                                .expect("visiting modules are in the active path");
2185                            let mut cycle = path[start..].to_vec();
2186                            cycle.push(dependency);
2187                            return Err(ConstructionCycle { path: cycle });
2188                        }
2189                        VisitState::Visited => {}
2190                    }
2191                }
2192            }
2193        }
2194        Ok(())
2195    }
2196}
2197
2198#[derive(Clone, Copy, Eq, PartialEq)]
2199enum VisitState {
2200    Unvisited,
2201    Visiting,
2202    Visited,
2203}
2204
2205/// A construction cycle with the repeated start module closing its path.
2206#[derive(Clone, Debug, Eq, PartialEq)]
2207pub struct ConstructionCycle {
2208    path: Vec<ModuleId>,
2209}
2210
2211impl ConstructionCycle {
2212    /// Returns the dependency path, including the repeated start module.
2213    pub fn path(&self) -> &[ModuleId] {
2214        &self.path
2215    }
2216}
2217
2218impl fmt::Display for ConstructionCycle {
2219    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2220        formatter.write_str("construction cycle: ")?;
2221        for (index, module) in self.path.iter().enumerate() {
2222            if index > 0 {
2223                formatter.write_str(" -> ")?;
2224            }
2225            formatter.write_str(module.as_str())?;
2226        }
2227        Ok(())
2228    }
2229}
2230
2231impl Error for ConstructionCycle {}
2232
2233/// Resolves one typed requirement from the provisions declared for it.
2234pub struct Resolver;
2235
2236impl Resolver {
2237    /// Resolves a unique provision, or the provision named by `selected`.
2238    ///
2239    /// Registration order never selects a winner. Multiple candidates without
2240    /// explicit selection produce a structured ambiguity error. No global
2241    /// registry, runtime type map, or allocation is needed on the success path.
2242    pub fn resolve<'value, C: Capability>(
2243        required_by: ModuleId,
2244        provisions: &[Provision<'value, C>],
2245        selected: Option<ModuleId>,
2246    ) -> Result<&'value C::Value, CompositionError> {
2247        let capability = C::ID;
2248        Self::resolve_candidates(
2249            required_by,
2250            capability,
2251            None,
2252            provisions
2253                .iter()
2254                .map(|provision| (provision.module, provision.value)),
2255            provisions.len(),
2256            selected,
2257        )
2258    }
2259
2260    /// Resolves an optional requirement without installing a default provider.
2261    /// Zero candidates returns `Ok(None)`, one returns its value, and multiple
2262    /// candidates remain ambiguous.
2263    pub fn resolve_optional<'value, C: Capability>(
2264        required_by: ModuleId,
2265        provisions: &[Provision<'value, C>],
2266    ) -> Result<Option<&'value C::Value>, CompositionError> {
2267        match provisions {
2268            [] => Ok(None),
2269            [provision] => Ok(Some(provision.value)),
2270            _ => Err(Self::error(
2271                CompositionErrorKind::AmbiguousProviders,
2272                required_by,
2273                C::ID,
2274                None,
2275                provisions
2276                    .iter()
2277                    .map(|provision| (provision.module, provision.value)),
2278            )),
2279        }
2280    }
2281
2282    /// Returns every provider for a many-valued requirement.
2283    ///
2284    /// Results are sorted by module identity for stable inspection only. This
2285    /// order does not define provider execution or dependency order.
2286    pub fn resolve_many<'value, C: Capability>(
2287        provisions: &[Provision<'value, C>],
2288    ) -> Vec<Provision<'value, C>> {
2289        let mut resolved = provisions
2290            .iter()
2291            .map(|provision| Provision::new(provision.module, provision.value))
2292            .collect::<Vec<_>>();
2293        resolved.sort_unstable_by_key(Provision::module);
2294        resolved
2295    }
2296
2297    /// Resolves a provision for one typed qualifier, excluding other qualifiers
2298    /// from candidate counting and diagnostics.
2299    pub fn resolve_qualified<'value, C: Capability, Q: Qualifier>(
2300        required_by: ModuleId,
2301        provisions: &[QualifiedProvision<'value, C, Q>],
2302        selected: Option<ModuleId>,
2303    ) -> Result<&'value C::Value, CompositionError> {
2304        Self::resolve_candidates(
2305            required_by,
2306            C::ID,
2307            Some(Q::ID),
2308            provisions
2309                .iter()
2310                .map(|provision| (provision.module, provision.value)),
2311            provisions.len(),
2312            selected,
2313        )
2314    }
2315
2316    fn resolve_candidates<'value, V: ?Sized + 'value>(
2317        required_by: ModuleId,
2318        capability: CapabilityId,
2319        qualifier: Option<QualifierId>,
2320        mut provisions: impl Iterator<Item = (ModuleId, &'value V)> + Clone,
2321        count: usize,
2322        selected: Option<ModuleId>,
2323    ) -> Result<&'value V, CompositionError> {
2324        if let Some(selected) = selected {
2325            let mut matches = provisions.clone().filter(|(module, _)| *module == selected);
2326            if let Some((_, value)) = matches.next() {
2327                if matches.next().is_none() {
2328                    return Ok(value);
2329                }
2330                return Err(Self::error(
2331                    CompositionErrorKind::AmbiguousProviders,
2332                    required_by,
2333                    capability,
2334                    qualifier,
2335                    provisions,
2336                ));
2337            }
2338            return Err(Self::error(
2339                CompositionErrorKind::ProviderSelectionUnavailable,
2340                required_by,
2341                capability,
2342                qualifier,
2343                provisions,
2344            ));
2345        }
2346
2347        match count {
2348            0 => Err(Self::error(
2349                CompositionErrorKind::MissingProvider,
2350                required_by,
2351                capability,
2352                qualifier,
2353                provisions,
2354            )),
2355            1 => Ok(provisions.next().expect("count checked").1),
2356            _ => Err(Self::error(
2357                CompositionErrorKind::AmbiguousProviders,
2358                required_by,
2359                capability,
2360                qualifier,
2361                provisions,
2362            )),
2363        }
2364    }
2365
2366    fn error<'value, V: ?Sized + 'value>(
2367        kind: CompositionErrorKind,
2368        required_by: ModuleId,
2369        capability: CapabilityId,
2370        qualifier: Option<QualifierId>,
2371        provisions: impl Iterator<Item = (ModuleId, &'value V)>,
2372    ) -> CompositionError {
2373        let mut candidates = provisions.map(|(module, _)| module).collect::<Vec<_>>();
2374        candidates.sort_unstable();
2375        CompositionError::new(kind, required_by, capability, qualifier, candidates)
2376    }
2377}