Skip to main content

navree_kernel/
graph.rs

1//! The module graph: walking modules, visibility of providers and the
2//! boot-time checks (missing or private providers, cycles, scope inversion).
3
4use std::any::TypeId;
5use std::collections::{HashMap, HashSet, VecDeque};
6use std::fmt;
7
8use crate::builder::{Contribution, PassedModule, ProviderDef};
9use crate::lifecycle::LifecycleDef;
10use crate::plugin::names_crate;
11use crate::{
12    BootErrors, CommandSpec, KernelError, Module, ModuleBuilder, ModuleId, PluginInfo,
13    PluginsReport, ProviderKey, Scope,
14};
15
16/// The validated module graph, as printed by `check --graph`.
17#[derive(Clone, Debug)]
18pub struct GraphReport {
19    /// Every module in dependency order (imports first); the implicit app root `App` is last.
20    pub modules: Vec<ModuleReport>,
21}
22
23/// One module of a [`GraphReport`].
24#[derive(Clone, Debug)]
25pub struct ModuleReport {
26    /// The module id.
27    pub id: ModuleId,
28    /// The module name.
29    pub name: &'static str,
30    /// Whether the module's exports are visible everywhere.
31    pub global: bool,
32    /// Names of the modules it imports.
33    pub imports: Vec<&'static str>,
34    /// Its providers, in registration order.
35    pub providers: Vec<ProviderReport>,
36    /// The keys it exports.
37    pub exports: Vec<String>,
38    /// The commands it registers.
39    pub commands: Vec<CommandInfo>,
40}
41
42/// One command of a [`ModuleReport`].
43#[derive(Clone, Debug)]
44pub struct CommandInfo {
45    /// The command name.
46    pub name: &'static str,
47    /// Its one-line description.
48    pub about: &'static str,
49}
50
51/// One provider of a [`ModuleReport`].
52#[derive(Clone, Debug)]
53pub struct ProviderReport {
54    /// The provider key.
55    pub key: String,
56    /// The provider scope.
57    pub scope: Scope,
58    /// The declared dependencies.
59    pub dependencies: Vec<String>,
60    /// Whether this is a multi-binding (see [`ModuleBuilder::multi`]).
61    pub multi: bool,
62}
63
64impl GraphReport {
65    /// Whether any module registers the command `name`.
66    pub fn has_command(&self, name: &str) -> bool {
67        self.modules
68            .iter()
69            .any(|m| m.commands.iter().any(|c| c.name == name))
70    }
71}
72
73/// Prints the import tree from the implicit root `App`; each module's
74/// providers, exports and commands are listed at its first appearance.
75impl fmt::Display for GraphReport {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        fn module_lines(
78            report: &GraphReport,
79            m: usize,
80            prefix: &str,
81            shown: &mut [bool],
82            out: &mut Vec<String>,
83        ) {
84            let module = &report.modules[m];
85            if std::mem::replace(&mut shown[m], true) {
86                return;
87            }
88            let mut items: Vec<Result<String, usize>> = Vec::new();
89            for p in &module.providers {
90                let mut line = format!("provides {} ({})", p.key, p.scope);
91                if p.multi {
92                    line.push_str(" [multi]");
93                }
94                if !p.dependencies.is_empty() {
95                    line.push_str(&format!(" <- {}", p.dependencies.join(", ")));
96                }
97                items.push(Ok(line));
98            }
99            items.extend(module.exports.iter().map(|e| Ok(format!("exports {e}"))));
100            items.extend(
101                module
102                    .commands
103                    .iter()
104                    .map(|c| Ok(format!("command {}: {}", c.name, c.about))),
105            );
106            items.extend(
107                module
108                    .imports
109                    .iter()
110                    .filter_map(|name| report.modules.iter().position(|r| r.name == *name))
111                    .map(Err),
112            );
113            let count = items.len();
114            for (i, item) in items.into_iter().enumerate() {
115                let last = i + 1 == count;
116                let (branch, indent) = if last {
117                    ("└── ", "    ")
118                } else {
119                    ("├── ", "│   ")
120                };
121                match item {
122                    Ok(line) => out.push(format!("{prefix}{branch}{line}")),
123                    Err(child) => {
124                        let module = &report.modules[child];
125                        let mut header = module.name.to_owned();
126                        if module.global {
127                            header.push_str(" [global]");
128                        }
129                        if shown[child] {
130                            header.push_str(" (see above)");
131                        }
132                        out.push(format!("{prefix}{branch}{header}"));
133                        module_lines(report, child, &format!("{prefix}{indent}"), shown, out);
134                    }
135                }
136            }
137        }
138
139        let Some(root) = self.modules.len().checked_sub(1) else {
140            return Ok(());
141        };
142        let mut lines = vec![self.modules[root].name.to_owned()];
143        let mut shown = vec![false; self.modules.len()];
144        module_lines(self, root, "", &mut shown, &mut lines);
145        f.write_str(&lines.join("\n"))
146    }
147}
148
149/// The implicit root module that imports the modules passed to the app builder.
150struct AppRoot;
151
152/// Index of the implicit root module.
153pub(crate) const ROOT: usize = 0;
154
155/// A registered module.
156pub(crate) struct ModuleNode {
157    pub(crate) id: ModuleId,
158    pub(crate) name: &'static str,
159    pub(crate) global: bool,
160    pub(crate) imports: Vec<usize>,
161    pub(crate) providers: Vec<usize>,
162    pub(crate) exports: Vec<ProviderKey>,
163    pub(crate) contributions: Vec<Contribution>,
164    pub(crate) lifecycles: Vec<LifecycleDef>,
165    pub(crate) commands: Vec<CommandSpec>,
166    /// The plugin the module names itself ([`ModuleBuilder::plugin`]).
167    pub(crate) plugin: Option<PluginInfo>,
168    /// Whether the module called `m.plugin(..)` more than once.
169    pub(crate) plugin_twice: bool,
170    /// `std::any::type_name` of the module value whose `register` ran, as the
171    /// app or its importer passed it (that of `Box<dyn Module>` for a module
172    /// passed already boxed): the module's own type, which its id need not
173    /// name. The plugin checks read it (see [`Graph::check_plugins`]).
174    pub(crate) type_name: &'static str,
175    /// For a configured instance (`for_root`, `from_config`), the module that
176    /// imported it (the root for a module the app passed).
177    pub(crate) configured_by: Option<usize>,
178}
179
180/// A registered provider and the module that owns it.
181pub(crate) struct ProviderNode {
182    pub(crate) def: ProviderDef,
183    pub(crate) module: usize,
184}
185
186/// What a key resolves to from inside one module.
187#[derive(Clone, Debug, PartialEq)]
188pub(crate) enum Visible {
189    One(usize),
190    /// Several different providers (indices, in module order) are visible.
191    Ambiguous(Vec<usize>),
192}
193
194impl Visible {
195    fn providers(&self) -> &[usize] {
196        match self {
197            Visible::One(p) => std::slice::from_ref(p),
198            Visible::Ambiguous(ps) => ps,
199        }
200    }
201
202    fn union(&self, other: &Visible) -> Visible {
203        let mut all = self.providers().to_vec();
204        for p in other.providers() {
205            if !all.contains(p) {
206                all.push(*p);
207            }
208        }
209        if all.len() == 1 {
210            Visible::One(all[0])
211        } else {
212            Visible::Ambiguous(all)
213        }
214    }
215}
216
217type VisibleMap = HashMap<ProviderKey, Visible>;
218
219/// The validated module graph of an app.
220pub(crate) struct Graph {
221    pub(crate) modules: Vec<ModuleNode>,
222    pub(crate) module_index: HashMap<ModuleId, usize>,
223    pub(crate) providers: Vec<ProviderNode>,
224    /// Per module: every key it can resolve.
225    visible: Vec<VisibleMap>,
226    /// What modules outside the graph see: exports of global modules.
227    outside: VisibleMap,
228    /// Module indices in dependency order (imports first); the root is last.
229    pub(crate) order: Vec<usize>,
230    /// Multi-binding provider indices per provided type, in dependency order.
231    multi: HashMap<TypeId, Vec<usize>>,
232    /// The service locator's answer for every key it resolves to exactly
233    /// one provider, built once at boot (see [`Graph::locate`]).
234    located: HashMap<ProviderKey, usize>,
235    /// Names of the plugins the kernel finds first-party (see
236    /// [`Graph::check_plugins`]).
237    pub(crate) first_party: HashSet<&'static str>,
238    /// Per module, the plugin it acts for, as the index of that plugin's first
239    /// module (the one whose info is the plugin's), or `None`: step 9 of
240    /// [`Graph::check_plugins`]. Empty until the checks run.
241    pub(crate) acts_for: Vec<Option<usize>>,
242}
243
244impl Graph {
245    /// Walks the modules from the implicit root, applies `overrides` (value
246    /// definitions replacing unnamed providers) and validates the graph.
247    /// `roots` are the modules the app passed, each with the type it was
248    /// passed as.
249    pub(crate) fn build_passed(
250        roots: &[PassedModule],
251        overrides: &[ProviderDef],
252    ) -> Result<Graph, BootErrors> {
253        let roots: Vec<(&dyn Module, &'static str)> = roots
254            .iter()
255            .map(|passed| (passed.module.as_ref(), passed.type_name))
256            .collect();
257        Self::build_from(&roots, overrides)
258    }
259
260    /// [`build_passed`](Graph::build_passed) for root modules passed already
261    /// boxed: each recovers its concrete type.
262    #[cfg(test)]
263    pub(crate) fn build(
264        roots: &[Box<dyn Module>],
265        overrides: &[ProviderDef],
266    ) -> Result<Graph, BootErrors> {
267        let roots: Vec<(&dyn Module, &'static str)> = roots
268            .iter()
269            .map(|module| {
270                (
271                    module.as_ref(),
272                    crate::module::resolved_type_name(module.as_ref()),
273                )
274            })
275            .collect();
276        Self::build_from(&roots, overrides)
277    }
278
279    /// Walks the modules from the implicit root (each root module with the
280    /// type it was passed as), applies `overrides` and validates the graph.
281    fn build_from(
282        roots: &[(&dyn Module, &'static str)],
283        overrides: &[ProviderDef],
284    ) -> Result<Graph, BootErrors> {
285        let walked = walk(roots)?;
286        let mut errors = Vec::new();
287        let mut graph = assemble(walked.registered, &mut errors);
288        if !walked.twice.is_empty() {
289            // The plugin checks run only to learn which plugin each module
290            // acts for; as before, the second configured instances are the
291            // only errors reported.
292            if graph.find_module_cycle().is_none() {
293                graph.check_plugins(&mut Vec::new());
294            }
295            return Err(BootErrors(graph.configured_twice(&walked.twice)));
296        }
297        graph.apply_overrides(overrides);
298        if let Some(cycle) = graph.find_module_cycle() {
299            errors.push(cycle);
300            return Err(BootErrors(errors));
301        }
302        graph.compute_visibility(&mut errors);
303        let edges = graph.check_dependencies(&mut errors);
304        graph.check_lifecycles(&mut errors);
305        graph.check_commands(&mut errors);
306        graph.check_plugins(&mut errors);
307        graph.check_scopes(&edges, &mut errors);
308        graph.check_provider_cycles(&edges, &mut errors);
309        if !errors.is_empty() {
310            return Err(BootErrors(errors));
311        }
312        graph.order = graph.dependency_order(&edges);
313        for &m in &graph.order {
314            for &p in &graph.modules[m].providers {
315                let def = &graph.providers[p].def;
316                if def.multi {
317                    graph.multi.entry(def.key.type_id()).or_default().push(p);
318                }
319            }
320        }
321        graph.located = graph.locator_map();
322        Ok(graph)
323    }
324
325    /// The plugins listing of `roots` when their graph is refused: the modules
326    /// are walked and assembled again (each `register` runs once more), and
327    /// the plugin checks run only to learn which plugin each module acts for.
328    /// `None` when the walk itself fails or the modules import each other in a
329    /// cycle. Nothing is built.
330    pub(crate) fn plugins_of_refused(roots: &[PassedModule]) -> Option<PluginsReport> {
331        let roots: Vec<(&dyn Module, &'static str)> = roots
332            .iter()
333            .map(|passed| (passed.module.as_ref(), passed.type_name))
334            .collect();
335        let walked = walk(&roots).ok()?;
336        let mut graph = assemble(walked.registered, &mut Vec::new());
337        if graph.find_module_cycle().is_some() {
338            return None;
339        }
340        graph.check_plugins(&mut Vec::new());
341        // The listing goes in dependency order, which a refused graph lacks:
342        // imports before the modules that import them stands in for it.
343        graph.order = graph.import_order();
344        Some(graph.plugins_report())
345    }
346
347    /// The errors of the configured instances the walk dropped (`twice`, in
348    /// its order), once [`check_plugins`](Graph::check_plugins) has recorded
349    /// which plugin each module acts for. Each is `PluginConfiguresModule`
350    /// when the module that imported the dropped instance, else the one that
351    /// imported the instance kept, acts for a plugin that is not first-party
352    /// and whose crate the module's type does not name; otherwise
353    /// `ConfiguredTwice`, as in an app with no such plugin.
354    fn configured_twice(&self, twice: &[Twice]) -> Vec<KernelError> {
355        twice
356            .iter()
357            .map(|twice| {
358                let kept = self
359                    .module_of(twice.module)
360                    .and_then(|m| self.modules[m].configured_by);
361                [self.module_of(twice.importer), kept]
362                    .into_iter()
363                    .flatten()
364                    .find_map(|importer| {
365                        let info = self.community_plugin(importer)?;
366                        (!names_crate(twice.module.type_name(), info.crate_name)).then(|| {
367                            KernelError::PluginConfiguresModule {
368                                plugin: info.name,
369                                module: twice.name,
370                                importer: self.modules[importer].name,
371                                reason: self.acts_for_reason(importer, info),
372                            }
373                        })
374                    })
375                    .unwrap_or(KernelError::ConfiguredTwice { module: twice.name })
376            })
377            .collect()
378    }
379
380    /// Whether provider `p` may answer an app-wide service-locator lookup:
381    /// multi-bindings never do, and an unexported provider of a module acting
382    /// for a community plugin stays private to that module.
383    fn is_locator_candidate(&self, p: usize) -> bool {
384        let provider = &self.providers[p];
385        if provider.def.multi {
386            return false;
387        }
388        let m = provider.module;
389        !(self.community_plugin(m).is_some()
390            && !self.modules[m].exports.contains(&provider.def.key))
391    }
392
393    /// The service locator's answers, decided once: every key with exactly
394    /// one candidate provider, or with several of which exactly one is exported
395    /// (the rule of [`locate_by_scan`](Graph::locate_by_scan)). Unexported
396    /// providers of community-plugin modules are excluded.
397    fn locator_map(&self) -> HashMap<ProviderKey, usize> {
398        let mut candidates: HashMap<&ProviderKey, Vec<usize>> = HashMap::new();
399        for (index, provider) in self.providers.iter().enumerate() {
400            if self.is_locator_candidate(index) {
401                candidates.entry(&provider.def.key).or_default().push(index);
402            }
403        }
404        candidates
405            .into_iter()
406            .filter_map(|(key, providers)| {
407                let only = match providers.as_slice() {
408                    [only] => *only,
409                    _ => {
410                        let mut exported = providers.iter().copied().filter(|&p| {
411                            self.modules[self.providers[p].module].exports.contains(key)
412                        });
413                        match (exported.next(), exported.next()) {
414                            (Some(only), None) => only,
415                            _ => return None,
416                        }
417                    }
418                };
419                Some((key.clone(), only))
420            })
421            .collect()
422    }
423
424    /// Replaces every unnamed, non-multi provider of each override's key; an
425    /// override nobody registers becomes a global export of the root.
426    fn apply_overrides(&mut self, overrides: &[ProviderDef]) {
427        for value in overrides {
428            let mut replaced = false;
429            for provider in self
430                .providers
431                .iter_mut()
432                .filter(|p| !p.def.multi && p.def.key == value.key)
433            {
434                provider.def = value.clone();
435                replaced = true;
436            }
437            if !replaced {
438                self.modules[ROOT].providers.push(self.providers.len());
439                self.modules[ROOT].exports.push(value.key.clone());
440                self.providers.push(ProviderNode {
441                    def: value.clone(),
442                    module: ROOT,
443                });
444            }
445        }
446    }
447
448    /// Finds the provider of `key` anywhere in the app, ignoring visibility
449    /// (for the service locator). Prefers exported providers when several
450    /// modules register the key. One map lookup: the answers are decided
451    /// at boot; a key the map lacks is missing or ambiguous, and the scan
452    /// explains which.
453    pub(crate) fn locate(
454        &self,
455        key: &ProviderKey,
456        required_by: &str,
457    ) -> Result<usize, KernelError> {
458        match self.located.get(key) {
459            Some(&index) => Ok(index),
460            None => self.locate_by_scan(key, required_by),
461        }
462    }
463
464    /// [`locate`](Graph::locate) by scanning every candidate provider.
465    fn locate_by_scan(&self, key: &ProviderKey, required_by: &str) -> Result<usize, KernelError> {
466        let candidates: Vec<usize> = (0..self.providers.len())
467            .filter(|&p| self.is_locator_candidate(p) && self.providers[p].def.key == *key)
468            .collect();
469        let exported: Vec<usize> = candidates
470            .iter()
471            .copied()
472            .filter(|&p| self.modules[self.providers[p].module].exports.contains(key))
473            .collect();
474        match (candidates.as_slice(), exported.as_slice()) {
475            ([], _) => Err(KernelError::MissingProvider {
476                module: self.modules[ROOT].name,
477                requested: key.to_string(),
478                required_by: required_by.to_owned(),
479            }),
480            ([only], _) | (_, [only]) => Ok(*only),
481            _ => Err(KernelError::AmbiguousProvider {
482                module: self.modules[ROOT].name,
483                requested: key.to_string(),
484                owners: candidates
485                    .iter()
486                    .map(|&p| self.modules[self.providers[p].module].name)
487                    .collect(),
488            }),
489        }
490    }
491
492    /// The multi-bindings of type `T` (by type id), in module dependency order.
493    pub(crate) fn multi_of(&self, type_id: TypeId) -> &[usize] {
494        self.multi.get(&type_id).map_or(&[], Vec::as_slice)
495    }
496
497    /// Resolves `key` as seen from `module` (`None` for modules outside the graph,
498    /// which only see global exports).
499    pub(crate) fn lookup(&self, module: Option<usize>, key: &ProviderKey) -> Option<&Visible> {
500        match module {
501            Some(m) => self.visible[m].get(key),
502            None => self.outside.get(key),
503        }
504    }
505
506    /// The module index of `id`, if it is part of the graph.
507    pub(crate) fn module_of(&self, id: ModuleId) -> Option<usize> {
508        self.module_index.get(&id).copied()
509    }
510
511    /// The error for a lookup that did not find exactly one provider.
512    pub(crate) fn unresolved(
513        &self,
514        found: Option<&Visible>,
515        module: Option<usize>,
516        module_name: &'static str,
517        key: &ProviderKey,
518        required_by: String,
519    ) -> KernelError {
520        match found {
521            Some(Visible::Ambiguous(providers)) => KernelError::AmbiguousProvider {
522                module: module_name,
523                requested: key.to_string(),
524                owners: providers
525                    .iter()
526                    .map(|&p| self.modules[self.providers[p].module].name)
527                    .collect(),
528            },
529            _ => self.missing(module, module_name, key, required_by),
530        }
531    }
532
533    /// Explains why `key` is not visible from `module` (`module_name` names it in the error).
534    pub(crate) fn missing(
535        &self,
536        module: Option<usize>,
537        module_name: &'static str,
538        key: &ProviderKey,
539        required_by: String,
540    ) -> KernelError {
541        let requested = key.to_string();
542        let owners: Vec<usize> = self
543            .providers
544            .iter()
545            .filter(|p| !p.def.multi && p.def.key == *key && Some(p.module) != module)
546            .map(|p| p.module)
547            .collect();
548        let imported_owner = module.and_then(|m| {
549            owners
550                .iter()
551                .copied()
552                .find(|o| self.modules[m].imports.contains(o))
553        });
554        if let Some(owner) = imported_owner {
555            return KernelError::NotExported {
556                module: module_name,
557                requested,
558                owner: self.modules[owner].name,
559            };
560        }
561        if let Some(owner) = owners
562            .iter()
563            .copied()
564            .find(|&o| self.modules[o].exports.contains(key))
565        {
566            return KernelError::NotImported {
567                module: module_name,
568                requested,
569                owner: self.modules[owner].name,
570            };
571        }
572        if let Some(&owner) = owners.first() {
573            return KernelError::NotExported {
574                module: module_name,
575                requested,
576                owner: self.modules[owner].name,
577            };
578        }
579        KernelError::MissingProvider {
580            module: module_name,
581            requested,
582            required_by,
583        }
584    }
585
586    /// The first module import cycle reachable from the root, if any.
587    fn find_module_cycle(&self) -> Option<KernelError> {
588        #[derive(Clone, Copy, PartialEq)]
589        enum Mark {
590            New,
591            Active,
592            Done,
593        }
594        fn visit(
595            graph: &Graph,
596            m: usize,
597            marks: &mut [Mark],
598            stack: &mut Vec<usize>,
599        ) -> Option<Vec<usize>> {
600            marks[m] = Mark::Active;
601            stack.push(m);
602            for &import in &graph.modules[m].imports {
603                match marks[import] {
604                    Mark::Active => {
605                        let start = stack.iter().position(|&s| s == import).unwrap_or(0);
606                        let mut path = stack[start..].to_vec();
607                        path.push(import);
608                        return Some(path);
609                    }
610                    Mark::New => {
611                        if let Some(path) = visit(graph, import, marks, stack) {
612                            return Some(path);
613                        }
614                    }
615                    Mark::Done => {}
616                }
617            }
618            stack.pop();
619            marks[m] = Mark::Done;
620            None
621        }
622        let mut marks = vec![Mark::New; self.modules.len()];
623        visit(self, ROOT, &mut marks, &mut Vec::new()).map(|path| KernelError::ModuleCycle {
624            path: path.into_iter().map(|m| self.modules[m].name).collect(),
625        })
626    }
627
628    /// Modules in import post-order (imports before importers), root last.
629    pub(crate) fn import_order(&self) -> Vec<usize> {
630        fn visit(graph: &Graph, m: usize, seen: &mut [bool], order: &mut Vec<usize>) {
631            if std::mem::replace(&mut seen[m], true) {
632                return;
633            }
634            for &import in &graph.modules[m].imports {
635                visit(graph, import, seen, order);
636            }
637            order.push(m);
638        }
639        let mut seen = vec![false; self.modules.len()];
640        let mut order = Vec::with_capacity(self.modules.len());
641        visit(self, ROOT, &mut seen, &mut order);
642        order
643    }
644
645    fn own(&self, module: usize, key: &ProviderKey) -> Option<usize> {
646        self.modules[module]
647            .providers
648            .iter()
649            .copied()
650            .find(|&p| !self.providers[p].def.multi && self.providers[p].def.key == *key)
651    }
652
653    /// Computes what each module exports (own providers and re-exports of
654    /// imported exports) and, from that, what each module can see:
655    /// own providers, then exports of direct imports, then exports of global modules.
656    fn compute_visibility(&mut self, errors: &mut Vec<KernelError>) {
657        let mut exported: Vec<VisibleMap> = vec![VisibleMap::new(); self.modules.len()];
658        for m in self.import_order() {
659            let mut map = VisibleMap::new();
660            for key in &self.modules[m].exports {
661                let found = match self.own(m, key) {
662                    Some(p) => Some(Visible::One(p)),
663                    None => self.modules[m]
664                        .imports
665                        .iter()
666                        .filter_map(|&i| exported[i].get(key))
667                        .fold(None, |acc: Option<Visible>, v| {
668                            Some(acc.map_or_else(|| v.clone(), |a| a.union(v)))
669                        }),
670                };
671                match found {
672                    Some(v) => {
673                        map.insert(key.clone(), v);
674                    }
675                    None => errors.push(KernelError::MissingProvider {
676                        module: self.modules[m].name,
677                        requested: key.to_string(),
678                        required_by: format!("the exports of `{}`", self.modules[m].name),
679                    }),
680                }
681            }
682            exported[m] = map;
683        }
684
685        let globals: Vec<usize> = (0..self.modules.len())
686            .filter(|&m| self.modules[m].global)
687            .collect();
688        let mut outside = VisibleMap::new();
689        for &g in &globals {
690            merge(&mut outside, &exported[g]);
691        }
692        let mut visible = Vec::with_capacity(self.modules.len());
693        for m in 0..self.modules.len() {
694            let mut map = VisibleMap::new();
695            for &g in globals.iter().filter(|&&g| g != m) {
696                merge(&mut map, &exported[g]);
697            }
698            let mut imported = VisibleMap::new();
699            for &i in &self.modules[m].imports {
700                merge(&mut imported, &exported[i]);
701            }
702            map.extend(imported);
703            for &p in &self.modules[m].providers {
704                if !self.providers[p].def.multi {
705                    map.insert(self.providers[p].def.key.clone(), Visible::One(p));
706                }
707            }
708            visible.push(map);
709        }
710        self.visible = visible;
711        self.outside = outside;
712    }
713
714    /// Checks that every declared dependency resolves to exactly one visible
715    /// provider. Returns the resolved dependency edges per provider.
716    fn check_dependencies(&self, errors: &mut Vec<KernelError>) -> Vec<Vec<usize>> {
717        let mut edges = Vec::with_capacity(self.providers.len());
718        for provider in &self.providers {
719            let mut resolved = Vec::new();
720            for dep in &provider.def.deps {
721                match self.lookup(Some(provider.module), dep) {
722                    Some(Visible::One(p)) => resolved.push(*p),
723                    found => errors.push(self.unresolved(
724                        found,
725                        Some(provider.module),
726                        self.modules[provider.module].name,
727                        dep,
728                        format!("`{}`", provider.def.key),
729                    )),
730                }
731            }
732            edges.push(resolved);
733        }
734        edges
735    }
736
737    /// Lifecycle hooks must belong to a provider of the registering module.
738    fn check_lifecycles(&self, errors: &mut Vec<KernelError>) {
739        for (m, module) in self.modules.iter().enumerate() {
740            for hooks in &module.lifecycles {
741                if self.own(m, &hooks.key).is_none() {
742                    errors.push(KernelError::MissingProvider {
743                        module: module.name,
744                        requested: hooks.key.to_string(),
745                        required_by: format!("a lifecycle registration of `{}`", module.name),
746                    });
747                }
748            }
749        }
750    }
751
752    /// Command names must be unique across the app.
753    fn check_commands(&self, errors: &mut Vec<KernelError>) {
754        let mut seen: HashMap<&str, &'static str> = HashMap::new();
755        for m in self.import_order() {
756            let module = &self.modules[m];
757            for command in &module.commands {
758                if let Some(first) = seen.insert(command.name, module.name) {
759                    errors.push(KernelError::DuplicateCommand {
760                        name: command.name.to_owned(),
761                        first,
762                        second: module.name,
763                    });
764                }
765            }
766        }
767    }
768
769    /// Whether any module registers the command `name`.
770    pub(crate) fn has_command(&self, name: &str) -> bool {
771        self.commands().any(|c| c.name == name)
772    }
773
774    /// Every command, modules in dependency order.
775    pub(crate) fn commands(&self) -> impl Iterator<Item = &CommandSpec> {
776        self.order
777            .iter()
778            .flat_map(|&m| self.modules[m].commands.iter())
779    }
780
781    /// Rejects singletons that depend on request-scoped providers, directly or
782    /// through transient providers.
783    fn check_scopes(&self, edges: &[Vec<usize>], errors: &mut Vec<KernelError>) {
784        fn reaches_request(
785            graph: &Graph,
786            edges: &[Vec<usize>],
787            p: usize,
788            seen: &mut HashSet<usize>,
789        ) -> Option<usize> {
790            match graph.providers[p].def.scope {
791                Scope::Request => Some(p),
792                Scope::Singleton => None,
793                Scope::Transient => {
794                    if !seen.insert(p) {
795                        return None;
796                    }
797                    edges[p]
798                        .iter()
799                        .find_map(|&d| reaches_request(graph, edges, d, seen))
800                }
801            }
802        }
803        for (p, provider) in self.providers.iter().enumerate() {
804            if provider.def.scope != Scope::Singleton {
805                continue;
806            }
807            let mut seen = HashSet::new();
808            if let Some(r) = edges[p]
809                .iter()
810                .find_map(|&d| reaches_request(self, edges, d, &mut seen))
811            {
812                errors.push(KernelError::ScopeInversion {
813                    module: self.modules[provider.module].name,
814                    singleton: provider.def.key.to_string(),
815                    request_scoped: self.providers[r].def.key.to_string(),
816                });
817            }
818        }
819    }
820
821    /// Reports every cycle in the declared provider dependencies.
822    fn check_provider_cycles(&self, edges: &[Vec<usize>], errors: &mut Vec<KernelError>) {
823        #[derive(Clone, Copy, PartialEq)]
824        enum Mark {
825            New,
826            Active,
827            Done,
828        }
829        fn visit(
830            graph: &Graph,
831            edges: &[Vec<usize>],
832            p: usize,
833            marks: &mut [Mark],
834            stack: &mut Vec<usize>,
835            errors: &mut Vec<KernelError>,
836        ) {
837            marks[p] = Mark::Active;
838            stack.push(p);
839            for &d in &edges[p] {
840                match marks[d] {
841                    Mark::Active => {
842                        let start = stack.iter().position(|&s| s == d).unwrap_or(0);
843                        let path = stack[start..]
844                            .iter()
845                            .chain(std::iter::once(&d))
846                            .map(|&q| graph.providers[q].def.key.to_string())
847                            .collect();
848                        errors.push(KernelError::ProviderCycle { path });
849                    }
850                    Mark::New => visit(graph, edges, d, marks, stack, errors),
851                    Mark::Done => {}
852                }
853            }
854            stack.pop();
855            marks[p] = Mark::Done;
856        }
857        let mut marks = vec![Mark::New; self.providers.len()];
858        for p in 0..self.providers.len() {
859            if marks[p] == Mark::New {
860                visit(self, edges, p, &mut marks, &mut Vec::new(), errors);
861            }
862        }
863    }
864
865    /// Module order for construction, contributions and lifecycle hooks: a
866    /// module comes after the modules it imports and the modules whose
867    /// providers it uses; the root is last.
868    fn dependency_order(&self, edges: &[Vec<usize>]) -> Vec<usize> {
869        fn visit(
870            graph: &Graph,
871            edges: &[Vec<usize>],
872            m: usize,
873            seen: &mut [bool],
874            order: &mut Vec<usize>,
875        ) {
876            if std::mem::replace(&mut seen[m], true) {
877                return;
878            }
879            for &import in &graph.modules[m].imports {
880                visit(graph, edges, import, seen, order);
881            }
882            for &p in &graph.modules[m].providers {
883                for &d in &edges[p] {
884                    visit(graph, edges, graph.providers[d].module, seen, order);
885                }
886            }
887            order.push(m);
888        }
889        let mut seen = vec![false; self.modules.len()];
890        let mut order = Vec::with_capacity(self.modules.len());
891        visit(self, edges, ROOT, &mut seen, &mut order);
892        order
893    }
894
895    /// A description of the graph for `check --graph`, modules in dependency order.
896    pub(crate) fn report(&self) -> GraphReport {
897        let modules = self
898            .order
899            .iter()
900            .map(|&m| {
901                let module = &self.modules[m];
902                ModuleReport {
903                    id: module.id,
904                    name: module.name,
905                    global: module.global,
906                    imports: module
907                        .imports
908                        .iter()
909                        .map(|&i| self.modules[i].name)
910                        .collect(),
911                    providers: module
912                        .providers
913                        .iter()
914                        .map(|&p| {
915                            let def = &self.providers[p].def;
916                            ProviderReport {
917                                key: def.key.to_string(),
918                                scope: def.scope,
919                                dependencies: def.deps.iter().map(ToString::to_string).collect(),
920                                multi: def.multi,
921                            }
922                        })
923                        .collect(),
924                    exports: module.exports.iter().map(ToString::to_string).collect(),
925                    commands: module
926                        .commands
927                        .iter()
928                        .map(|c| CommandInfo {
929                            name: c.name,
930                            about: c.about,
931                        })
932                        .collect(),
933                }
934            })
935            .collect();
936        GraphReport { modules }
937    }
938}
939
940/// Adds `from` into `into`; a key mapped to different providers becomes ambiguous.
941fn merge(into: &mut VisibleMap, from: &VisibleMap) {
942    for (key, v) in from {
943        match into.get_mut(key) {
944            Some(existing) => *existing = existing.union(v),
945            None => {
946                into.insert(key.clone(), v.clone());
947            }
948        }
949    }
950}
951
952/// The output of `Module::register` for one module.
953struct Registered {
954    builder: ModuleBuilder,
955    /// The type the registered module value was passed as.
956    type_name: &'static str,
957    /// For a configured instance, the module that imported it.
958    configured_by: Option<ModuleId>,
959    import_ids: Vec<ModuleId>,
960}
961
962/// A configured instance the walk dropped, because another configured
963/// instance of its module came first.
964struct Twice {
965    /// The module's id.
966    module: ModuleId,
967    /// The module's name.
968    name: &'static str,
969    /// The module that imported the dropped instance (the root's id for a
970    /// module the app passed).
971    importer: ModuleId,
972}
973
974/// What a walk registered, the configured instances it dropped, and any
975/// cross-crate `ModuleId` collisions it refused.
976struct Walked {
977    registered: Vec<Registered>,
978    twice: Vec<Twice>,
979    conflicts: Vec<KernelError>,
980}
981
982/// A module value to register: a root module borrowed from the app builder or
983/// an import owned by the walk, each with the type it was passed as.
984enum Source<'a> {
985    Root(&'a dyn Module, &'static str),
986    Import(PassedModule),
987}
988
989impl Source<'_> {
990    fn module(&self) -> &dyn Module {
991        match self {
992            Source::Root(m, _) => *m,
993            Source::Import(passed) => passed.module.as_ref(),
994        }
995    }
996
997    /// `std::any::type_name` of the module value, as it was passed.
998    fn type_name(&self) -> &'static str {
999        match self {
1000            Source::Root(_, type_name) => type_name,
1001            Source::Import(passed) => passed.type_name,
1002        }
1003    }
1004}
1005
1006/// A configured instance of `ModuleId` turned up after a plain instance of it
1007/// was registered: walk again, registering that plain import last.
1008struct Restart(ModuleId, &'static str);
1009
1010/// Calls `register` once per module id, starting from the implicit root.
1011/// Configured (`for_root`) instances win over plain imports of the same id; a
1012/// second configured instance of an id is dropped and recorded.
1013fn walk(roots: &[(&dyn Module, &'static str)]) -> Result<Walked, BootErrors> {
1014    let mut deferred = HashSet::new();
1015    loop {
1016        match Walker::new(&deferred).run(roots) {
1017            Ok(walked) => {
1018                if !walked.conflicts.is_empty() {
1019                    return Err(BootErrors(walked.conflicts));
1020                }
1021                return Ok(walked);
1022            }
1023            Err(Restart(id, name)) => {
1024                if !deferred.insert(id) {
1025                    // Only the plain instance's own imports lead to the configured
1026                    // one: the module (transitively) imports itself.
1027                    return Err(KernelError::ModuleCycle {
1028                        path: vec![name, name],
1029                    }
1030                    .into());
1031                }
1032            }
1033        }
1034    }
1035}
1036
1037struct Walker<'a, 'd> {
1038    deferred: &'d HashSet<ModuleId>,
1039    registered: HashSet<ModuleId>,
1040    configured: HashSet<ModuleId>,
1041    /// The module that imported the first configured instance of each id.
1042    configured_by: HashMap<ModuleId, ModuleId>,
1043    /// The crate stem and full type name of the first module value seen for each id.
1044    seen_crates: HashMap<ModuleId, (Option<&'static str>, &'static str)>,
1045    configured_queue: VecDeque<Source<'a>>,
1046    plain: Vec<(ModuleId, Source<'a>)>,
1047    out: Vec<Registered>,
1048    /// The configured instances dropped because one of their id came first.
1049    twice: Vec<Twice>,
1050    /// Cross-crate `ModuleId` collisions found during the walk.
1051    conflicts: Vec<KernelError>,
1052}
1053
1054impl<'a, 'd> Walker<'a, 'd> {
1055    fn new(deferred: &'d HashSet<ModuleId>) -> Self {
1056        Self {
1057            deferred,
1058            registered: HashSet::new(),
1059            configured: HashSet::new(),
1060            configured_by: HashMap::new(),
1061            seen_crates: HashMap::new(),
1062            configured_queue: VecDeque::new(),
1063            plain: Vec::new(),
1064            out: Vec::new(),
1065            twice: Vec::new(),
1066            conflicts: Vec::new(),
1067        }
1068    }
1069
1070    fn run(mut self, roots: &[(&'a dyn Module, &'static str)]) -> Result<Walked, Restart> {
1071        let root_id = ModuleId::named::<AppRoot>("App");
1072        let mut root = ModuleBuilder::new(root_id, root_id.name());
1073        root.global = true;
1074        self.registered.insert(root_id);
1075        let root_type = std::any::type_name::<AppRoot>();
1076        self.seen_crates
1077            .insert(root_id, (crate::plugin::module_crate(root_type), root_type));
1078        self.out.push(Registered {
1079            builder: root,
1080            type_name: root_type,
1081            configured_by: None,
1082            import_ids: roots.iter().map(|(m, _)| m.id()).collect(),
1083        });
1084        for &(module, type_name) in roots {
1085            self.enqueue(Source::Root(module, type_name), root_id)?;
1086        }
1087        loop {
1088            if let Some(source) = self.configured_queue.pop_front() {
1089                self.process(source)?;
1090            } else if let Some(source) = self.next_plain() {
1091                self.process(source)?;
1092            } else {
1093                break;
1094            }
1095        }
1096        Ok(Walked {
1097            registered: self.out,
1098            twice: self.twice,
1099            conflicts: self.conflicts,
1100        })
1101    }
1102
1103    /// Queues `source`, which `importer` imports (the root's id for a module
1104    /// the app passed).
1105    fn enqueue(&mut self, source: Source<'a>, importer: ModuleId) -> Result<(), Restart> {
1106        let module = source.module();
1107        let id = module.id();
1108        let type_name = source.type_name();
1109        let krate = crate::plugin::module_crate(type_name);
1110        if let Some(&(first_krate, first_type)) = self.seen_crates.get(&id) {
1111            let same_crate = match (first_krate, krate) {
1112                (Some(a), Some(b)) => a == b,
1113                _ => first_type == type_name && krate.is_some(),
1114            };
1115            if !same_crate {
1116                let already = self.conflicts.iter().any(|err| {
1117                    matches!(
1118                        err,
1119                        KernelError::DuplicateModuleId {
1120                            first,
1121                            second,
1122                            ..
1123                        } if *first == first_type && *second == type_name
1124                    )
1125                });
1126                if !already {
1127                    self.conflicts.push(KernelError::DuplicateModuleId {
1128                        module: module.name(),
1129                        id_type: id.type_name(),
1130                        first: first_type,
1131                        second: type_name,
1132                    });
1133                }
1134                return Ok(());
1135            }
1136        } else {
1137            self.seen_crates.insert(id, (krate, type_name));
1138        }
1139        if module.is_configured() {
1140            if !self.configured.insert(id) {
1141                self.twice.push(Twice {
1142                    module: id,
1143                    name: module.name(),
1144                    importer,
1145                });
1146                return Ok(());
1147            }
1148            self.configured_by.insert(id, importer);
1149            if self.registered.contains(&id) {
1150                return Err(Restart(id, module.name()));
1151            }
1152            self.configured_queue.push_back(source);
1153        } else if !self.registered.contains(&id)
1154            && !self.configured.contains(&id)
1155            && !self.plain.iter().any(|(queued, _)| *queued == id)
1156        {
1157            self.plain.push((id, source));
1158        }
1159        Ok(())
1160    }
1161
1162    /// The next plain module to register; deferred ids go last.
1163    fn next_plain(&mut self) -> Option<Source<'a>> {
1164        let (registered, configured) = (&self.registered, &self.configured);
1165        self.plain
1166            .retain(|(id, _)| !registered.contains(id) && !configured.contains(id));
1167        let position = self
1168            .plain
1169            .iter()
1170            .position(|(id, _)| !self.deferred.contains(id))
1171            .or(if self.plain.is_empty() { None } else { Some(0) })?;
1172        Some(self.plain.remove(position).1)
1173    }
1174
1175    fn process(&mut self, source: Source<'a>) -> Result<(), Restart> {
1176        let module = source.module();
1177        let id = module.id();
1178        let mut builder = ModuleBuilder::new(id, module.name());
1179        module.register(&mut builder);
1180        let imports = std::mem::take(&mut builder.imports);
1181        self.registered.insert(id);
1182        let configured_by = if module.is_configured() {
1183            self.configured_by.get(&id).copied()
1184        } else {
1185            None
1186        };
1187        self.out.push(Registered {
1188            builder,
1189            type_name: source.type_name(),
1190            configured_by,
1191            import_ids: imports.iter().map(|import| import.module.id()).collect(),
1192        });
1193        for import in imports {
1194            self.enqueue(Source::Import(import), id)?;
1195        }
1196        Ok(())
1197    }
1198}
1199
1200/// Turns registered builders into graph nodes; reports duplicate keys.
1201fn assemble(walked: Vec<Registered>, errors: &mut Vec<KernelError>) -> Graph {
1202    let module_index: HashMap<ModuleId, usize> = walked
1203        .iter()
1204        .enumerate()
1205        .map(|(i, r)| (r.builder.id, i))
1206        .collect();
1207    let mut modules = Vec::with_capacity(walked.len());
1208    let mut providers: Vec<ProviderNode> = Vec::new();
1209    for (index, registered) in walked.into_iter().enumerate() {
1210        let builder = registered.builder;
1211        let mut imports: Vec<usize> = Vec::new();
1212        for id in &registered.import_ids {
1213            let import = module_index[id];
1214            if !imports.contains(&import) {
1215                imports.push(import);
1216            }
1217        }
1218        let mut provider_indices: Vec<usize> = Vec::new();
1219        for def in builder.providers {
1220            if !def.multi
1221                && provider_indices
1222                    .iter()
1223                    .any(|&p| !providers[p].def.multi && providers[p].def.key == def.key)
1224            {
1225                errors.push(KernelError::DuplicateProvider {
1226                    module: builder.name,
1227                    key: def.key.to_string(),
1228                });
1229                continue;
1230            }
1231            provider_indices.push(providers.len());
1232            providers.push(ProviderNode { def, module: index });
1233        }
1234        modules.push(ModuleNode {
1235            id: builder.id,
1236            name: builder.name,
1237            global: builder.global,
1238            imports,
1239            providers: provider_indices,
1240            exports: builder.exports,
1241            contributions: builder.contributions,
1242            lifecycles: builder.lifecycles,
1243            commands: builder.commands,
1244            plugin: builder.plugin,
1245            plugin_twice: builder.plugin_twice,
1246            type_name: registered.type_name,
1247            configured_by: registered
1248                .configured_by
1249                .and_then(|importer| module_index.get(&importer).copied()),
1250        });
1251    }
1252    Graph {
1253        modules,
1254        module_index,
1255        providers,
1256        visible: Vec::new(),
1257        outside: VisibleMap::new(),
1258        order: Vec::new(),
1259        multi: HashMap::new(),
1260        located: HashMap::new(),
1261        first_party: HashSet::new(),
1262        acts_for: Vec::new(),
1263    }
1264}
1265
1266#[cfg(test)]
1267mod tests {
1268    use std::sync::Arc;
1269
1270    use super::*;
1271    use crate::{Factory, Resolver};
1272
1273    /// A plugin that is not first-party, in a namespace the framework keeps.
1274    const LEDGER: PluginInfo =
1275        PluginInfo::new("navree-plugin-ledger", module_path!(), "billing", "1.0.0");
1276
1277    /// The ledger plugin's module.
1278    struct Reserved;
1279
1280    impl Module for Reserved {
1281        fn register(&self, m: &mut ModuleBuilder) {
1282            m.plugin(LEDGER);
1283        }
1284    }
1285
1286    #[test]
1287    fn a_refused_graph_still_lists_its_plugins() {
1288        let roots = [PassedModule::of(Reserved)];
1289        assert!(Graph::build_passed(&roots, &[]).is_err());
1290        let report = Graph::plugins_of_refused(&roots).expect("the modules walk");
1291        let listed: Vec<(&str, usize)> = report
1292            .plugins
1293            .iter()
1294            .map(|plugin| (plugin.info.name, plugin.modules.len()))
1295            .collect();
1296        assert_eq!(listed, [("navree-plugin-ledger", 1)]);
1297    }
1298
1299    /// Provides a private `u32` and an unexported `String`.
1300    struct Private;
1301
1302    impl Module for Private {
1303        fn register(&self, m: &mut ModuleBuilder) {
1304            m.value(1_u32).value(String::from("private"));
1305        }
1306    }
1307
1308    /// Exports a `String`, an `i64` and a `u8` named `eight`.
1309    struct Exporting;
1310
1311    impl Module for Exporting {
1312        fn register(&self, m: &mut ModuleBuilder) {
1313            m.value(String::from("exported"))
1314                .exports::<String>()
1315                .value(1_i64)
1316                .exports::<i64>()
1317                .factory(
1318                    Factory::<u8>::new(|_: Resolver| async { Ok(Arc::new(8_u8)) }).named("eight"),
1319                )
1320                .export_key(ProviderKey::named::<u8>("eight"));
1321        }
1322    }
1323
1324    /// Exports another `i64`: two modules export one, so the locator cannot pick.
1325    struct AlsoExporting;
1326
1327    impl Module for AlsoExporting {
1328        fn register(&self, m: &mut ModuleBuilder) {
1329            m.value(2_i64).exports::<i64>();
1330        }
1331    }
1332
1333    fn graph() -> Graph {
1334        let roots: Vec<Box<dyn Module>> = vec![
1335            Box::new(Private),
1336            Box::new(Exporting),
1337            Box::new(AlsoExporting),
1338        ];
1339        Graph::build(&roots, &[]).expect("graph builds")
1340    }
1341
1342    #[test]
1343    fn the_locator_map_answers_as_a_scan_of_every_provider_does() {
1344        let graph = graph();
1345        let mut keys: Vec<ProviderKey> =
1346            graph.providers.iter().map(|p| p.def.key.clone()).collect();
1347        keys.push(ProviderKey::of::<bool>());
1348        keys.push(ProviderKey::named::<u8>("nine"));
1349        for key in &keys {
1350            let mapped = graph.locate(key, "a test").map_err(|e| e.to_string());
1351            let scanned = graph
1352                .locate_by_scan(key, "a test")
1353                .map_err(|e| e.to_string());
1354            assert_eq!(mapped, scanned, "{key}");
1355        }
1356    }
1357
1358    #[test]
1359    fn only_keys_with_one_answer_are_in_the_locator_map() {
1360        let graph = graph();
1361        // One provider, private: the locator ignores visibility.
1362        assert!(graph.located.contains_key(&ProviderKey::of::<u32>()));
1363        // Two providers, one exported: the exported one.
1364        let string = graph.located[&ProviderKey::of::<String>()];
1365        assert_eq!(
1366            graph.modules[graph.providers[string].module].name,
1367            "Exporting"
1368        );
1369        assert!(
1370            graph
1371                .located
1372                .contains_key(&ProviderKey::named::<u8>("eight"))
1373        );
1374        // Two exported providers: ambiguous, answered by the scan's error.
1375        assert!(!graph.located.contains_key(&ProviderKey::of::<i64>()));
1376        assert!(matches!(
1377            graph.locate(&ProviderKey::of::<i64>(), "a test"),
1378            Err(KernelError::AmbiguousProvider { .. })
1379        ));
1380        assert!(matches!(
1381            graph.locate(&ProviderKey::of::<bool>(), "a test"),
1382            Err(KernelError::MissingProvider { .. })
1383        ));
1384    }
1385}