navree-kernel 1.3.0

Navree kernel: module graph, type-keyed DI container, lifecycle and command runner.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
//! The module graph: walking modules, visibility of providers and the
//! boot-time checks (missing or private providers, cycles, scope inversion).

use std::any::TypeId;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;

use crate::builder::{Contribution, PassedModule, ProviderDef};
use crate::lifecycle::LifecycleDef;
use crate::plugin::names_crate;
use crate::{
    BootErrors, CommandSpec, KernelError, Module, ModuleBuilder, ModuleId, PluginInfo,
    PluginsReport, ProviderKey, Scope,
};

/// The validated module graph, as printed by `check --graph`.
#[derive(Clone, Debug)]
pub struct GraphReport {
    /// Every module in dependency order (imports first); the implicit app root `App` is last.
    pub modules: Vec<ModuleReport>,
}

/// One module of a [`GraphReport`].
#[derive(Clone, Debug)]
pub struct ModuleReport {
    /// The module id.
    pub id: ModuleId,
    /// The module name.
    pub name: &'static str,
    /// Whether the module's exports are visible everywhere.
    pub global: bool,
    /// Names of the modules it imports.
    pub imports: Vec<&'static str>,
    /// Its providers, in registration order.
    pub providers: Vec<ProviderReport>,
    /// The keys it exports.
    pub exports: Vec<String>,
    /// The commands it registers.
    pub commands: Vec<CommandInfo>,
}

/// One command of a [`ModuleReport`].
#[derive(Clone, Debug)]
pub struct CommandInfo {
    /// The command name.
    pub name: &'static str,
    /// Its one-line description.
    pub about: &'static str,
}

/// One provider of a [`ModuleReport`].
#[derive(Clone, Debug)]
pub struct ProviderReport {
    /// The provider key.
    pub key: String,
    /// The provider scope.
    pub scope: Scope,
    /// The declared dependencies.
    pub dependencies: Vec<String>,
    /// Whether this is a multi-binding (see [`ModuleBuilder::multi`]).
    pub multi: bool,
}

impl GraphReport {
    /// Whether any module registers the command `name`.
    pub fn has_command(&self, name: &str) -> bool {
        self.modules
            .iter()
            .any(|m| m.commands.iter().any(|c| c.name == name))
    }
}

/// Prints the import tree from the implicit root `App`; each module's
/// providers, exports and commands are listed at its first appearance.
impl fmt::Display for GraphReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn module_lines(
            report: &GraphReport,
            m: usize,
            prefix: &str,
            shown: &mut [bool],
            out: &mut Vec<String>,
        ) {
            let module = &report.modules[m];
            if std::mem::replace(&mut shown[m], true) {
                return;
            }
            let mut items: Vec<Result<String, usize>> = Vec::new();
            for p in &module.providers {
                let mut line = format!("provides {} ({})", p.key, p.scope);
                if p.multi {
                    line.push_str(" [multi]");
                }
                if !p.dependencies.is_empty() {
                    line.push_str(&format!(" <- {}", p.dependencies.join(", ")));
                }
                items.push(Ok(line));
            }
            items.extend(module.exports.iter().map(|e| Ok(format!("exports {e}"))));
            items.extend(
                module
                    .commands
                    .iter()
                    .map(|c| Ok(format!("command {}: {}", c.name, c.about))),
            );
            items.extend(
                module
                    .imports
                    .iter()
                    .filter_map(|name| report.modules.iter().position(|r| r.name == *name))
                    .map(Err),
            );
            let count = items.len();
            for (i, item) in items.into_iter().enumerate() {
                let last = i + 1 == count;
                let (branch, indent) = if last {
                    ("└── ", "    ")
                } else {
                    ("├── ", "│   ")
                };
                match item {
                    Ok(line) => out.push(format!("{prefix}{branch}{line}")),
                    Err(child) => {
                        let module = &report.modules[child];
                        let mut header = module.name.to_owned();
                        if module.global {
                            header.push_str(" [global]");
                        }
                        if shown[child] {
                            header.push_str(" (see above)");
                        }
                        out.push(format!("{prefix}{branch}{header}"));
                        module_lines(report, child, &format!("{prefix}{indent}"), shown, out);
                    }
                }
            }
        }

        let Some(root) = self.modules.len().checked_sub(1) else {
            return Ok(());
        };
        let mut lines = vec![self.modules[root].name.to_owned()];
        let mut shown = vec![false; self.modules.len()];
        module_lines(self, root, "", &mut shown, &mut lines);
        f.write_str(&lines.join("\n"))
    }
}

/// The implicit root module that imports the modules passed to the app builder.
struct AppRoot;

/// Index of the implicit root module.
pub(crate) const ROOT: usize = 0;

/// A registered module.
pub(crate) struct ModuleNode {
    pub(crate) id: ModuleId,
    pub(crate) name: &'static str,
    pub(crate) global: bool,
    pub(crate) imports: Vec<usize>,
    pub(crate) providers: Vec<usize>,
    pub(crate) exports: Vec<ProviderKey>,
    pub(crate) contributions: Vec<Contribution>,
    pub(crate) lifecycles: Vec<LifecycleDef>,
    pub(crate) commands: Vec<CommandSpec>,
    /// The plugin the module names itself ([`ModuleBuilder::plugin`]).
    pub(crate) plugin: Option<PluginInfo>,
    /// Whether the module called `m.plugin(..)` more than once.
    pub(crate) plugin_twice: bool,
    /// `std::any::type_name` of the module value whose `register` ran, as the
    /// app or its importer passed it (that of `Box<dyn Module>` for a module
    /// passed already boxed): the module's own type, which its id need not
    /// name. The plugin checks read it (see [`Graph::check_plugins`]).
    pub(crate) type_name: &'static str,
    /// For a configured instance (`for_root`, `from_config`), the module that
    /// imported it (the root for a module the app passed).
    pub(crate) configured_by: Option<usize>,
}

