ulo 0.1.0-alpha.2

Fast and modular web framework for scalable applications
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
use std::collections::HashSet;
use std::error::Error;
use std::fmt;
use std::panic::Location;

use crate::graph::visibility::two_versions;
use crate::hooks::HookKind;
use crate::key::{BindingKind, Key, KeyName, role_spelling};
use crate::module::{ModuleName, colliding_names};
use crate::redact::{Redacted, SecretRegistry, scrub};
use crate::runtime::Runtime;
use crate::scope::ScopeKind;
use crate::timer::Timer;
use crate::type_name::{TypeName, short_type_name};

/// Every failure `wire()` found, one entry each, in the order the six steps of §10.1 found
/// them. `Display` writes the full report:
///
/// ```text
/// error: wiring failed with 2 errors
///
///   × missing dependency `dyn Mailer`
///     ├─ needed by UserService (param `mailer`) in UsersModule
///     └─ help: import a module that exports `dyn Mailer`, or provide it in UsersModule
///
///   × scope violation: singleton `ReportService` depends on per-execution data
///     └─ ReportService → AuditContext (execution) → Ext<CurrentUser>
///        help: declare ReportService #[injectable(execution)], or inject a factory
/// ```
///
/// Type names are cut to their last path segment. Where the report would print two different
/// types alike, `a::Config` and `b::Config`, whether as a key's type, as its qualifier or as a
/// transport, it prints those types with their full paths, and the rest of each key short; two different
/// modules printing alike, `billing::Module` and `users::Module`, print with their full paths. Which
/// names an entry stores as values and which it carries in rendered text follows
/// [`TypeName`](crate::TypeName)'s rule. A [`WiringError`] displayed on its own applies the same
/// rule to the keys, transports and modules it names.
///
/// `Debug` writes the same report, so `main` returning `Box<dyn Error>` prints it.
pub struct WiringErrors {
    errors: Vec<WiringError>,
}

impl WiringErrors {
    pub(crate) fn new(errors: Vec<WiringError>) -> Self {
        WiringErrors { errors }
    }

    pub fn iter(&self) -> std::slice::Iter<'_, WiringError> {
        self.errors.iter()
    }

    pub fn len(&self) -> usize {
        self.errors.len()
    }

    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }
}

impl<'a> IntoIterator for &'a WiringErrors {
    type Item = &'a WiringError;
    type IntoIter = std::slice::Iter<'a, WiringError>;

    fn into_iter(self) -> Self::IntoIter {
        self.errors.iter()
    }
}

impl fmt::Display for WiringErrors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let count = self.errors.len();
        let noun = if count == 1 { "error" } else { "errors" };
        write!(f, "error: wiring failed with {count} {noun}")?;
        let full = Collisions {
            types: TypeName::colliding(self.errors.iter().flat_map(WiringError::type_names)),
            modules: colliding_names(self.errors.iter().flat_map(|error| error.module_names())),
        };
        for error in &self.errors {
            let text = Rendered { error, full: &full }.to_string();
            let mut lines = text.lines();
            if let Some(first) = lines.next() {
                write!(f, "\n\n  × {first}")?;
            }
            for line in lines {
                write!(f, "\n    {line}")?;
            }
        }
        Ok(())
    }
}

impl fmt::Debug for WiringErrors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl Error for WiringErrors {}

/// One wiring failure. `at` is the source location of the registration call that declared the
/// offending item, captured with `#[track_caller]`.
#[non_exhaustive]
#[derive(Debug)]
pub enum WiringError {
    /// Step 1: the path of module names, from a module back to itself.
    ImportCycle { path: Vec<ModuleName> },
    /// Step 1: a re-export of a key the module cannot see.
    ReexportNotVisible { module: ModuleName, key: KeyName, at: &'static Location<'static> },
    /// Step 1: a re-export of a key the module sees from several sources.
    ReexportAmbiguous { module: ModuleName, key: KeyName, sources: Vec<ModuleName>, at: &'static Location<'static> },
    /// Step 1: an execution input declared inside a keyed module.
    KeyedInput { module: ModuleName, key: KeyName, at: &'static Location<'static> },
    /// Step 1: a keyed module keyed again, `m.keyed::<Inner>().keyed::<Outer>()`. The module's
    /// identity carries `outer` and its exports `inner`, so the two disagree for every module
    /// written this way. `module` is the module as its identity names it.
    NestedKeyed { module: ModuleName, outer: TypeName, inner: TypeName },
    /// Step 1: a second registration of an identity already registered, whose
    /// [`Module::settings`](crate::Module::settings) differ from the first's. The two are one
    /// module and only the first registers, so the second's settings would go unused. `first`
    /// is the registration holding the identity, `second` the later one; `settings` holds each
    /// setting that differs, in the order the first wrote them. Also answered by `load` for a
    /// module whose identity the graph holds.
    DifferingSettings { module: ModuleName, first: ModuleSite, second: ModuleSite, settings: Vec<DifferingSetting> },
    /// Step 1: `export::<T>()` of a key the module does not bind. `imported` when the module sees
    /// the key through an import, which leaves through `reexport`; `near` is a key the module
    /// binds that is spelled the same up to a trailing `+ Send + Sync`, or by its last path
    /// segment.
    ExportNotBound { module: ModuleName, key: KeyName, imported: bool, near: Option<KeyName>, at: &'static Location<'static> },

