cargo-modules 0.12.0

A cargo plugin for showing a tree-like overview of a crate's modules.
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use std::collections::{HashMap, HashSet};

use hir::HirDisplay;
use log::trace;
use petgraph::graph::{EdgeIndex, NodeIndex};
use ra_ap_hir::{self as hir};
use ra_ap_hir_def::{self as hir_def};
use ra_ap_hir_ty::{self as hir_ty, db::HirDatabase as _, TyExt as _};
use ra_ap_ide_db::{self as ide_db};
use ra_ap_vfs::{self as vfs};
use scopeguard::defer;

use crate::{
    analyzer,
    graph::{
        edge::{Edge, EdgeKind},
        node::Node,
        Graph,
    },
    item::Item,
};

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Options {}

#[derive(Debug, Hash, Eq, PartialEq)]
struct Dependency {
    source_idx: NodeIndex,
    target_hir: hir::ModuleDef,
}

#[derive(Debug)]
pub struct Builder<'a> {
    #[allow(dead_code)]
    options: Options,
    db: &'a ide_db::RootDatabase,
    vfs: &'a vfs::Vfs,
    krate: hir::Crate,
    graph: Graph,
    nodes: HashMap<hir::ModuleDef, NodeIndex>,
    edges: HashMap<(NodeIndex, EdgeKind, NodeIndex), EdgeIndex>,
}

impl<'a> Builder<'a> {
    pub fn new(
        options: Options,
        db: &'a ide_db::RootDatabase,
        vfs: &'a vfs::Vfs,
        krate: hir::Crate,
    ) -> Self {
        let graph = Graph::default();
        let nodes = HashMap::default();
        let edges = HashMap::default();

        Self {
            options,
            db,
            vfs,
            krate,
            graph,
            nodes,
            edges,
        }
    }

    pub fn build(mut self) -> anyhow::Result<(Graph, NodeIndex)> {
        trace!("Scanning project...");

        defer! {
            trace!("Finished canning project");
        }

        let node_idx = self
            .process_crate(self.krate)
            .expect("graph node for crate root module");

        Ok((self.graph, node_idx))
    }

    fn process_crate(&mut self, crate_hir: hir::Crate) -> Option<NodeIndex> {
        let path = vec![analyzer::crate_name(crate_hir, self.db)];

        trace!("Processing crate {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing crate {path}", path = path.join("::"));
        }

        let module = crate_hir.root_module();

        let node_idx = self.process_moduledef(module.into(), &[]);

        for impl_hir in hir::Impl::all_in_crate(self.db, crate_hir) {
            let impl_ty = impl_hir.self_ty(self.db);

            let impl_ty_hir = if let Some(adt_hir) = impl_ty.as_adt() {
                Some(hir::ModuleDef::Adt(adt_hir))
            } else {
                impl_ty.as_builtin().map(hir::ModuleDef::BuiltinType)
            };

            let Some(impl_ty_hir) = impl_ty_hir else {
                continue;
            };

            let impl_ty_idx = *self.nodes.get(&impl_ty_hir).expect("impl type node");
            let impl_ty_path = self.graph[impl_ty_idx].item.path.clone();

            for impl_item_idx in self.process_impl(impl_hir, &impl_ty_path) {
                let edge = Edge {
                    kind: EdgeKind::Owns,
                };

                self.add_edge(impl_ty_idx, impl_item_idx, edge);
            }
        }