/// A registered provider and the module that owns it.
pub(crate) struct ProviderNode {
    pub(crate) def: ProviderDef,
    pub(crate) module: usize,
}

/// What a key resolves to from inside one module.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Visible {
    One(usize),
    /// Several different providers (indices, in module order) are visible.
    Ambiguous(Vec<usize>),
}

impl Visible {
    fn providers(&self) -> &[usize] {
        match self {
            Visible::One(p) => std::slice::from_ref(p),
            Visible::Ambiguous(ps) => ps,
        }
    }

    fn union(&self, other: &Visible) -> Visible {
        let mut all = self.providers().to_vec();
        for p in other.providers() {
            if !all.contains(p) {
                all.push(*p);
            }
        }
        if all.len() == 1 {
            Visible::One(all[0])
        } else {
            Visible::Ambiguous(all)
        }
    }
}

type VisibleMap = HashMap<ProviderKey, Visible>;

/// The validated module graph of an app.
pub(crate) struct Graph {
    pub(crate) modules: Vec<ModuleNode>,
    pub(crate) module_index: HashMap<ModuleId, usize>,
    pub(crate) providers: Vec<ProviderNode>,
    /// Per module: every key it can resolve.
    visible: Vec<VisibleMap>,
    /// What modules outside the graph see: exports of global modules.
    outside: VisibleMap,
    /// Module indices in dependency order (imports first); the root is last.
    pub(crate) order: Vec<usize>,
    /// Multi-binding provider indices per provided type, in dependency order.
    multi: HashMap<TypeId, Vec<usize>>,
    /// The service locator's answer for every key it resolves to exactly
    /// one provider, built once at boot (see [`Graph::locate`]).
    located: HashMap<ProviderKey, usize>,
    /// Names of the plugins the kernel finds first-party (see
    /// [`Graph::check_plugins`]).
    pub(crate) first_party: HashSet<&'static str>,
    /// Per module, the plugin it acts for, as the index of that plugin's first
    /// module (the one whose info is the plugin's), or `None`: step 9 of
    /// [`Graph::check_plugins`]. Empty until the checks run.
    pub(crate) acts_for: Vec<Option<usize>>,
}