    /// Step 2: a second single binding for a key in one module, naming both source locations.
    DuplicateBinding { key: KeyName, module: ModuleName, first: &'static Location<'static>, second: &'static Location<'static> },
    /// Step 2: `provide` and `contribute` under one key.
    KindMix { key: KeyName, module: ModuleName, single: &'static Location<'static>, collection: &'static Location<'static> },
    /// Step 2: an alias whose target nothing visible binds.
    DanglingAlias { alias: KeyName, target: KeyName, module: ModuleName, at: &'static Location<'static> },
    /// Step 2: the `Err` a `try_value` recorded, redacted: `ModuleDef::try_value`, or
    /// `Contribute::try_value`, whose `key` is the collection's.
    ValueFailed { module: ModuleName, key: KeyName, error: Redacted, at: &'static Location<'static> },
    /// Step 2: a qualified contribution under a role key, `key` the qualified collection. A
    /// transport reads only the role key's unqualified collection.
    QualifiedRoleContribution { key: KeyName, module: ModuleName, at: &'static Location<'static> },
    /// Step 2: a single binding under a role key, through its primary key, an `also_as` key or an
    /// alias. A transport reads enhancers only from the role key's collection. `key` is the
    /// binding's key that names the role key, qualified as the binding is, and `at` the call that
    /// registered the binding.
    SingleRoleBinding { key: KeyName, module: ModuleName, at: &'static Location<'static> },
    /// Step 2: two `.ready(..)` checks on one binding.
    DuplicateReadiness { key: KeyName, module: ModuleName, first: &'static Location<'static>, second: &'static Location<'static> },
    /// Step 2: an execution input a transport declares through `Transport::inputs` that has a
    /// second source. `first` is a transport's declaration; `second` is a module's
    /// `input::<T>().seeded_by::<Tr>()` naming another seeder, a later transport's declaration,
    /// or a single binding.
    InputConflict { key: KeyName, first: InputOrigin, second: InputOrigin },
    /// Step 2, tests: an override that matches no binding. `keyed` names a keyed module whose
    /// qualifier the override's key carries and which binds the key unqualified, as a keyed
    /// module's bindings are: `.in_module_keyed::<M, Q>()` reaches that binding as written.
    OverrideUnmatched { key: KeyName, keyed: Option<ModuleName>, at: &'static Location<'static> },
    /// Step 2, tests: an override that matches several bindings, listing every match; scope it
    /// with `.in_module::<M>()` or replace all with `.everywhere()`.
    OverrideAmbiguous { key: KeyName, matches: Vec<ModuleName>, at: &'static Location<'static> },
    /// Step 2, tests: `.in_module::<M>()` over several instances of `M`; name one with
    /// `.in_module_keyed::<M, Q>()` or `.in_module_of(&config)`.
    OverrideModuleAmbiguous { module: &'static str, candidates: Vec<ModuleName>, at: &'static Location<'static> },
    /// Step 2, tests: an override that would change a key's kind; `override_many` replaces a
    /// whole collection.
    OverrideKind { key: KeyName, expected: BindingKind, found: BindingKind, at: &'static Location<'static> },
    /// Step 2, tests: `override_value::<dyn Timer>`. Hint: "set it with `TestApp::timer(..)`".
    TimerOverride { at: &'static Location<'static> },
    /// Step 2, tests: `override_value::<dyn Runtime>`. Hint: "set it with `TestApp::runtime(..)`".
    RuntimeOverride { at: &'static Location<'static> },
    /// Step 2, tests: a `replace_module` replacement that does not export a superset of the
    /// original's keys.
    ReplacementMissingExports { original: ModuleName, replacement: ModuleName, missing: Vec<KeyName> },
    /// Step 2, tests: a `replace_module` whose original no module imports, the same stale mock an
    /// override that matches nothing is.
    ReplacementUnmatched { original: ModuleName, at: &'static Location<'static> },
    /// Step 2, tests: a second `replace_module` of an original already replaced, naming both
    /// calls. Wiring applies the first.
    DuplicateReplacement { original: ModuleName, first: &'static Location<'static>, second: &'static Location<'static> },
    /// Step 2: a controller's `.at(prefix)` that none of its handlers reads, every one belonging
    /// to a transport whose `Transport::READS_PREFIX` is `false`, an RPC pattern or a gRPC method
    /// path. `transports` lists those transports, each once, empty for a controller that mounts
    /// no handler; `at` is the `.at(..)` call.
    UnreadPrefix { controller: KeyName, module: ModuleName, prefix: String, transports: Vec<TypeName>, at: &'static Location<'static> },

    /// Step 3: an injection point whose key the module cannot see. `consumer` names what reads
    /// it, as in ``UserService (param `mailer`)``. `near` is a visible key spelled the same up to
    /// a trailing `+ Send + Sync`, or by its last path segment, with the module exporting it.
    Missing { key: KeyName, consumer: String, module: ModuleName, near: Option<(KeyName, ModuleName)> },
    /// Step 3: an injection point whose key the module sees from several sources, naming each.
    Ambiguous { key: KeyName, consumer: String, module: ModuleName, sources: Vec<(ModuleName, &'static Location<'static>)> },
    /// Step 3: a binding that is not a controller reads a controller's key, through its
    /// construction, a hook, its readiness check or an alias. A controller is the edge of the
    /// application, reached by its transport alone. `consumer` names the reader as `Missing`
    /// does; `module` is the reader's module, and `controller_module` the controller's.
    ControllerRead { controller: KeyName, consumer: String, module: ModuleName, controller_module: ModuleName },

    /// Step 4: the full path, as in `A → B → C → A`, each step with its module.
    Cycle { path: Vec<(KeyName, ModuleName)> },

    /// Step 5: a binding that cannot run in an execution depends on per-execution data. `path`
    /// is the dependency path that introduces it, each step as printed. `by_closure` when a
    /// factory closure builds the binding rather than a `Construct` type, so its scope is
    /// written where the closure is registered, not on an `#[injectable]`.
    ScopeViolation { binding: KeyName, declared: ScopeKind, by_closure: bool, module: ModuleName, path: Vec<String> },
    /// Step 5: hooks on an `Auto` binding the scope pass inferred per-execution, a contribution
    /// declared by closure included.
    HooksOnPerExecution { binding: KeyName, module: ModuleName },
    /// Step 5: an enhancer a handler declares by closure in an explicit singleton scope, which
    /// reads per-execution data. `closure` names it, as in ``method-level guard #2 of
    /// UsersController::get``, and the report writes the handler's `transport` after it, as in
    /// `(Http)`; `role` is `guard`, `interceptor` or `error handler`; `path` runs from the
    /// injection point to the read of execution data.
    ClosureScopeViolation {
        closure: String,
        transport: TypeName,
        role: &'static str,
        path: Vec<String>,
        at: &'static Location<'static>,
    },
    /// Step 5: a hook, readiness, module-hook or metadata closure that reads `Ext`,
    /// `ExecutionRef`, an execution input or a per-execution key, where no execution exists.
    /// `closure` names it, as in ``readiness check of `PgPool` in DbModule``; `path` runs from the
    /// injection point to the read of execution data. A metadata value has no `at`.
    ClosureNeedsExecution { closure: String, path: Vec<String>, at: Option<&'static Location<'static>> },
    /// Step 5: a non-optional input read on a path from a handler whose transport does not seed
    /// it. `steps` holds the steps after the handler, each binding between it and the read and
    /// then the injection point; the report writes the handler and its `transport` ahead of them.
    InputNotSeeded { handler: String, transport: TypeName, input: KeyName, seeder: TypeName, steps: Vec<String> },

    /// Step 6: an explicit bound with no `Timer`. `item` names the bounded item, as in
    /// ``readiness `.attempt_timeout` of `PgPool` ``.
    BoundWithoutTimer { item: String, at: &'static Location<'static> },
    /// Step 6: a readiness `.backoff(..)` on an app with no `Timer`, which cannot wait between
    /// attempts. `binding` is the checked binding as printed, and `at` the last `.backoff(..)`
    /// call.
    BackoffWithoutTimer { binding: String, at: &'static Location<'static> },
    /// Step 6: a builder knob set on an app with no `Timer`.
    KnobWithoutTimer { knob: &'static str },
    /// Step 6: a bound of `After(Duration::ZERO)` on a construction, a readiness check, one of its
    /// attempts or a hook, which would time the item out before it starts. Refused whatever the
    /// app's clock, and reported instead of `BoundWithoutTimer` on an app with none. `binding` is
    /// the binding the item belongs to, `None` for a module's own hook; `at` is the call that wrote
    /// the bound, or the registration that brought the type in for a trait const. Hint:
    /// `.unbounded()`.
    ZeroBound { item: BoundItem, binding: Option<KeyName>, module: ModuleName, at: &'static Location<'static> },
    /// Step 6: `construct_timeout` or `hook_timeout` set to `Duration::ZERO`, which would end
    /// every item left at `Default` before it starts. `knob` is the builder method's name and
    /// `at` the call that set it. Hint: `.unbounded()` on the items.
    ZeroDefault { knob: &'static str, at: &'static Location<'static> },
}

/// The item a bound is written on, as [`WiringError::ZeroBound`] names it.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BoundItem {
    /// The construction: `.timeout(..)` after the registration, or `CONSTRUCT_TIMEOUT`.
    Construction,
    /// A readiness check as a whole: `.timeout(..)` after `.ready(..)`.
    ReadinessWhole,
    /// One attempt of a readiness check: `.attempt_timeout(..)`.
    ReadinessAttempt,
    /// A hook: `.timeout(..)` after an `on_*`, or the hook trait's `TIMEOUT`.
    Hook(HookKind),
}

impl fmt::Display for BoundItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BoundItem::Construction => f.write_str("construction"),
            BoundItem::ReadinessWhole => f.write_str("readiness check"),
            BoundItem::ReadinessAttempt => f.write_str("readiness attempt"),
            BoundItem::Hook(kind) => write!(f, "`{kind}` hook"),
        }
    }
}