        node_idx
    }

    fn process_impl(&mut self, impl_hir: hir::Impl, owner_path: &[String]) -> Vec<NodeIndex> {
        let trait_name = impl_hir
            .trait_(self.db)
            .map(|trait_hir| trait_hir.name(self.db).display(self.db).to_string());

        if let Some(trait_name) = trait_name.as_ref() {
            trace!(
                "Processing impl {trait_name} for {path}...",
                path = owner_path.join("::")
            );
        } else {
            trace!("Processing impl {path}...", path = owner_path.join("::"));
        }

        defer! {
            if let Some(trait_name) = trait_name.as_ref() {
                trace!("Finished processing impl {trait_name} for {path}", path = owner_path.join("::"));
            } else {
                trace!("Finished processing impl {path}", path = owner_path.join("::"));
            }
        }

        impl_hir
            .items(self.db)
            .into_iter()
            .filter_map(|item| {
                let mut dependencies: HashSet<_> = HashSet::default();

                let mut push_dependencies = |moduledef_hir| {
                    dependencies.insert(moduledef_hir);
                };

                let item_idx = match item {
                    hir::AssocItem::Function(function_hir) => {
                        self.process_function(function_hir, owner_path, &mut push_dependencies)
                    }
                    hir::AssocItem::Const(const_hir) => {
                        self.process_const(const_hir, owner_path, &mut push_dependencies)
                    }
                    hir::AssocItem::TypeAlias(type_alias_hir) => {
                        self.process_type_alias(type_alias_hir, owner_path, &mut push_dependencies)
                    }
                };

                if let Some(item_idx) = item_idx {
                    self.add_dependencies(item_idx, dependencies.clone());
                }

                item_idx
            })
            .collect()
    }

    fn process_moduledef(
        &mut self,
        moduledef_hir: hir::ModuleDef,
        owner_path: &[String],
    ) -> Option<NodeIndex> {
        trace!("Processing moduledef...");

        defer! {
            trace!("Finished processing moduledef");
        }

        let mut dependencies: HashSet<_> = HashSet::default();

        let mut push_dependencies = |moduledef_hir| {
            dependencies.insert(moduledef_hir);
        };

        let node_idx = match moduledef_hir {
            hir::ModuleDef::Module(module_hir) => {
                self.process_module(module_hir, owner_path, &mut push_dependencies)
            }
            hir::ModuleDef::Function(function_hir) => {
                self.process_function(function_hir, owner_path, &mut push_dependencies)
            }
            hir::ModuleDef::Adt(adt_hir) => {
                self.process_adt(adt_hir, owner_path, &mut push_dependencies)
            }
            hir::ModuleDef::Variant(variant_hir) => {
                self.process_variant(variant_hir, owner_path, &mut push_dependencies)
            }
            hir::ModuleDef::Const(const_hir) => {
                self.process_const(const_hir, owner_path, &mut push_dependencies)
            }
            hir::ModuleDef::Static(static_hir) => {
                self.process_static(static_hir, owner_path, &mut push_dependencies)
            }
            hir::ModuleDef::Trait(trait_hir) => {
                self.process_trait(trait_hir, owner_path, &mut push_dependencies)
            }
            hir::ModuleDef::TraitAlias(trait_alias_hir) => {
                self.process_trait_alias(trait_alias_hir, owner_path, &mut push_dependencies)
            }
            hir::ModuleDef::TypeAlias(type_alias_hir) => {
                self.process_type_alias(type_alias_hir, owner_path, &mut push_dependencies)
            }
            hir::ModuleDef::BuiltinType(builtin_type_hir) => {
                self.process_builtin_type(builtin_type_hir, owner_path, &mut push_dependencies)
            }
            hir::ModuleDef::Macro(macro_hir) => {
                self.process_macro(macro_hir, owner_path, &mut push_dependencies)
            }
        };

        if let Some(node_idx) = node_idx.as_ref() {
            self.add_dependencies(*node_idx, dependencies.clone());
        }

        node_idx
    }

    fn process_module(
        &mut self,
        module_hir: hir::Module,
        owner_path: &[String],
        dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, module_hir, self.db);

        trace!("Processing module {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing module {path}", path = path.join("::"));
        }

        let node_idx = self.add_node_if_necessary(module_hir.into(), path.clone());

        if let Some(node_idx) = node_idx {
            // Process sub-items:
            for declaration in module_hir.declarations(self.db) {
                let Some(declaration_idx) = self.process_moduledef(declaration, &path) else {
                    continue;
                };

                let edge = Edge {
                    kind: EdgeKind::Owns,
                };

                self.add_edge(node_idx, declaration_idx, edge);
            }
        }

        for (_name, scope_hir) in module_hir.scope(self.db, None) {
            let hir::ScopeDef::ModuleDef(scope_module_hir) = scope_hir else {
                // Skip everything but module-defs:
                continue;
            };

            // Check if definition is a child of `module`:
            if scope_module_hir.module(self.db) == Some(module_hir) {
                // Is a child, omit it:
                continue;
            }

            dependencies_callback(scope_module_hir);
        }

        node_idx
    }

    fn process_function(
        &mut self,
        function_hir: hir::Function,
        owner_path: &[String],
        dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, function_hir, self.db);

        trace!("Processing function {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing function {path}", path = path.join("::"));
        }

        let Some(node_idx) =
            self.add_node_if_necessary(hir::ModuleDef::Function(function_hir), path.clone())
        else {
            return None;
        };

        for param in function_hir.params_without_self(self.db) {
            Self::walk_and_push_type(
                param.ty().strip_references(),
                self.db,
                dependencies_callback,
            );
        }

        for param in function_hir.assoc_fn_params(self.db) {
            Self::walk_and_push_type(
                param.ty().strip_references(),
                self.db,
                dependencies_callback,
            );
        }

        let return_type = function_hir.ret_type(self.db);
        Self::walk_and_push_type(
            return_type.strip_references(),
            self.db,
            dependencies_callback,
        );

        let def_with_body = hir::DefWithBody::from(function_hir);
        let def_with_body_id: hir_def::DefWithBodyId = def_with_body.into();
        let inference_result = self.db.infer(def_with_body_id);

        for (_id, ty) in inference_result.type_of_binding.iter() {
            Self::walk_and_push_ty(ty.clone(), self.db, dependencies_callback);
        }

        for (_id, ty) in inference_result.type_of_expr.iter() {
            Self::walk_and_push_ty(ty.clone(), self.db, dependencies_callback);
        }

        for (_id, ty) in inference_result.type_of_for_iterator.iter() {
            Self::walk_and_push_ty(ty.clone(), self.db, dependencies_callback);
        }

        for (_id, ty) in inference_result.type_of_pat.iter() {
            Self::walk_and_push_ty(ty.clone(), self.db, dependencies_callback);
        }

        for (_id, ty) in inference_result.type_of_rpit.iter() {
            Self::walk_and_push_ty(ty.clone(), self.db, dependencies_callback);
        }

        Some(node_idx)
    }

    fn process_adt(
        &mut self,
        adt_hir: hir::Adt,
        owner_path: &[String],
        dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        trace!("Processing adt...");

        defer! {
            trace!("Finished processing adt");
        }

        match adt_hir {
            hir::Adt::Struct(struct_hir) => {
                self.process_struct(struct_hir, owner_path, dependencies_callback)
            }
            hir::Adt::Enum(enum_hir) => {
                self.process_enum(enum_hir, owner_path, dependencies_callback)
            }
            hir::Adt::Union(union_hir) => {
                self.process_union(union_hir, owner_path, dependencies_callback)
            }
        }
    }

    fn process_struct(
        &mut self,
        struct_hir: hir::Struct,
        owner_path: &[String],
        dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, struct_hir, self.db);

        trace!("Processing struct {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing struct {path}", path = path.join("::"));
        }

        let node_idx = self.add_node_if_necessary(
            hir::ModuleDef::Adt(hir::Adt::Struct(struct_hir)),
            path.clone(),
        );

        for field_hir in struct_hir.fields(self.db) {
            Self::walk_and_push_type(
                field_hir.ty(self.db).strip_references(),
                self.db,
                dependencies_callback,
            );
        }

        node_idx
    }

    fn process_enum(
        &mut self,
        enum_hir: hir::Enum,
        owner_path: &[String],
        dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, enum_hir, self.db);

        trace!("Processing enum {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing enum {path}", path = path.join("::"));
        }

        let node_idx =
            self.add_node_if_necessary(hir::ModuleDef::Adt(hir::Adt::Enum(enum_hir)), path.clone());

        for variant_hir in enum_hir.variants(self.db) {
            for field_hir in variant_hir.fields(self.db) {
                Self::walk_and_push_type(
                    field_hir.ty(self.db).strip_references(),
                    self.db,
                    dependencies_callback,
                );
            }
        }

        node_idx
    }

    fn process_union(
        &mut self,
        union_hir: hir::Union,
        owner_path: &[String],
        dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, union_hir, self.db);

        trace!("Processing union {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing union {path}", path = path.join("::"));
        }

        let node_idx = self.add_node_if_necessary(
            hir::ModuleDef::Adt(hir::Adt::Union(union_hir)),
            path.clone(),
        );

        for field_hir in union_hir.fields(self.db) {
            Self::walk_and_push_type(
                field_hir.ty(self.db).strip_references(),
                self.db,
                dependencies_callback,
            );
        }

        node_idx
    }

    fn process_variant(
        &mut self,
        variant_hir: hir::Variant,
        owner_path: &[String],
        dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, variant_hir, self.db);

        trace!("Processing variant {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing variant {path}", path = path.join("::"));
        }

        for field_hir in variant_hir.fields(self.db) {
            Self::walk_and_push_type(field_hir.ty(self.db), self.db, dependencies_callback);
        }

        None
    }

    fn process_const(
        &mut self,
        const_hir: hir::Const,
        owner_path: &[String],
        dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, const_hir, self.db);

        trace!("Processing const {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing const {path}", path = path.join("::"));
        }

        Self::walk_and_push_type(const_hir.ty(self.db), self.db, dependencies_callback);

        None
    }

    fn process_static(
        &mut self,
        static_hir: hir::Static,
        owner_path: &[String],
        dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, static_hir, self.db);

        trace!("Processing static {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing static {path}", path = path.join("::"));
        }

        Self::walk_and_push_type(static_hir.ty(self.db), self.db, dependencies_callback);

        None
    }

    fn process_trait(
        &mut self,
        trait_hir: hir::Trait,
        owner_path: &[String],
        _dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, trait_hir, self.db);

        trace!("Processing trait {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing trait {path}", path = path.join("::"));
        }

        let node_idx = self.add_node_if_necessary(hir::ModuleDef::Trait(trait_hir), path.clone());

        // TODO: walk types?

        #[allow(clippy::let_and_return)]
        node_idx
    }

    fn process_trait_alias(
        &mut self,
        trait_alias_hir: hir::TraitAlias,
        owner_path: &[String],
        _dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, trait_alias_hir, self.db);

        trace!("Processing trait alias {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing trait alias {path}", path = path.join("::"));
        }

        let node_idx =
            self.add_node_if_necessary(hir::ModuleDef::TraitAlias(trait_alias_hir), path.clone());

        // TODO: walk types?

        #[allow(clippy::let_and_return)]
        node_idx
    }

    fn process_type_alias(
        &mut self,
        type_alias_hir: hir::TypeAlias,
        owner_path: &[String],
        dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, type_alias_hir, self.db);

        trace!("Processing type alias {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing type alias {path}", path = path.join("::"));
        }

        let node_idx =
            self.add_node_if_necessary(hir::ModuleDef::TypeAlias(type_alias_hir), path.clone());

        Self::walk_and_push_type(type_alias_hir.ty(self.db), self.db, dependencies_callback);

        node_idx
    }

    fn process_builtin_type(
        &mut self,
        builtin_type_hir: hir::BuiltinType,
        owner_path: &[String],
        dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, builtin_type_hir, self.db);

        trace!("Processing builtin type {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing builtin type {path}", path = path.join("::"));
        }

        let node_idx =
            self.add_node_if_necessary(hir::ModuleDef::BuiltinType(builtin_type_hir), path.clone());

        Self::walk_and_push_type(builtin_type_hir.ty(self.db), self.db, dependencies_callback);

        node_idx
    }

    fn process_macro(
        &mut self,
        macro_hir: hir::Macro,
        owner_path: &[String],
        _dependencies_callback: &mut dyn FnMut(hir::ModuleDef),
    ) -> Option<NodeIndex> {
        let path = analyzer::path_appending(owner_path, macro_hir, self.db);

        trace!("Processing macro {path}...", path = path.join("::"));

        defer! {
            trace!("Finished processing macro {path}", path = path.join("::"));
        }

        // TODO: should the macro be walked, somehow?

        None
    }

    pub(super) fn walk_and_push_type(
        ty: hir::Type,
        db: &ide_db::RootDatabase,
        visit: &mut dyn FnMut(hir::ModuleDef),
    ) {
        trace!("Walking type {ty}...", ty = ty.display(db));

        defer! {
            trace!("Finished walking type {ty}", ty = ty.display(db));
        }

        ty.walk(db, |ty| {
            if let Some(adt) = ty.as_adt() {
                visit(adt.into());
            } else if let Some(trait_) = ty.as_dyn_trait() {
                visit(trait_.into());
            } else if let Some(traits) = ty.as_impl_traits(db) {
                traits.for_each(|it| visit(it.into()));
            } else if let Some(trait_) = ty.as_associated_type_parent_trait(db) {
                visit(trait_.into());
            }
        });
    }

    fn walk_and_push_ty(
        ty: hir_ty::Ty,
        db: &ide_db::RootDatabase,
        visit: &mut dyn FnMut(hir::ModuleDef),
    ) {
        trace!("Walking type {ty}...", ty = ty.display(db));

        defer! {
            trace!("Finished walking type {ty}", ty = ty.display(db));
        }

        use hir_ty::TyKind;

        match ty.kind(hir_ty::Interner) {
            TyKind::Adt(adt_id, substitution) => {
                let adt_hir = hir::Adt::from(adt_id.0);
                visit(hir::ModuleDef::Adt(adt_hir));
                Self::walk_and_push_substitution(substitution.clone(), db, visit);
            }
            TyKind::AssociatedType(assoc_type_id, substitution) => {
                let associated_ty = db.associated_ty_data(*assoc_type_id);
                Self::walk_and_push_binders(
                    associated_ty.binders.binders.iter(hir_ty::Interner),
                    db,
                    visit,
                );
                Self::walk_and_push_substitution(substitution.clone(), db, visit);
            }
            TyKind::Scalar(_scalar) => {
                let builtin = ty.as_builtin().expect("builtin type");
                let builtin_hir = hir::BuiltinType::from(builtin);
                visit(hir::ModuleDef::BuiltinType(builtin_hir));
            }
            TyKind::Tuple(_usize, substitution) => {
                Self::walk_and_push_substitution(substitution.clone(), db, visit);
            }
            TyKind::Array(ty, konst) => {
                Self::walk_and_push_ty(ty.clone(), db, visit);
                Self::walk_and_push_ty(konst.data(hir_ty::Interner).ty.clone(), db, visit);
            }
            TyKind::Slice(ty) => {
                Self::walk_and_push_ty(ty.clone(), db, visit);
            }
            TyKind::Raw(_mutability, ty) => {
                Self::walk_and_push_ty(ty.clone(), db, visit);
            }
            TyKind::Ref(_mutability, _lifetime, ty) => {
                Self::walk_and_push_ty(ty.clone(), db, visit);
            }
            TyKind::OpaqueType(_opaque_ty_id, substitution) => {
                Self::walk_and_push_substitution(substitution.clone(), db, visit);
            }
            TyKind::FnDef(_fn_def_id, substitution) => {
                Self::walk_and_push_substitution(substitution.clone(), db, visit);
            }
            TyKind::Str => {
                let builtin_hir = hir::BuiltinType::str();
                visit(hir::ModuleDef::BuiltinType(builtin_hir));
            }
            TyKind::Never => {
                // nothing to do here
            }
            TyKind::Closure(_closure_id, substitution) => {
                Self::walk_and_push_substitution(substitution.clone(), db, visit);
            }
            TyKind::Generator(_generator_id, substitution) => {
                Self::walk_and_push_substitution(substitution.clone(), db, visit);
            }
            TyKind::GeneratorWitness(_generator_id, substitution) => {
                Self::walk_and_push_substitution(substitution.clone(), db, visit);
            }
            TyKind::Foreign(_foreign_def_id) => {
                // FIXME: Anything to do here?
            }
            TyKind::Error => {
                // nothing to do here
            }
            TyKind::Placeholder(_placeholder_index) => {
                // Do not walk the placeholder or the stack overflows in an infinite loop!
            }
            TyKind::Dyn(dyn_ty) => {
                Self::walk_and_push_binders(
                    dyn_ty.bounds.binders.iter(hir_ty::Interner),
                    db,
                    visit,
                );
            }
            TyKind::Alias(alias_ty) => match alias_ty {
                hir_ty::AliasTy::Projection(projection) => {
                    Self::walk_and_push_substitution(projection.substitution.clone(), db, visit);
                }
                hir_ty::AliasTy::Opaque(opaque) => {
                    Self::walk_and_push_substitution(opaque.substitution.clone(), db, visit);
                }
            },
            TyKind::Function(fn_pointer) => {
                Self::walk_and_push_substitution(fn_pointer.substitution.0.clone(), db, visit);
            }
            TyKind::BoundVar(bound_var) => {
                Self::walk_and_push_ty(bound_var.to_ty(hir_ty::Interner), db, visit);
            }
            TyKind::InferenceVar(inference_var, _ty_variable_kind) => {
                Self::walk_and_push_ty(
                    inference_var.to_ty(hir_ty::Interner, hir_ty::TyVariableKind::General),
                    db,
                    visit,
                );
            }
        }
    }

    fn walk_and_push_substitution(
        substitution: hir_ty::Substitution,
        db: &ide_db::RootDatabase,
        visit: &mut dyn FnMut(hir::ModuleDef),
    ) {
        trace!("Walking substitution {substitution:?}...");

        defer! {
            trace!("Finished walking substitution {substitution:?}");
        }

        for ty in substitution
            .iter(hir_ty::Interner)
            .filter_map(|a| a.ty(hir_ty::Interner))
        {
            Self::walk_and_push_ty(ty.clone(), db, visit);
        }
    }

    fn walk_and_push_binders<'b>(
        binders: impl Iterator<Item = &'b hir_ty::VariableKind>,
        db: &ide_db::RootDatabase,
        visit: &mut dyn FnMut(hir::ModuleDef),
    ) {
        for binder in binders {
            match binder {
                hir_ty::VariableKind::Ty(_ty_variable_kind) => {}
                hir_ty::VariableKind::Lifetime => {}
                hir_ty::VariableKind::Const(ty) => {
                    Self::walk_and_push_ty(ty.clone(), db, visit);
                }
            }
        }
    }

    fn add_dependencies<I>(&mut self, depender_idx: NodeIndex, dependencies: I)
    where
        I: IntoIterator<Item = hir::ModuleDef>,
    {
        trace!("Adding outgoing 'use' edges for node {depender_idx:?}...");

        defer! {
            trace!("Finished adding outgoing 'use' edges for node {depender_idx:?}");
        }

        for dependency_hir in dependencies {
            let path = analyzer::path(dependency_hir, self.db);
            let Some(dependency_hir) = self.add_node_if_necessary(dependency_hir, path) else {
                continue;
            };

            let edge = Edge {
                kind: EdgeKind::Uses,
            };

            self.add_edge(depender_idx, dependency_hir, edge);
        }
    }

    fn add_node_if_necessary(
        &mut self,
        moduledef_hir: hir::ModuleDef,
        path: Vec<String>,
    ) -> Option<NodeIndex> {
        let name = moduledef_hir
            .name(self.db)
            .map(|name| name.display(self.db).to_string());
        trace!(
            "Adding node {name}...",
            name = name.clone().unwrap_or_default()
        );

        defer! {
            trace!("Finished adding node {name}", name = name.clone().unwrap_or_default());
        }

        assert!(!path.iter().any(|segment| { segment.contains(' ') }));

        // Check if we already added an equivalent node:
        match self.nodes.get(&moduledef_hir) {
            Some(node_idx) => {
                // If we did indeed already process it, then retrieve its index:
                Some(*node_idx)
            }
            None => {
                // Otherwise try to add a node:
                let node = Node::new(Item::new(moduledef_hir, path, self.db, self.vfs));
                let node_idx = self.graph.add_node(node);
                self.nodes.insert(moduledef_hir, node_idx);

                Some(node_idx)
            }
        }
    }

    fn add_edge(
        &mut self,
        source_idx: NodeIndex,
        target_idx: NodeIndex,
        edge: Edge,
    ) -> Option<EdgeIndex> {
        if source_idx == target_idx {
            return None;
        }

        let source_path = self.graph[source_idx].item.path.join("::");
        let target_path = self.graph[target_idx].item.path.join("::");
        let edge_name = edge.kind.display_name();

        let edge_id = (source_idx, edge.kind, target_idx);

        trace!("Adding edge: {source_path} --({edge_name})-> {target_path}...");

        defer! {
            trace!("Finished adding edge: {source_path} --({edge_name})-> {target_path}");
        }

        // Check if we already added an equivalent edge:
        let edge_idx = match self.edges.get(&edge_id) {
            Some(edge_idx) => {
                // If we did indeed already process it, then retrieve its index:
                *edge_idx
            }
            None => {
                // Otherwise add an edge:
                let edge_idx = self.graph.add_edge(source_idx, target_idx, edge);
                self.edges.insert(edge_id, edge_idx);

                edge_idx
            }
        };

        Some(edge_idx)
    }
}