impl Graph {
    /// Walks the modules from the implicit root, applies `overrides` (value
    /// definitions replacing unnamed providers) and validates the graph.
    /// `roots` are the modules the app passed, each with the type it was
    /// passed as.
    pub(crate) fn build_passed(
        roots: &[PassedModule],
        overrides: &[ProviderDef],
    ) -> Result<Graph, BootErrors> {
        let roots: Vec<(&dyn Module, &'static str)> = roots
            .iter()
            .map(|passed| (passed.module.as_ref(), passed.type_name))
            .collect();
        Self::build_from(&roots, overrides)
    }

    /// [`build_passed`](Graph::build_passed) for root modules passed already
    /// boxed: each has the type `Box<dyn Module>`.
    #[cfg(test)]
    pub(crate) fn build(
        roots: &[Box<dyn Module>],
        overrides: &[ProviderDef],
    ) -> Result<Graph, BootErrors> {
        let boxed = std::any::type_name::<Box<dyn Module>>();
        let roots: Vec<(&dyn Module, &'static str)> = roots
            .iter()
            .map(|module| (module.as_ref(), boxed))
            .collect();
        Self::build_from(&roots, overrides)
    }

    /// Walks the modules from the implicit root (each root module with the
    /// type it was passed as), applies `overrides` and validates the graph.
    fn build_from(
        roots: &[(&dyn Module, &'static str)],
        overrides: &[ProviderDef],
    ) -> Result<Graph, BootErrors> {
        let walked = walk(roots)?;
        let mut errors = Vec::new();
        let mut graph = assemble(walked.registered, &mut errors);
        if !walked.twice.is_empty() {
            // The plugin checks run only to learn which plugin each module
            // acts for; as before, the second configured instances are the
            // only errors reported.
            if graph.find_module_cycle().is_none() {
                graph.check_plugins(&mut Vec::new());
            }
            return Err(BootErrors(graph.configured_twice(&walked.twice)));
        }
        graph.apply_overrides(overrides);
        if let Some(cycle) = graph.find_module_cycle() {
            errors.push(cycle);
            return Err(BootErrors(errors));
        }
        graph.compute_visibility(&mut errors);
        let edges = graph.check_dependencies(&mut errors);
        graph.check_lifecycles(&mut errors);
        graph.check_commands(&mut errors);
        graph.check_plugins(&mut errors);
        graph.check_scopes(&edges, &mut errors);
        graph.check_provider_cycles(&edges, &mut errors);
        if !errors.is_empty() {
            return Err(BootErrors(errors));
        }
        graph.order = graph.dependency_order(&edges);
        for &m in &graph.order {
            for &p in &graph.modules[m].providers {
                let def = &graph.providers[p].def;
                if def.multi {
                    graph.multi.entry(def.key.type_id()).or_default().push(p);
                }
            }
        }
        graph.located = graph.locator_map();
        Ok(graph)
    }

    /// The plugins listing of `roots` when their graph is refused: the modules
    /// are walked and assembled again (each `register` runs once more), and
    /// the plugin checks run only to learn which plugin each module acts for.
    /// `None` when the walk itself fails or the modules import each other in a
    /// cycle. Nothing is built.
    pub(crate) fn plugins_of_refused(roots: &[PassedModule]) -> Option<PluginsReport> {
        let roots: Vec<(&dyn Module, &'static str)> = roots
            .iter()
            .map(|passed| (passed.module.as_ref(), passed.type_name))
            .collect();
        let walked = walk(&roots).ok()?;
        let mut graph = assemble(walked.registered, &mut Vec::new());
        if graph.find_module_cycle().is_some() {
            return None;
        }
        graph.check_plugins(&mut Vec::new());
        // The listing goes in dependency order, which a refused graph lacks:
        // imports before the modules that import them stands in for it.
        graph.order = graph.import_order();
        Some(graph.plugins_report())
    }

    /// The errors of the configured instances the walk dropped (`twice`, in
    /// its order), once [`check_plugins`](Graph::check_plugins) has recorded
    /// which plugin each module acts for. Each is `PluginConfiguresModule`
    /// when the module that imported the dropped instance, else the one that
    /// imported the instance kept, acts for a plugin that is not first-party
    /// and whose crate the module's type does not name; otherwise
    /// `ConfiguredTwice`, as in an app with no such plugin.
    fn configured_twice(&self, twice: &[Twice]) -> Vec<KernelError> {
        twice
            .iter()
            .map(|twice| {
                let kept = self
                    .module_of(twice.module)
                    .and_then(|m| self.modules[m].configured_by);
                [self.module_of(twice.importer), kept]
                    .into_iter()
                    .flatten()
                    .find_map(|importer| {
                        let info = self.community_plugin(importer)?;
                        (!names_crate(twice.module.type_name(), info.crate_name)).then(|| {
                            KernelError::PluginConfiguresModule {
                                plugin: info.name,
                                module: twice.name,
                                importer: self.modules[importer].name,
                                reason: self.acts_for_reason(importer, info),
                            }
                        })
                    })
                    .unwrap_or(KernelError::ConfiguredTwice { module: twice.name })
            })
            .collect()
    }

    /// The service locator's answers, decided once: every key with exactly
    /// one provider, or with several of which exactly one is exported (the
    /// rule of [`locate_by_scan`](Graph::locate_by_scan)).
    fn locator_map(&self) -> HashMap<ProviderKey, usize> {
        let mut candidates: HashMap<&ProviderKey, Vec<usize>> = HashMap::new();
        for (index, provider) in self.providers.iter().enumerate() {
            if !provider.def.multi {
                candidates.entry(&provider.def.key).or_default().push(index);
            }
        }
        candidates
            .into_iter()
            .filter_map(|(key, providers)| {
                let only = match providers.as_slice() {
                    [only] => *only,
                    _ => {
                        let mut exported = providers.iter().copied().filter(|&p| {
                            self.modules[self.providers[p].module].exports.contains(key)
                        });
                        match (exported.next(), exported.next()) {
                            (Some(only), None) => only,
                            _ => return None,
                        }
                    }
                };
                Some((key.clone(), only))
            })
            .collect()
    }

    /// Replaces every unnamed, non-multi provider of each override's key; an
    /// override nobody registers becomes a global export of the root.
    fn apply_overrides(&mut self, overrides: &[ProviderDef]) {
        for value in overrides {
            let mut replaced = false;
            for provider in self
                .providers
                .iter_mut()
                .filter(|p| !p.def.multi && p.def.key == value.key)
            {
                provider.def = value.clone();
                replaced = true;
            }
            if !replaced {
                self.modules[ROOT].providers.push(self.providers.len());
                self.modules[ROOT].exports.push(value.key.clone());
                self.providers.push(ProviderNode {
                    def: value.clone(),
                    module: ROOT,
                });
            }
        }
    }

    /// Finds the provider of `key` anywhere in the app, ignoring visibility
    /// (for the service locator). Prefers exported providers when several
    /// modules register the key. One map lookup: the answers are decided
    /// at boot; a key the map lacks is missing or ambiguous, and the scan
    /// explains which.
    pub(crate) fn locate(
        &self,
        key: &ProviderKey,
        required_by: &str,
    ) -> Result<usize, KernelError> {
        match self.located.get(key) {
            Some(&index) => Ok(index),
            None => self.locate_by_scan(key, required_by),
        }
    }

    /// [`locate`](Graph::locate) by scanning every provider.
    fn locate_by_scan(&self, key: &ProviderKey, required_by: &str) -> Result<usize, KernelError> {
        let candidates: Vec<usize> = (0..self.providers.len())
            .filter(|&p| !self.providers[p].def.multi && self.providers[p].def.key == *key)
            .collect();
        let exported: Vec<usize> = candidates
            .iter()
            .copied()
            .filter(|&p| self.modules[self.providers[p].module].exports.contains(key))
            .collect();
        match (candidates.as_slice(), exported.as_slice()) {
            ([], _) => {
                Err(self.missing(None, self.modules[ROOT].name, key, required_by.to_owned()))
            }
            ([only], _) | (_, [only]) => Ok(*only),
            _ => Err(KernelError::AmbiguousProvider {
                module: self.modules[ROOT].name,
                requested: key.to_string(),
                owners: candidates
                    .iter()
                    .map(|&p| self.modules[self.providers[p].module].name)
                    .collect(),
            }),
        }
    }

    /// The multi-bindings of type `T` (by type id), in module dependency order.
    pub(crate) fn multi_of(&self, type_id: TypeId) -> &[usize] {
        self.multi.get(&type_id).map_or(&[], Vec::as_slice)
    }

    /// Resolves `key` as seen from `module` (`None` for modules outside the graph,
    /// which only see global exports).
    pub(crate) fn lookup(&self, module: Option<usize>, key: &ProviderKey) -> Option<&Visible> {
        match module {
            Some(m) => self.visible[m].get(key),
            None => self.outside.get(key),
        }
    }

    /// The module index of `id`, if it is part of the graph.
    pub(crate) fn module_of(&self, id: ModuleId) -> Option<usize> {
        self.module_index.get(&id).copied()
    }

    /// The error for a lookup that did not find exactly one provider.
    pub(crate) fn unresolved(
        &self,
        found: Option<&Visible>,
        module: Option<usize>,
        module_name: &'static str,
        key: &ProviderKey,
        required_by: String,
    ) -> KernelError {
        match found {
            Some(Visible::Ambiguous(providers)) => KernelError::AmbiguousProvider {
                module: module_name,
                requested: key.to_string(),
                owners: providers
                    .iter()
                    .map(|&p| self.modules[self.providers[p].module].name)
                    .collect(),
            },
            _ => self.missing(module, module_name, key, required_by),
        }
    }

    /// Explains why `key` is not visible from `module` (`module_name` names it in the error).
    pub(crate) fn missing(
        &self,
        module: Option<usize>,
        module_name: &'static str,
        key: &ProviderKey,
        required_by: String,
    ) -> KernelError {
        let requested = key.to_string();
        let owners: Vec<usize> = self
            .providers
            .iter()
            .filter(|p| !p.def.multi && p.def.key == *key && Some(p.module) != module)
            .map(|p| p.module)
            .collect();
        let imported_owner = module.and_then(|m| {
            owners
                .iter()
                .copied()
                .find(|o| self.modules[m].imports.contains(o))
        });
        if let Some(owner) = imported_owner {
            return KernelError::NotExported {
                module: module_name,
                requested,
                owner: self.modules[owner].name,
            };
        }
        if let Some(owner) = owners
            .iter()
            .copied()
            .find(|&o| self.modules[o].exports.contains(key))
        {
            return KernelError::NotImported {
                module: module_name,
                requested,
                owner: self.modules[owner].name,
            };
        }
        if let Some(&owner) = owners.first() {
            return KernelError::NotExported {
                module: module_name,
                requested,
                owner: self.modules[owner].name,
            };
        }
        KernelError::MissingProvider {
            module: module_name,
            requested,
            required_by,
        }
    }

    /// The first module import cycle reachable from the root, if any.
    fn find_module_cycle(&self) -> Option<KernelError> {
        #[derive(Clone, Copy, PartialEq)]
        enum Mark {
            New,
            Active,
            Done,
        }
        fn visit(
            graph: &Graph,
            m: usize,
            marks: &mut [Mark],
            stack: &mut Vec<usize>,
        ) -> Option<Vec<usize>> {
            marks[m] = Mark::Active;
            stack.push(m);
            for &import in &graph.modules[m].imports {
                match marks[import] {
                    Mark::Active => {
                        let start = stack.iter().position(|&s| s == import).unwrap_or(0);
                        let mut path = stack[start..].to_vec();
                        path.push(import);
                        return Some(path);
                    }
                    Mark::New => {
                        if let Some(path) = visit(graph, import, marks, stack) {
                            return Some(path);
                        }
                    }
                    Mark::Done => {}
                }
            }
            stack.pop();
            marks[m] = Mark::Done;
            None
        }
        let mut marks = vec![Mark::New; self.modules.len()];
        visit(self, ROOT, &mut marks, &mut Vec::new()).map(|path| KernelError::ModuleCycle {
            path: path.into_iter().map(|m| self.modules[m].name).collect(),
        })
    }

    /// Modules in import post-order (imports before importers), root last.
    pub(crate) fn import_order(&self) -> Vec<usize> {
        fn visit(graph: &Graph, m: usize, seen: &mut [bool], order: &mut Vec<usize>) {
            if std::mem::replace(&mut seen[m], true) {
                return;
            }
            for &import in &graph.modules[m].imports {
                visit(graph, import, seen, order);
            }
            order.push(m);
        }
        let mut seen = vec![false; self.modules.len()];
        let mut order = Vec::with_capacity(self.modules.len());
        visit(self, ROOT, &mut seen, &mut order);
        order
    }

    fn own(&self, module: usize, key: &ProviderKey) -> Option<usize> {
        self.modules[module]
            .providers
            .iter()
            .copied()
            .find(|&p| !self.providers[p].def.multi && self.providers[p].def.key == *key)
    }

    /// Computes what each module exports (own providers and re-exports of
    /// imported exports) and, from that, what each module can see:
    /// own providers, then exports of direct imports, then exports of global modules.
    fn compute_visibility(&mut self, errors: &mut Vec<KernelError>) {
        let mut exported: Vec<VisibleMap> = vec![VisibleMap::new(); self.modules.len()];
        for m in self.import_order() {
            let mut map = VisibleMap::new();
            for key in &self.modules[m].exports {
                let found = match self.own(m, key) {
                    Some(p) => Some(Visible::One(p)),
                    None => self.modules[m]
                        .imports
                        .iter()
                        .filter_map(|&i| exported[i].get(key))
                        .fold(None, |acc: Option<Visible>, v| {
                            Some(acc.map_or_else(|| v.clone(), |a| a.union(v)))
                        }),
                };
                match found {
                    Some(v) => {
                        map.insert(key.clone(), v);
                    }
                    None => errors.push(KernelError::MissingProvider {
                        module: self.modules[m].name,
                        requested: key.to_string(),
                        required_by: format!("the exports of `{}`", self.modules[m].name),
                    }),
                }
            }
            exported[m] = map;
        }

        let globals: Vec<usize> = (0..self.modules.len())
            .filter(|&m| self.modules[m].global)
            .collect();
        let mut outside = VisibleMap::new();
        for &g in &globals {
            merge(&mut outside, &exported[g]);
        }
        let mut visible = Vec::with_capacity(self.modules.len());
        for m in 0..self.modules.len() {
            let mut map = VisibleMap::new();
            for &g in globals.iter().filter(|&&g| g != m) {
                merge(&mut map, &exported[g]);
            }
            let mut imported = VisibleMap::new();
            for &i in &self.modules[m].imports {
                merge(&mut imported, &exported[i]);
            }
            map.extend(imported);
            for &p in &self.modules[m].providers {
                if !self.providers[p].def.multi {
                    map.insert(self.providers[p].def.key.clone(), Visible::One(p));
                }
            }
            visible.push(map);
        }
        self.visible = visible;
        self.outside = outside;
    }

    /// Checks that every declared dependency resolves to exactly one visible
    /// provider. Returns the resolved dependency edges per provider.
    fn check_dependencies(&self, errors: &mut Vec<KernelError>) -> Vec<Vec<usize>> {
        let mut edges = Vec::with_capacity(self.providers.len());
        for provider in &self.providers {
            let mut resolved = Vec::new();
            for dep in &provider.def.deps {
                match self.lookup(Some(provider.module), dep) {
                    Some(Visible::One(p)) => resolved.push(*p),
                    found => errors.push(self.unresolved(
                        found,
                        Some(provider.module),
                        self.modules[provider.module].name,
                        dep,
                        format!("`{}`", provider.def.key),
                    )),
                }
            }
            edges.push(resolved);
        }
        edges
    }

    /// Lifecycle hooks must belong to a provider of the registering module.
    fn check_lifecycles(&self, errors: &mut Vec<KernelError>) {
        for (m, module) in self.modules.iter().enumerate() {
            for hooks in &module.lifecycles {
                if self.own(m, &hooks.key).is_none() {
                    errors.push(KernelError::MissingProvider {
                        module: module.name,
                        requested: hooks.key.to_string(),
                        required_by: format!("a lifecycle registration of `{}`", module.name),
                    });
                }
            }
        }
    }

    /// Command names must be unique across the app.
    fn check_commands(&self, errors: &mut Vec<KernelError>) {
        let mut seen: HashMap<&str, &'static str> = HashMap::new();
        for m in self.import_order() {
            let module = &self.modules[m];
            for command in &module.commands {
                if let Some(first) = seen.insert(command.name, module.name) {
                    errors.push(KernelError::DuplicateCommand {
                        name: command.name.to_owned(),
                        first,
                        second: module.name,
                    });
                }
            }
        }
    }

    /// Whether any module registers the command `name`.
    pub(crate) fn has_command(&self, name: &str) -> bool {
        self.commands().any(|c| c.name == name)
    }

    /// Every command, modules in dependency order.
    pub(crate) fn commands(&self) -> impl Iterator<Item = &CommandSpec> {
        self.order
            .iter()
            .flat_map(|&m| self.modules[m].commands.iter())
    }

    /// Rejects singletons that depend on request-scoped providers, directly or
    /// through transient providers.
    fn check_scopes(&self, edges: &[Vec<usize>], errors: &mut Vec<KernelError>) {
        fn reaches_request(
            graph: &Graph,
            edges: &[Vec<usize>],
            p: usize,
            seen: &mut HashSet<usize>,
        ) -> Option<usize> {
            match graph.providers[p].def.scope {
                Scope::Request => Some(p),
                Scope::Singleton => None,
                Scope::Transient => {
                    if !seen.insert(p) {
                        return None;
                    }
                    edges[p]
                        .iter()
                        .find_map(|&d| reaches_request(graph, edges, d, seen))
                }
            }
        }
        for (p, provider) in self.providers.iter().enumerate() {
            if provider.def.scope != Scope::Singleton {
                continue;
            }
            let mut seen = HashSet::new();
            if let Some(r) = edges[p]
                .iter()
                .find_map(|&d| reaches_request(self, edges, d, &mut seen))
            {
                errors.push(KernelError::ScopeInversion {
                    module: self.modules[provider.module].name,
                    singleton: provider.def.key.to_string(),
                    request_scoped: self.providers[r].def.key.to_string(),
                });
            }
        }
    }

    /// Reports every cycle in the declared provider dependencies.
    fn check_provider_cycles(&self, edges: &[Vec<usize>], errors: &mut Vec<KernelError>) {
        #[derive(Clone, Copy, PartialEq)]
        enum Mark {
            New,
            Active,
            Done,
        }
        fn visit(
            graph: &Graph,
            edges: &[Vec<usize>],
            p: usize,
            marks: &mut [Mark],
            stack: &mut Vec<usize>,
            errors: &mut Vec<KernelError>,
        ) {
            marks[p] = Mark::Active;
            stack.push(p);
            for &d in &edges[p] {
                match marks[d] {
                    Mark::Active => {
                        let start = stack.iter().position(|&s| s == d).unwrap_or(0);
                        let path = stack[start..]
                            .iter()
                            .chain(std::iter::once(&d))
                            .map(|&q| graph.providers[q].def.key.to_string())
                            .collect();
                        errors.push(KernelError::ProviderCycle { path });
                    }
                    Mark::New => visit(graph, edges, d, marks, stack, errors),
                    Mark::Done => {}
                }
            }
            stack.pop();
            marks[p] = Mark::Done;
        }
        let mut marks = vec![Mark::New; self.providers.len()];
        for p in 0..self.providers.len() {
            if marks[p] == Mark::New {
                visit(self, edges, p, &mut marks, &mut Vec::new(), errors);
            }
        }
    }

    /// Module order for construction, contributions and lifecycle hooks: a
    /// module comes after the modules it imports and the modules whose
    /// providers it uses; the root is last.
    fn dependency_order(&self, edges: &[Vec<usize>]) -> Vec<usize> {
        fn visit(
            graph: &Graph,
            edges: &[Vec<usize>],
            m: usize,
            seen: &mut [bool],
            order: &mut Vec<usize>,
        ) {
            if std::mem::replace(&mut seen[m], true) {
                return;
            }
            for &import in &graph.modules[m].imports {
                visit(graph, edges, import, seen, order);
            }
            for &p in &graph.modules[m].providers {
                for &d in &edges[p] {
                    visit(graph, edges, graph.providers[d].module, seen, order);
                }
            }
            order.push(m);
        }
        let mut seen = vec![false; self.modules.len()];
        let mut order = Vec::with_capacity(self.modules.len());
        visit(self, edges, ROOT, &mut seen, &mut order);
        order
    }

    /// A description of the graph for `check --graph`, modules in dependency order.
    pub(crate) fn report(&self) -> GraphReport {
        let modules = self
            .order
            .iter()
            .map(|&m| {
                let module = &self.modules[m];
                ModuleReport {
                    id: module.id,
                    name: module.name,
                    global: module.global,
                    imports: module
                        .imports
                        .iter()
                        .map(|&i| self.modules[i].name)
                        .collect(),
                    providers: module
                        .providers
                        .iter()
                        .map(|&p| {
                            let def = &self.providers[p].def;
                            ProviderReport {
                                key: def.key.to_string(),
                                scope: def.scope,
                                dependencies: def.deps.iter().map(ToString::to_string).collect(),
                                multi: def.multi,
                            }
                        })
                        .collect(),
                    exports: module.exports.iter().map(ToString::to_string).collect(),
                    commands: module
                        .commands
                        .iter()
                        .map(|c| CommandInfo {
                            name: c.name,
                            about: c.about,
                        })
                        .collect(),
                }
            })
            .collect();
        GraphReport { modules }
    }
}

/// Adds `from` into `into`; a key mapped to different providers becomes ambiguous.
fn merge(into: &mut VisibleMap, from: &VisibleMap) {
    for (key, v) in from {
        match into.get_mut(key) {
            Some(existing) => *existing = existing.union(v),
            None => {
                into.insert(key.clone(), v.clone());
            }
        }
    }
}

/// The output of `Module::register` for one module.
struct Registered {
    builder: ModuleBuilder,
    /// The type the registered module value was passed as.
    type_name: &'static str,
    /// For a configured instance, the module that imported it.
    configured_by: Option<ModuleId>,
    import_ids: Vec<ModuleId>,
}

/// A configured instance the walk dropped, because another configured
/// instance of its module came first.
struct Twice {
    /// The module's id.
    module: ModuleId,
    /// The module's name.
    name: &'static str,
    /// The module that imported the dropped instance (the root's id for a
    /// module the app passed).
    importer: ModuleId,
}

/// What a walk registered, and the configured instances it dropped.
struct Walked {
    registered: Vec<Registered>,
    twice: Vec<Twice>,
}

/// A module value to register: a root module borrowed from the app builder or
/// an import owned by the walk, each with the type it was passed as.
enum Source<'a> {
    Root(&'a dyn Module, &'static str),
    Import(PassedModule),
}

impl Source<'_> {
    fn module(&self) -> &dyn Module {
        match self {
            Source::Root(m, _) => *m,
            Source::Import(passed) => passed.module.as_ref(),
        }
    }

    /// `std::any::type_name` of the module value, as it was passed.
    fn type_name(&self) -> &'static str {
        match self {
            Source::Root(_, type_name) => type_name,
            Source::Import(passed) => passed.type_name,
        }
    }
}

/// A configured instance of `ModuleId` turned up after a plain instance of it
/// was registered: walk again, registering that plain import last.
struct Restart(ModuleId, &'static str);

/// Calls `register` once per module id, starting from the implicit root.
/// Configured (`for_root`) instances win over plain imports of the same id; a
/// second configured instance of an id is dropped and recorded.
fn walk(roots: &[(&dyn Module, &'static str)]) -> Result<Walked, BootErrors> {
    let mut deferred = HashSet::new();
    loop {
        match Walker::new(&deferred).run(roots) {
            Ok(walked) => return Ok(walked),
            Err(Restart(id, name)) => {
                if !deferred.insert(id) {
                    // Only the plain instance's own imports lead to the configured
                    // one: the module (transitively) imports itself.
                    return Err(KernelError::ModuleCycle {
                        path: vec![name, name],
                    }
                    .into());
                }
            }
        }
    }
}

struct Walker<'a, 'd> {
    deferred: &'d HashSet<ModuleId>,
    registered: HashSet<ModuleId>,
    configured: HashSet<ModuleId>,
    /// The module that imported the first configured instance of each id.
    configured_by: HashMap<ModuleId, ModuleId>,
    configured_queue: VecDeque<Source<'a>>,
    plain: Vec<(ModuleId, Source<'a>)>,
    out: Vec<Registered>,
    /// The configured instances dropped because one of their id came first.
    twice: Vec<Twice>,
}

impl<'a, 'd> Walker<'a, 'd> {
    fn new(deferred: &'d HashSet<ModuleId>) -> Self {
        Self {
            deferred,
            registered: HashSet::new(),
            configured: HashSet::new(),
            configured_by: HashMap::new(),
            configured_queue: VecDeque::new(),
            plain: Vec::new(),
            out: Vec::new(),
            twice: Vec::new(),
        }
    }

    fn run(mut self, roots: &[(&'a dyn Module, &'static str)]) -> Result<Walked, Restart> {
        let root_id = ModuleId::named::<AppRoot>("App");
        let mut root = ModuleBuilder::new(root_id, root_id.name());
        root.global = true;
        self.registered.insert(root_id);
        self.out.push(Registered {
            builder: root,
            type_name: std::any::type_name::<AppRoot>(),
            configured_by: None,
            import_ids: roots.iter().map(|(m, _)| m.id()).collect(),
        });
        for &(module, type_name) in roots {
            self.enqueue(Source::Root(module, type_name), root_id)?;
        }
        loop {
            if let Some(source) = self.configured_queue.pop_front() {
                self.process(source)?;
            } else if let Some(source) = self.next_plain() {
                self.process(source)?;
            } else {
                break;
            }
        }
        Ok(Walked {
            registered: self.out,
            twice: self.twice,
        })
    }

    /// Queues `source`, which `importer` imports (the root's id for a module
    /// the app passed).
    fn enqueue(&mut self, source: Source<'a>, importer: ModuleId) -> Result<(), Restart> {
        let module = source.module();
        let id = module.id();
        if module.is_configured() {
            if !self.configured.insert(id) {
                self.twice.push(Twice {
                    module: id,
                    name: module.name(),
                    importer,
                });
                return Ok(());
            }
            self.configured_by.insert(id, importer);
            if self.registered.contains(&id) {
                return Err(Restart(id, module.name()));
            }
            self.configured_queue.push_back(source);
        } else if !self.registered.contains(&id)
            && !self.configured.contains(&id)
            && !self.plain.iter().any(|(queued, _)| *queued == id)
        {
            self.plain.push((id, source));
        }
        Ok(())
    }

    /// The next plain module to register; deferred ids go last.
    fn next_plain(&mut self) -> Option<Source<'a>> {
        let (registered, configured) = (&self.registered, &self.configured);
        self.plain
            .retain(|(id, _)| !registered.contains(id) && !configured.contains(id));
        let position = self
            .plain
            .iter()
            .position(|(id, _)| !self.deferred.contains(id))
            .or(if self.plain.is_empty() { None } else { Some(0) })?;
        Some(self.plain.remove(position).1)
    }

    fn process(&mut self, source: Source<'a>) -> Result<(), Restart> {
        let module = source.module();
        let id = module.id();
        let mut builder = ModuleBuilder::new(id, module.name());
        module.register(&mut builder);
        let imports = std::mem::take(&mut builder.imports);
        self.registered.insert(id);
        let configured_by = if module.is_configured() {
            self.configured_by.get(&id).copied()
        } else {
            None
        };
        self.out.push(Registered {
            builder,
            type_name: source.type_name(),
            configured_by,
            import_ids: imports.iter().map(|import| import.module.id()).collect(),
        });
        for import in imports {
            self.enqueue(Source::Import(import), id)?;
        }
        Ok(())
    }
}

/// Turns registered builders into graph nodes; reports duplicate keys.
fn assemble(walked: Vec<Registered>, errors: &mut Vec<KernelError>) -> Graph {
    let module_index: HashMap<ModuleId, usize> = walked
        .iter()
        .enumerate()
        .map(|(i, r)| (r.builder.id, i))
        .collect();
    let mut modules = Vec::with_capacity(walked.len());
    let mut providers: Vec<ProviderNode> = Vec::new();
    for (index, registered) in walked.into_iter().enumerate() {
        let builder = registered.builder;
        let mut imports: Vec<usize> = Vec::new();
        for id in &registered.import_ids {
            let import = module_index[id];
            if !imports.contains(&import) {
                imports.push(import);
            }
        }
        let mut provider_indices: Vec<usize> = Vec::new();
        for def in builder.providers {
            if !def.multi
                && provider_indices
                    .iter()
                    .any(|&p| !providers[p].def.multi && providers[p].def.key == def.key)
            {
                errors.push(KernelError::DuplicateProvider {
                    module: builder.name,
                    key: def.key.to_string(),
                });
                continue;
            }
            provider_indices.push(providers.len());
            providers.push(ProviderNode { def, module: index });
        }
        modules.push(ModuleNode {
            id: builder.id,
            name: builder.name,
            global: builder.global,
            imports,
            providers: provider_indices,
            exports: builder.exports,
            contributions: builder.contributions,
            lifecycles: builder.lifecycles,
            commands: builder.commands,
            plugin: builder.plugin,
            plugin_twice: builder.plugin_twice,
            type_name: registered.type_name,
            configured_by: registered
                .configured_by
                .and_then(|importer| module_index.get(&importer).copied()),
        });
    }
    Graph {
        modules,
        module_index,
        providers,
        visible: Vec::new(),
        outside: VisibleMap::new(),
        order: Vec::new(),
        multi: HashMap::new(),
        located: HashMap::new(),
        first_party: HashSet::new(),
        acts_for: Vec::new(),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::{Factory, Resolver};

    /// A plugin that is not first-party, in a namespace the framework keeps.
    const LEDGER: PluginInfo =
        PluginInfo::new("navree-plugin-ledger", module_path!(), "billing", "1.0.0");

    /// The ledger plugin's module.
    struct Reserved;

    impl Module for Reserved {
        fn register(&self, m: &mut ModuleBuilder) {
            m.plugin(LEDGER);
        }
    }

    #[test]
    fn a_refused_graph_still_lists_its_plugins() {
        let roots = [PassedModule::of(Reserved)];
        assert!(Graph::build_passed(&roots, &[]).is_err());
        let report = Graph::plugins_of_refused(&roots).expect("the modules walk");
        let listed: Vec<(&str, usize)> = report
            .plugins
            .iter()
            .map(|plugin| (plugin.info.name, plugin.modules.len()))
            .collect();
        assert_eq!(listed, [("navree-plugin-ledger", 1)]);
    }

    /// Provides a private `u32` and an unexported `String`.
    struct Private;

    impl Module for Private {
        fn register(&self, m: &mut ModuleBuilder) {
            m.value(1_u32).value(String::from("private"));
        }
    }

    /// Exports a `String`, an `i64` and a `u8` named `eight`.
    struct Exporting;

    impl Module for Exporting {
        fn register(&self, m: &mut ModuleBuilder) {
            m.value(String::from("exported"))
                .exports::<String>()
                .value(1_i64)
                .exports::<i64>()
                .factory(
                    Factory::<u8>::new(|_: Resolver| async { Ok(Arc::new(8_u8)) }).named("eight"),
                )
                .export_key(ProviderKey::named::<u8>("eight"));
        }
    }

    /// Exports another `i64`: two modules export one, so the locator cannot pick.
    struct AlsoExporting;

    impl Module for AlsoExporting {
        fn register(&self, m: &mut ModuleBuilder) {
            m.value(2_i64).exports::<i64>();
        }
    }

    fn graph() -> Graph {
        let roots: Vec<Box<dyn Module>> = vec![
            Box::new(Private),
            Box::new(Exporting),
            Box::new(AlsoExporting),
        ];
        Graph::build(&roots, &[]).expect("graph builds")
    }

    #[test]
    fn the_locator_map_answers_as_a_scan_of_every_provider_does() {
        let graph = graph();
        let mut keys: Vec<ProviderKey> =
            graph.providers.iter().map(|p| p.def.key.clone()).collect();
        keys.push(ProviderKey::of::<bool>());
        keys.push(ProviderKey::named::<u8>("nine"));
        for key in &keys {
            let mapped = graph.locate(key, "a test").map_err(|e| e.to_string());
            let scanned = graph
                .locate_by_scan(key, "a test")
                .map_err(|e| e.to_string());
            assert_eq!(mapped, scanned, "{key}");
        }
    }

    #[test]
    fn only_keys_with_one_answer_are_in_the_locator_map() {
        let graph = graph();
        // One provider, private: the locator ignores visibility.
        assert!(graph.located.contains_key(&ProviderKey::of::<u32>()));
        // Two providers, one exported: the exported one.
        let string = graph.located[&ProviderKey::of::<String>()];
        assert_eq!(
            graph.modules[graph.providers[string].module].name,
            "Exporting"
        );
        assert!(
            graph
                .located
                .contains_key(&ProviderKey::named::<u8>("eight"))
        );
        // Two exported providers: ambiguous, answered by the scan's error.
        assert!(!graph.located.contains_key(&ProviderKey::of::<i64>()));
        assert!(matches!(
            graph.locate(&ProviderKey::of::<i64>(), "a test"),
            Err(KernelError::AmbiguousProvider { .. })
        ));
        assert!(matches!(
            graph.locate(&ProviderKey::of::<bool>(), "a test"),
            Err(KernelError::MissingProvider { .. })
        ));
    }
}