impl WiringError {
    /// Every key this entry prints, for the check that decides which keys print with their full
    /// paths.
    fn key_names(&self) -> Vec<&KeyName> {
        match self {
            WiringError::ReexportNotVisible { key, .. }
            | WiringError::ReexportAmbiguous { key, .. }
            | WiringError::KeyedInput { key, .. }
            | WiringError::DuplicateBinding { key, .. }
            | WiringError::KindMix { key, .. }
            | WiringError::ValueFailed { key, .. }
            | WiringError::QualifiedRoleContribution { key, .. }
            | WiringError::SingleRoleBinding { key, .. }
            | WiringError::DuplicateReadiness { key, .. }
            | WiringError::InputConflict { key, .. }
            | WiringError::OverrideUnmatched { key, .. }
            | WiringError::OverrideAmbiguous { key, .. }
            | WiringError::OverrideKind { key, .. }
            | WiringError::Ambiguous { key, .. } => vec![key],
            WiringError::ExportNotBound { key, near, .. } => std::iter::once(key).chain(near).collect(),
            WiringError::DanglingAlias { alias, target, .. } => vec![alias, target],
            WiringError::ReplacementMissingExports { missing, .. } => missing.iter().collect(),
            WiringError::Missing { key, near, .. } => std::iter::once(key).chain(near.iter().map(|(bound, _)| bound)).collect(),
            WiringError::Cycle { path } => path.iter().map(|(key, _)| key).collect(),
            WiringError::ScopeViolation { binding, .. } | WiringError::HooksOnPerExecution { binding, .. } => vec![binding],
            WiringError::InputNotSeeded { input, .. } => vec![input],
            WiringError::UnreadPrefix { controller, .. } | WiringError::ControllerRead { controller, .. } => vec![controller],
            WiringError::ZeroBound { binding, .. } => binding.iter().collect(),
            WiringError::ImportCycle { .. }
            | WiringError::NestedKeyed { .. }
            | WiringError::DifferingSettings { .. }
            | WiringError::OverrideModuleAmbiguous { .. }
            | WiringError::TimerOverride { .. }
            | WiringError::RuntimeOverride { .. }
            | WiringError::ReplacementUnmatched { .. }
            | WiringError::DuplicateReplacement { .. }
            | WiringError::ClosureNeedsExecution { .. }
            | WiringError::ClosureScopeViolation { .. }
            | WiringError::BoundWithoutTimer { .. }
            | WiringError::BackoffWithoutTimer { .. }
            | WiringError::ZeroDefault { .. }
            | WiringError::KnobWithoutTimer { .. } => Vec::new(),
        }
    }

    /// Every type name this entry prints, for the check that decides which print with their full
    /// paths: each key's type and qualifier, and the transports an input or closure entry names.
    /// A key's kind plays no part: `a::Config` and `b::Config (collection)` collide too.
    fn type_names(&self) -> Vec<TypeName> {
        let keys = self.key_names().into_iter().flat_map(|name| name.key().type_names());
        let transports = match self {
            WiringError::InputNotSeeded { transport, seeder, .. } => vec![*transport, *seeder],
            WiringError::ClosureScopeViolation { transport, .. } => vec![*transport],
            WiringError::UnreadPrefix { transports, .. } => transports.clone(),
            WiringError::InputConflict { first, second, .. } => first.type_names().into_iter().chain(second.type_names()).collect(),
            WiringError::NestedKeyed { outer, inner, .. } => vec![*outer, *inner],
            WiringError::ImportCycle { .. }
            | WiringError::DifferingSettings { .. }
            | WiringError::ReexportNotVisible { .. }
            | WiringError::ReexportAmbiguous { .. }
            | WiringError::KeyedInput { .. }
            | WiringError::ExportNotBound { .. }
            | WiringError::DuplicateBinding { .. }
            | WiringError::KindMix { .. }
            | WiringError::DanglingAlias { .. }
            | WiringError::ValueFailed { .. }
            | WiringError::QualifiedRoleContribution { .. }
            | WiringError::SingleRoleBinding { .. }
            | WiringError::DuplicateReadiness { .. }
            | WiringError::OverrideUnmatched { .. }
            | WiringError::OverrideAmbiguous { .. }
            | WiringError::OverrideModuleAmbiguous { .. }
            | WiringError::OverrideKind { .. }
            | WiringError::TimerOverride { .. }
            | WiringError::RuntimeOverride { .. }
            | WiringError::ReplacementMissingExports { .. }
            | WiringError::ReplacementUnmatched { .. }
            | WiringError::DuplicateReplacement { .. }
            | WiringError::Missing { .. }
            | WiringError::Ambiguous { .. }
            | WiringError::Cycle { .. }
            | WiringError::ScopeViolation { .. }
            | WiringError::HooksOnPerExecution { .. }
            | WiringError::ClosureNeedsExecution { .. }
            | WiringError::BoundWithoutTimer { .. }
            | WiringError::BackoffWithoutTimer { .. }
            | WiringError::KnobWithoutTimer { .. }
            | WiringError::ControllerRead { .. }
            | WiringError::ZeroDefault { .. }
            | WiringError::ZeroBound { .. } => Vec::new(),
        };
        keys.chain(transports).collect()
    }

    /// Every module name this entry holds as a `ModuleName`, for the same check over modules.
    fn module_names(&self) -> Vec<&ModuleName> {
        match self {
            WiringError::ImportCycle { path } => path.iter().collect(),
            WiringError::ReexportNotVisible { module, .. }
            | WiringError::KeyedInput { module, .. }
            | WiringError::ExportNotBound { module, .. }
            | WiringError::DuplicateBinding { module, .. }
            | WiringError::KindMix { module, .. }
            | WiringError::DanglingAlias { module, .. }
            | WiringError::ValueFailed { module, .. }
            | WiringError::QualifiedRoleContribution { module, .. }
            | WiringError::SingleRoleBinding { module, .. }
            | WiringError::DuplicateReadiness { module, .. }
            | WiringError::ScopeViolation { module, .. }
            | WiringError::HooksOnPerExecution { module, .. }
            | WiringError::UnreadPrefix { module, .. }
            | WiringError::NestedKeyed { module, .. }
            | WiringError::ZeroBound { module, .. } => vec![module],
            WiringError::ControllerRead { module, controller_module, .. } => vec![module, controller_module],
            WiringError::DifferingSettings { module, first, second, .. } => {
                std::iter::once(module).chain(first.importer()).chain(second.importer()).collect()
            }
            WiringError::ReexportAmbiguous { module, sources, .. } => std::iter::once(module).chain(sources).collect(),
            WiringError::OverrideUnmatched { keyed, .. } => keyed.iter().collect(),
            WiringError::OverrideAmbiguous { matches, .. } => matches.iter().collect(),
            WiringError::OverrideModuleAmbiguous { candidates, .. } => candidates.iter().collect(),
            WiringError::ReplacementMissingExports { original, replacement, .. } => vec![original, replacement],
            WiringError::ReplacementUnmatched { original, .. } | WiringError::DuplicateReplacement { original, .. } => {
                vec![original]
            }
            WiringError::Missing { module, near, .. } => {
                std::iter::once(module).chain(near.iter().map(|(_, exporter)| exporter)).collect()
            }
            WiringError::Ambiguous { module, sources, .. } => {
                std::iter::once(module).chain(sources.iter().map(|(source, _)| source)).collect()
            }
            WiringError::Cycle { path } => path.iter().map(|(_, module)| module).collect(),
            WiringError::InputConflict { first, second, .. } => first.module().into_iter().chain(second.module()).collect(),
            WiringError::OverrideKind { .. }
            | WiringError::TimerOverride { .. }
            | WiringError::RuntimeOverride { .. }
            | WiringError::ClosureNeedsExecution { .. }
            | WiringError::ClosureScopeViolation { .. }
            | WiringError::InputNotSeeded { .. }
            | WiringError::BoundWithoutTimer { .. }
            | WiringError::BackoffWithoutTimer { .. }
            | WiringError::ZeroDefault { .. }
            | WiringError::KnobWithoutTimer { .. } => Vec::new(),
        }
    }

    /// The entry, each key and module in `full` printed with its full paths.
    fn render(&self, f: &mut fmt::Formatter<'_>, full: &Collisions) -> fmt::Result {
        let show = |name: &KeyName| name.text_in(&full.types);
        let show_module =
            |name: &ModuleName| if full.modules.contains(name) { format!("{name:#}") } else { name.to_string() };
        let type_text = |name: &KeyName| name.key().type_name().written(&full.types);
        let show_type = |name: TypeName| name.written(&full.types);
        match self {
            WiringError::ImportCycle { path } => tree(
                f,
                format!("import cycle: {}", closed_loop(path.iter().map(show_module).collect())),
                vec!["help: move what the modules in the cycle share into a module each of them imports".to_owned()],
            ),
            WiringError::ReexportNotVisible { module, key, at } => {
                let key = show(key);
                let module = show_module(module);
                tree(
                    f,
                    format!("re-export of `{key}` from {module}, which {module} cannot see"),
                    vec![
                        format!("declared at {}", place(at)),
                        format!("help: import a module that exports `{key}`, or remove the re-export"),
                    ],
                )
            }
            WiringError::ReexportAmbiguous { module, key, sources, at } => {
                let key = show(key);
                let module = show_module(module);
                let mut items: Vec<String> = sources.iter().map(|s| format!("exported by {}", show_module(s))).collect();
                items.push(format!("declared at {}", place(at)));
                items.push(format!("help: import `{key}` into {module} from one module only"));
                tree(f, format!("ambiguous re-export of `{key}` in {module}"), items)
            }
            WiringError::KeyedInput { module, key, at } => tree(
                f,
                format!("execution input `{}` declared in the keyed module {}", show(key), show_module(module)),
                vec![
                    format!("declared at {}", place(at)),
                    "help: inputs are app-wide and belong to transports; declare it in a module that is not keyed"
                        .to_owned(),
                ],
            ),
            WiringError::ExportNotBound { module, key, imported, near, at } => {
                let key = show(key);
                let module = show_module(module);
                let help = match near {
                    Some(near) => format!("help: {module} binds `{}`; the export names `{key}`", show(near)),
                    None if *imported => format!(
                        "help: an import of {module} provides `{key}`; re-export it with `reexport`, or bind it in {module}"
                    ),
                    None => format!("help: bind `{key}` in {module}, or remove the export"),
                };
                tree(
                    f,
                    format!("export of `{key}` from {module}, which {module} does not bind"),
                    vec![format!("declared at {}", place(at)), help],
                )
            }
            WiringError::DuplicateBinding { key, module, first, second } => tree(
                f,
                format!("duplicate binding for `{}` in {}", show(key), show_module(module)),
                vec![
                    format!("first bound at {}", place(first)),
                    format!("bound again at {}", place(second)),
                    "help: remove one, or give one a qualifier with `.qualified::<Q>()`".to_owned(),
                ],
            ),
            WiringError::KindMix { key, module, single, collection } => tree(
                f,
                format!("`{}` is bound both as a single binding and as a collection in {}", show(key), show_module(module)),
                vec![
                    format!("single binding at {}", place(single)),
                    format!("contribution at {}", place(collection)),
                    "help: contribute every entry with `contribute::<T>()` and read them as `Many<T>`, or bind it once"
                        .to_owned(),
                ],
            ),
            WiringError::DanglingAlias { alias, target, module, at } => {
                let target = show(target);
                let module = show_module(module);
                tree(
                    f,
                    format!("alias `{}` in {module} points at `{target}`, which {module} cannot see", show(alias)),
                    vec![
                        format!("declared at {}", place(at)),
                        format!("help: bind `{target}` in {module}, or import a module that exports it"),
                    ],
                )
            }
            WiringError::ValueFailed { module, key, error, at } => tree(
                f,
                format!("the value for `{}` in {} failed to build: {error}", show(key), show_module(module)),
                vec![format!("recorded by `try_value` at {}", place(at))],
            ),
            WiringError::QualifiedRoleContribution { key, module, at } => {
                let role = role_spelling(&type_text(key));
                tree(
                    f,
                    format!("a qualified contribution to the role key `{role}` in {} is read by no transport", show_module(module)),
                    vec![
                        format!("contributed as `{}` at {}", role_spelling(&show(key)), place(at)),
                        format!("help: contribute it unqualified; a transport reads only `{role}`"),
                    ],
                )
            }
            WiringError::SingleRoleBinding { key, module, at } => {
                let role = role_spelling(&type_text(key));
                tree(
                    f,
                    format!("a single binding under the role key `{role}` in {} is read by no transport", show_module(module)),
                    vec![
                        format!("bound as `{}` at {}", role_spelling(&show(key)), place(at)),
                        format!("help: contribute it: `into {role}: [..]`, or `m.contribute::<{role}>()`"),
                    ],
                )
            }
            WiringError::DuplicateReadiness { key, module, first, second } => tree(
                f,
                format!("two readiness checks on `{}` in {}", show(key), show_module(module)),
                vec![
                    format!("first `.ready(..)` at {}", place(first)),
                    format!("second `.ready(..)` at {}", place(second)),
                    "help: fold both into one check".to_owned(),
                ],
            ),
            WiringError::InputConflict { key, first, second } => tree(
                f,
                format!("execution input `{}` has two sources", show(key)),
                vec![
                    first.line(&show_module, &show_type),
                    second.line(&show_module, &show_type),
                    "help: an input is seeded by the one transport that declares it, and no module binds it; remove the other source"
                        .to_owned(),
                ],
            ),
            WiringError::OverrideUnmatched { key, keyed, at } => {
                let key = show(key);
                let help = match keyed {
                    Some(module) => format!(
                        "help: {} binds it unqualified, as a keyed module's bindings are; reach it with `.in_module_keyed::<M, Q>()` and no `.qualified`",
                        show_module(module)
                    ),
                    None => format!("help: remove the override, or bind `{key}` in the module the test expects"),
                };
                tree(f, format!("override of `{key}` matches no binding"), vec![format!("declared at {}", place(at)), help])
            }
            WiringError::OverrideAmbiguous { key, matches, at } => {
                let mut items: Vec<String> = matches.iter().map(|m| format!("bound in {}", show_module(m))).collect();
                items.push(format!("declared at {}", place(at)));
                items.push("help: scope it with `.in_module::<M>()`, or replace every match with `.everywhere()`".to_owned());
                tree(f, format!("override of `{}` matches several bindings", show(key)), items)
            }
            WiringError::OverrideModuleAmbiguous { module, candidates, at } => {
                let module = short_type_name(*module);
                let mut items: Vec<String> = candidates.iter().map(|c| format!("instance {}", show_module(c))).collect();
                items.push(format!("declared at {}", place(at)));
                items.push(format!("help: name one with `.in_module_keyed::<{module}, Q>()` or `.in_module_of(&config)`"));
                tree(f, format!("`.in_module::<{module}>()` matches several instances of {module}"), items)
            }
            WiringError::OverrideKind { key, expected, found, at } => tree(
                f,
                format!(
                    "override of `{}` would change its kind: the binding is {}, the override {}",
                    show(key),
                    kind_text(*expected),
                    kind_text(*found)
                ),
                vec![format!("declared at {}", place(at)), "help: `override_many` replaces a whole collection".to_owned()],
            ),
            WiringError::TimerOverride { at } => tree(
                f,
                "`override_value::<dyn Timer>` overrides app configuration, not a binding".to_owned(),
                vec![format!("declared at {}", place(at)), "help: set it with `TestApp::timer(..)`".to_owned()],
            ),
            WiringError::RuntimeOverride { at } => tree(
                f,
                "`override_value::<dyn Runtime>` overrides app configuration, not a binding".to_owned(),
                vec![format!("declared at {}", place(at)), "help: set it with `TestApp::runtime(..)`".to_owned()],
            ),
            WiringError::ReplacementMissingExports { original, replacement, missing } => {
                let original = show_module(original);
                let replacement = show_module(replacement);
                let mut items: Vec<String> = missing.iter().map(|k| format!("missing `{}`", show(k))).collect();
                items.push(format!("help: export the missing keys from {replacement}"));
                tree(f, format!("{replacement} replaces {original} without exporting every key {original} exports"), items)
            }
            WiringError::ReplacementUnmatched { original, at } => {
                let original = show_module(original);
                tree(
                    f,
                    format!("`replace_module` replaces {original}, which no module imports"),
                    vec![
                        format!("declared at {}", place(at)),
                        format!("help: remove the replacement, or import {original} where the test expects it"),
                    ],
                )
            }
            WiringError::DuplicateReplacement { original, first, second } => tree(
                f,
                format!("two `replace_module` calls replace {}", show_module(original)),
                vec![
                    format!("first `replace_module` at {}", place(first)),
                    format!("second `replace_module` at {}", place(second)),
                    "help: keep one; wiring applied only the first".to_owned(),
                ],
            ),
            WiringError::UnreadPrefix { controller, module, prefix, transports, at } => {
                let readers = if transports.is_empty() {
                    "it mounts no handler".to_owned()
                } else {
                    let names: Vec<String> = transports.iter().map(|transport| show_type(*transport)).collect();
                    format!("its handlers belong to {}, which join no prefix to their routes", names.join(", "))
                };
                tree(
                    f,
                    format!("the prefix `{prefix}` on `{}` in {} is read by none of its handlers", show(controller), show_module(module)),
                    vec![
                        readers,
                        format!("set by `.at(..)` at {}", place(at)),
                        "help: remove the `.at(..)`; a prefix reaches HTTP routes and WebSocket gateway paths".to_owned(),
                    ],
                )
            }
            WiringError::Missing { key, consumer, module, near } => {
                let builder = builder_help(key.key());
                let missing = key.key();
                let key = show(key);
                let module = show_module(module);
                let help = match (builder, near) {
                    (Some(help), _) => help.to_owned(),
                    (None, Some((bound, exporter))) if two_versions(bound.key(), missing) => format!(
                        "help: {} exports `{}`, the same type from two versions of its crate; `cargo tree -d` lists them",
                        show_module(exporter),
                        show(bound)
                    ),
                    (None, Some((bound, exporter))) => {
                        format!("help: {} exports `{}`; the injection point reads `{key}`", show_module(exporter), show(bound))
                    }
                    (None, None) => format!("help: import a module that exports `{key}`, or provide it in {module}"),
                };
                tree(f, format!("missing dependency `{key}`"), vec![format!("needed by {consumer} in {module}"), help])
            }
            WiringError::Ambiguous { key, consumer, module, sources } => {
                let shown: Vec<(String, &Location<'static>)> = sources.iter().map(|(m, at)| (show_module(m), *at)).collect();
                let width = shown.iter().map(|(m, _)| m.chars().count()).max().unwrap_or(0);
                let mut items = vec![format!("needed by {consumer}")];
                items.extend(shown.iter().map(|(m, at)| format!("exported by {m:<width$}   ({})", place(at))));
                tree(f, format!("ambiguous dependency `{}` in {}", show(key), show_module(module)), items)
            }
            WiringError::Cycle { path } => {
                let mut steps: &[(KeyName, ModuleName)] = path;
                if let [first, .., last] = steps {
                    if first.0 == last.0 {
                        steps = &steps[..steps.len() - 1];
                    }
                }
                let head = format!("dependency cycle: {}", closed_loop(steps.iter().map(|(k, _)| show(k)).collect()));
                tree(f, head, steps.iter().map(|(k, m)| format!("`{}` in {}", show(k), show_module(m))).collect())
            }
            WiringError::ScopeViolation { binding, declared, by_closure, module, path } => {
                // The path's steps are printed short by the graph, so its first step is matched
                // against the short name whichever form the binding prints in.
                let short = binding.to_string();
                let name = show(binding);
                let module = show_module(module);
                let head = match (declared, by_closure) {
                    (ScopeKind::Singleton, _) => {
                        format!("scope violation: singleton `{name}` in {module} depends on per-execution data")
                    }
                    (ScopeKind::Auto, false) => format!(
                        "scope violation: `{name}` in {module} is a provider, so a singleton, and depends on per-execution data"
                    ),
                    (ScopeKind::Auto, true) => format!(
                        "scope violation: `{name}` in {module} is a provider declared by closure with no scope, so a singleton, and depends on per-execution data"
                    ),
                    _ => format!("scope violation: `{name}` in {module} depends on per-execution data"),
                };
                let help = match (declared, by_closure) {
                    (_, true) => "help: declare the closure `with(execution) = ..`, or register it with `.execution(..)`".to_owned(),
                    (ScopeKind::Singleton, false) => format!("help: declare {name} #[injectable(execution)], or inject a factory"),
                    _ => "help: declare it #[injectable(execution)]".to_owned(),
                };
                let item = match path.first() {
                    None => help,
                    Some(first) if first.starts_with(&short) => format!("{}\n{help}", path.join(" → ")),
                    Some(_) => format!("{name} → {}\n{help}", path.join(" → ")),
                };
                tree(f, head, vec![item])
            }
            WiringError::HooksOnPerExecution { binding, module } => {
                let binding = show(binding);
                tree(
                    f,
                    format!("lifecycle hooks on `{binding}` in {}, which the scope pass inferred per-execution", show_module(module)),
                    vec![format!(
                        "help: hooks run on singletons only; move them to a singleton, or remove what makes `{binding}` need an execution"
                    )],
                )
            }
            WiringError::ClosureNeedsExecution { closure, path, at } => {
                let mut items = Vec::new();
                if !path.is_empty() {
                    items.push(path.join(" → "));
                }
                if let Some(at) = at {
                    items.push(format!("declared at {}", place(at)));
                }
                items.push(
                    "help: hooks, readiness checks and metadata run where no execution exists; read singletons there, or take `ModuleRef` and open an execution with `execute`"
                        .to_owned(),
                );
                tree(f, format!("{closure} reads per-execution data"), items)
            }
            WiringError::ClosureScopeViolation { closure, transport, role, path, at } => {
                let method = role.replace(' ', "_");
                let mut items = Vec::new();
                if !path.is_empty() {
                    items.push(path.join(" → "));
                }
                items.push(format!("declared at {}", place(at)));
                items.push(format!(
                    "help: build it per call: drop the scope (`with = ..`, `{method}_with`), or declare it `with(execution) = ..` (`{method}_with_in::<PerExecution>`)"
                ));
                tree(
                    f,
                    format!(
                        "scope violation: {closure} ({}), declared by closure as a singleton, depends on per-execution data",
                        show_type(*transport)
                    ),
                    items,
                )
            }
            WiringError::InputNotSeeded { handler, transport, input, seeder, steps } => {
                let input = show(input);
                let transport = show_type(*transport);
                let seeder = show_type(*seeder);
                let route: Vec<String> = std::iter::once(format!("{handler} ({transport})")).chain(steps.iter().cloned()).collect();
                let route = route.join(" → ");
                tree(
                    f,
                    format!("input `{input}` is seeded by {seeder}, read on a path from the {transport} handler {handler}"),
                    vec![route, format!("help: read it as `Option<Dep<{input}>>` where the path is shared across transports")],
                )
            }
            WiringError::BoundWithoutTimer { item, at } => tree(
                f,
                format!("{item} needs a `Timer`, and the app has none"),
                vec![
                    format!("declared at {}", place(at)),
                    "help: set one with `.timer(..)`, or leave the bound at its default or write `.unbounded()`".to_owned(),
                ],
            ),
            WiringError::BackoffWithoutTimer { binding, at } => tree(
                f,
                format!("readiness `.backoff` of `{binding}` waits between attempts on a `Timer`, and the app has none"),
                vec![format!("declared at {}", place(at)), "help: set one with `.timer(..)`, or remove the `.backoff(..)`".to_owned()],
            ),
            WiringError::KnobWithoutTimer { knob } => tree(
                f,
                format!("`{knob}` is set on an app with no `Timer`"),
                vec!["help: set one with `.timer(..)`; every timing knob is timed by it".to_owned()],
            ),
            WiringError::ZeroDefault { knob, at } => tree(
                f,
                format!("`{knob}` is zero, which would end every item left at its default before it starts"),
                vec![
                    format!("set at {}", place(at)),
                    "help: write `.unbounded()` on the items for no bound, or give the knob a duration above zero".to_owned(),
                ],
            ),
            WiringError::ZeroBound { item, binding, module, at } => {
                let owner = match binding {
                    Some(binding) => format!("`{}` in {}", show(binding), show_module(module)),
                    None => format!("module {}", show_module(module)),
                };
                tree(
                    f,
                    format!("a zero bound on the {item} of {owner} would end it before it starts"),
                    vec![
                        format!("written at {}", place(at)),
                        "help: write `.unbounded()` for no bound, or give it a duration above zero".to_owned(),
                    ],
                )
            }
            WiringError::NestedKeyed { module, outer, inner } => {
                let outer = show_type(*outer);
                let inner = show_type(*inner);
                tree(
                    f,
                    format!("{} is keyed twice, by `{inner}` and then by `{outer}`", show_module(module)),
                    vec![
                        format!("its identity carries `{outer}`, and its exports leave as `T @ {inner}`"),
                        "help: key the module once, with the one qualifier its importers read".to_owned(),
                    ],
                )
            }
            WiringError::DifferingSettings { module, first, second, settings } => {
                let names: Vec<String> = settings.iter().map(|setting| format!("`{}`", setting.name)).collect();
                let values = |side: usize| {
                    let written: Vec<String> = settings
                        .iter()
                        .map(|setting| match &setting.shown[side] {
                            Some(text) => format!("`{}` = {text}", setting.name),
                            None => format!("`{}` unset", setting.name),
                        })
                        .collect();
                    written.join(", ")
                };
                tree(
                    f,
                    format!("two registrations of {} differ in {}", show_module(module), names.join(", ")),
                    vec![
                        format!("{} with {}", first.line(false, &show_module), values(0)),
                        format!("{} with {}", second.line(true, &show_module), values(1)),
                        "help: an equal identity is one module, registered once; write the same settings at both, or key one with `.keyed::<Q>()` to make it a second instance"
                            .to_owned(),
                    ],
                )
            }
            WiringError::ControllerRead { controller, consumer, module, controller_module } => tree(
                f,
                format!("the controller `{}` in {} is read by {consumer} in {}", show(controller), show_module(controller_module), show_module(module)),
                vec![
                    "a controller is the edge of the application, reached by its transport alone".to_owned(),
                    "help: move the shared logic into a provider both can read".to_owned(),
                ],
            ),
        }
    }
}

/// One entry of the report: a headline, then a tree of details whose last item is usually the
/// help. `WiringErrors` indents it under its `×`.
impl fmt::Display for WiringError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let full = Collisions { types: TypeName::colliding(self.type_names()), modules: colliding_names(self.module_names()) };
        self.render(f, &full)
    }
}

/// One source of an execution input's key, as [`WiringError::InputConflict`] names it. `at` is the
/// call that declared or bound it.
///
/// `Display` writes the line the report prints, as in ``declared by transport `Http` at
/// src/transport.rs:40``; `{:#}` writes a module name with its full path. A transport prints
/// short unless another, different one on the same line prints alike.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum InputOrigin {
    /// The transport's `Transport::inputs`. `name` is the transport's marker type; a report
    /// prints `ulo_http::Http` as `Http`.
    Transport { name: TypeName, at: &'static Location<'static> },
    /// A module's `input::<T>().seeded_by::<Tr>()`. `seeders` holds each `Tr`.
    Module { module: ModuleName, seeders: Vec<TypeName>, at: &'static Location<'static> },
    /// A single binding under the input's key.
    Binding { module: ModuleName, at: &'static Location<'static> },
}

impl InputOrigin {
    fn module(&self) -> Option<&ModuleName> {
        match self {
            InputOrigin::Transport { .. } => None,
            InputOrigin::Module { module, .. } | InputOrigin::Binding { module, .. } => Some(module),
        }
    }

    /// The transports this source names.
    fn type_names(&self) -> Vec<TypeName> {
        match self {
            InputOrigin::Transport { name, .. } => vec![*name],
            InputOrigin::Module { seeders, .. } => seeders.clone(),
            InputOrigin::Binding { .. } => Vec::new(),
        }
    }

    /// The report's line for this source, `module` writing each module name and `ty` each
    /// transport.
    fn line(&self, module: impl Fn(&ModuleName) -> String, ty: impl Fn(TypeName) -> String) -> String {
        match self {
            InputOrigin::Transport { name, at } => format!("declared by transport `{}` at {}", ty(*name), place(at)),
            InputOrigin::Module { module: declared_in, seeders, at } => {
                let noun = if seeders.len() == 1 { "seeder" } else { "seeders" };
                let names: Vec<String> = seeders.iter().map(|&seeder| format!("`{}`", ty(seeder))).collect();
                format!("declared in {} with {noun} {} at {}", module(declared_in), names.join(", "), place(at))
            }
            InputOrigin::Binding { module: bound_in, at } => format!("bound in {} at {}", module(bound_in), place(at)),
        }
    }
}

impl fmt::Display for InputOrigin {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let full = f.alternate();
        let types = TypeName::colliding(self.type_names());
        f.write_str(&self.line(|name| if full { format!("{name:#}") } else { name.to_string() }, |name| name.written(&types)))
    }
}

/// Where a module was registered, as [`WiringError::DifferingSettings`] names each side.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum ModuleSite {
    /// The root module the app was built from.
    Root,
    /// `ModuleDef::import` in `importer`, the call at `at`.
    Import { importer: ModuleName, at: &'static Location<'static> },
    /// `AppHandle::load`, the call at `at`.
    Load { at: &'static Location<'static> },
}

impl ModuleSite {
    fn importer(&self) -> Option<&ModuleName> {
        match self {
            ModuleSite::Import { importer, .. } => Some(importer),
            ModuleSite::Root | ModuleSite::Load { .. } => None,
        }
    }

    /// The report's line for this site; `again` for the later of two registrations.
    fn line(&self, again: bool, module: &impl Fn(&ModuleName) -> String) -> String {
        match (self, again) {
            (ModuleSite::Root, _) => "registered as the root module".to_owned(),
            (ModuleSite::Import { importer, at }, false) => format!("imported by {} at {}", module(importer), place(at)),
            (ModuleSite::Import { importer, at }, true) => format!("imported again by {} at {}", module(importer), place(at)),
            (ModuleSite::Load { at }, false) => format!("loaded by `AppHandle::load` at {}", place(at)),
            (ModuleSite::Load { at }, true) => format!("loaded again by `AppHandle::load` at {}", place(at)),
        }
    }
}

/// One setting two registrations of a module disagree on: its name and each side's value as
/// [`ModuleSettings`](crate::ModuleSettings) wrote it, `None` where that side has no such setting.
///
/// `first` and `second` hold the values unredacted. Its `Debug`, the `WiringError` entry's
/// `Display` and `Debug`, and the report's, print them after the graph's redaction function, so a
/// secret the graph registered is replaced there as in every other error.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq)]
pub struct DifferingSetting {
    pub name: &'static str,
    pub first: Option<String>,
    pub second: Option<String>,
    shown: [Option<String>; 2],
}

impl DifferingSetting {
    pub(crate) fn new(name: &'static str, first: Option<String>, second: Option<String>, secrets: &SecretRegistry) -> Self {
        let shown = [first.as_deref().map(|text| scrub(secrets, text)), second.as_deref().map(|text| scrub(secrets, text))];
        DifferingSetting { name, first, second, shown }
    }
}

impl fmt::Debug for DifferingSetting {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DifferingSetting").field("name", &self.name).field("first", &self.shown[0]).field("second", &self.shown[1]).finish()
    }
}

/// What one report prints with full paths: the types and the modules whose short form a different
/// type, or a different module, in the same report shares.
struct Collisions {
    types: HashSet<TypeName>,
    modules: HashSet<ModuleName>,
}

/// An entry rendered against the whole report's collisions.
struct Rendered<'a> {
    error: &'a WiringError,
    full: &'a Collisions,
}

impl fmt::Display for Rendered<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.error.render(f, self.full)
    }
}

/// The help for a missing key that the app's builder sets rather than a module: the core's own
/// module binds `dyn Runtime` from `.runtime(..)`, and `dyn Timer` from either call.
fn builder_help(key: Key) -> Option<&'static str> {
    if key == Key::of::<dyn Runtime, ()>() {
        Some("help: set one on the app with `.runtime(..)`, which sets its timer too")
    } else if key == Key::of::<dyn Timer, ()>() {
        Some("help: set one on the app with `.timer(..)`, or with `.runtime(..)`, which sets both")
    } else {
        None
    }
}

/// Writes `head`, then each item on its own line under `├─`, the last under `└─`. A line break
/// inside an item continues it under the same branch.
fn tree(f: &mut fmt::Formatter<'_>, head: String, items: Vec<String>) -> fmt::Result {
    f.write_str(&head)?;
    let last = items.len().saturating_sub(1);
    for (i, item) in items.iter().enumerate() {
        let (branch, continued) = if i == last { ("└─", "   ") } else { ("├─", "│  ") };
        let mut lines = item.lines();
        if let Some(first) = lines.next() {
            write!(f, "\n{branch} {first}")?;
        }
        for line in lines {
            write!(f, "\n{continued}{line}")?;
        }
    }
    Ok(())
}

/// `A → B → C → A`: the steps with the first repeated at the end unless it already is.
fn closed_loop(mut steps: Vec<String>) -> String {
    let closed = steps.len() > 1 && steps.first() == steps.last();
    if !closed {
        if let Some(first) = steps.first().cloned() {
            steps.push(first);
        }
    }
    steps.join(" → ")
}

fn place(at: &Location<'_>) -> String {
    format!("{}:{}", at.file(), at.line())
}

fn kind_text(kind: BindingKind) -> &'static str {
    match kind {
        BindingKind::Single => "a single binding",
        BindingKind::Collection => "a collection",
    }
}