Repository: rust-analyzer/rust-analyzer
Pull request #8055 (2021-03-16 15:40:16)

Implement HirDisplay for some more types
bors r+


Patch:
diff --git a/crates/base_db/src/fixture.rs b/crates/base_db/src/fixture.rs
index cad6866aa3..5c9824814e 100644
--- a/crates/base_db/src/fixture.rs
+++ b/crates/base_db/src/fixture.rs
@@ -57,7 +57,7 @@
 //! fn insert_source_code_here() {}
 //! "
 //! ```
-use std::{mem, str::FromStr, sync::Arc};
+use std::{str::FromStr, sync::Arc};
 
 use cfg::CfgOptions;
 use rustc_hash::FxHashMap;
@@ -148,7 +148,6 @@ impl ChangeFixture {
         let mut file_set = FileSet::default();
         let source_root_prefix = "/".to_string();
         let mut file_id = FileId(0);
-        let mut roots = Vec::new();
 
         let mut file_position = None;
 
@@ -169,10 +168,6 @@ impl ChangeFixture {
             let meta = FileMeta::from(entry);
             assert!(meta.path.starts_with(&source_root_prefix));
 
-            if meta.introduce_new_source_root {
-                roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
-            }
-
             if let Some(krate) = meta.krate {
                 let crate_name = CrateName::normalize_dashes(&krate);
                 let crate_id = crate_graph.add_crate_root(
@@ -220,8 +215,7 @@ impl ChangeFixture {
             }
         }
 
-        roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
-        change.set_roots(roots);
+        change.set_roots(vec![SourceRoot::new_local(file_set)]);
         change.set_crate_graph(crate_graph);
 
         ChangeFixture { file_position, files, change }
@@ -235,7 +229,6 @@ struct FileMeta {
     cfg: CfgOptions,
     edition: Edition,
     env: Env,
-    introduce_new_source_root: bool,
 }
 
 impl From<Fixture> for FileMeta {
@@ -254,7 +247,6 @@ impl From<Fixture> for FileMeta {
                 .as_ref()
                 .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()),
             env: f.env.into_iter().collect(),
-            introduce_new_source_root: f.introduce_new_source_root,
         }
     }
 }
diff --git a/crates/base_db/src/input.rs b/crates/base_db/src/input.rs
index d0def21815..b5f7e4200a 100644
--- a/crates/base_db/src/input.rs
+++ b/crates/base_db/src/input.rs
@@ -274,33 +274,6 @@ impl CrateGraph {
         deps.into_iter()
     }
 
-    /// Returns an iterator over all transitive reverse dependencies of the given crate.
-    pub fn transitive_reverse_dependencies(
-        &self,
-        of: CrateId,
-    ) -> impl Iterator<Item = CrateId> + '_ {
-        let mut worklist = vec![of];
-        let mut rev_deps = FxHashSet::default();
-        let mut inverted_graph = FxHashMap::<_, Vec<_>>::default();
-        self.arena.iter().for_each(|(&krate, data)| {
-            data.dependencies
-                .iter()
-                .for_each(|dep| inverted_graph.entry(dep.crate_id).or_default().push(krate))
-        });
-
-        while let Some(krate) = worklist.pop() {
-            if let Some(krate_rev_deps) = inverted_graph.get(&krate) {
-                krate_rev_deps
-                    .iter()
-                    .copied()
-                    .filter(|&rev_dep| rev_deps.insert(rev_dep))
-                    .for_each(|rev_dep| worklist.push(rev_dep));
-            }
-        }
-
-        rev_deps.into_iter()
-    }
-
     /// Returns all crates in the graph, sorted in topological order (ie. dependencies of a crate
     /// come before the crate itself).
     pub fn crates_in_topological_order(&self) -> Vec<CrateId> {
diff --git a/crates/hir/src/display.rs b/crates/hir/src/display.rs
index 44cdcc2963..81f0e04e55 100644
--- a/crates/hir/src/display.rs
+++ b/crates/hir/src/display.rs
@@ -12,8 +12,8 @@ use hir_ty::display::{
 use syntax::ast::{self, NameOwner};
 
 use crate::{
-    Const, ConstParam, Enum, Field, Function, HasVisibility, Module, Static, Struct, Substs, Trait,
-    Type, TypeAlias, TypeParam, Union, Variant,
+    Adt, Const, ConstParam, Enum, Field, Function, GenericParam, HasVisibility, LifetimeParam,
+    Module, Static, Struct, Substs, Trait, Type, TypeAlias, TypeParam, Union, Variant,
 };
 
 impl HirDisplay for Function {
@@ -120,6 +120,16 @@ impl HirDisplay for Function {
     }
 }
 
+impl HirDisplay for Adt {
+    fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
+        match self {
+            Adt::Struct(it) => it.hir_fmt(f),
+            Adt::Union(it) => it.hir_fmt(f),
+            Adt::Enum(it) => it.hir_fmt(f),
+        }
+    }
+}
+
 impl HirDisplay for Struct {
     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
         write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
@@ -211,6 +221,16 @@ impl HirDisplay for Type {
     }
 }
 
+impl HirDisplay for GenericParam {
+    fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
+        match self {
+            GenericParam::TypeParam(it) => it.hir_fmt(f),
+            GenericParam::LifetimeParam(it) => it.hir_fmt(f),
+            GenericParam::ConstParam(it) => it.hir_fmt(f),
+        }
+    }
+}
+
 impl HirDisplay for TypeParam {
     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
         write!(f, "{}", self.name(f.db))?;
@@ -224,6 +244,12 @@ impl HirDisplay for TypeParam {
     }
 }
 
+impl HirDisplay for LifetimeParam {
+    fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
+        write!(f, "{}", self.name(f.db))
+    }
+}
+
 impl HirDisplay for ConstParam {
     fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
         write!(f, "const {}: ", self.name(f.db))?;
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs
index ad79a79f8c..f0bc2c7b95 100644
--- a/crates/hir/src/lib.rs
+++ b/crates/hir/src/lib.rs
@@ -60,7 +60,6 @@ use hir_ty::{
     InEnvironment, Interner, Obligation, ProjectionPredicate, ProjectionTy, Scalar, Substs, Ty,
     TyDefId, TyKind, TyVariableKind,
 };
-use itertools::Itertools;
 use rustc_hash::FxHashSet;
 use stdx::{format_to, impl_from};
 use syntax::{
@@ -142,6 +141,7 @@ impl Crate {
             .collect()
     }
 
+    // FIXME: add `transitive_reverse_dependencies`.
     pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
         let crate_graph = db.crate_graph();
         crate_graph
@@ -153,14 +153,6 @@ impl Crate {
             .collect()
     }
 
-    pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
-        db.crate_graph()
-            .transitive_reverse_dependencies(self.id)
-            .into_iter()
-            .map(|id| Crate { id })
-            .collect()
-    }
-
     pub fn root_module(self, db: &dyn HirDatabase) -> Module {
         let def_map = db.crate_def_map(self.id);
         Module { id: def_map.module_id(def_map.root()) }
@@ -1549,17 +1541,11 @@ impl Impl {
         };
 
         let mut all = Vec::new();
-        def_crates.iter().for_each(|&id| {
+        def_crates.into_iter().for_each(|id| {
             all.extend(db.inherent_impls_in_crate(id).all_impls().map(Self::from).filter(filter))
         });
         let fp = TyFingerprint::for_impl(&ty.value);
-        for id in def_crates
-            .iter()
-            .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
-            .map(|Crate { id }| id)
-            .chain(def_crates.iter().copied())
-            .unique()
-        {
+        for id in db.crate_graph().iter() {
             match fp {
                 Some(fp) => all.extend(
                     db.trait_impls_in_crate(id).for_self_ty(fp).map(Self::from).filter(filter),
@@ -1574,8 +1560,7 @@ impl Impl {
     pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
         let krate = trait_.module(db).krate();
         let mut all = Vec::new();
-        for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter().chain(Some(krate))
-        {
+        for Crate { id } in krate.reverse_dependencies(db).into_iter().chain(Some(krate)) {
             let impls = db.trait_impls_in_crate(id);
             all.extend(impls.for_trait(trait_.id).map(Self::from))
         }
diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs
index 8d45b48750..3250146221 100644
--- a/crates/ide/src/hover.rs
+++ b/crates/ide/src/hover.rs
@@ -1,6 +1,6 @@
 use either::Either;
 use hir::{
-    Adt, AsAssocItem, AssocItemContainer, GenericParam, HasAttrs, HasSource, HirDisplay, Module,
+    AsAssocItem, AssocItemContainer, GenericParam, HasAttrs, HasSource, HirDisplay, Module,
     ModuleDef, Semantics,
 };
 use ide_db::{
@@ -339,9 +339,7 @@ fn hover_for_definition(
         Definition::ModuleDef(it) => match it {
             ModuleDef::Module(it) => from_hir_fmt(db, it, mod_path),
             ModuleDef::Function(it) => from_hir_fmt(db, it, mod_path),
-            ModuleDef::Adt(Adt::Struct(it)) => from_hir_fmt(db, it, mod_path),
-            ModuleDef::Adt(Adt::Union(it)) => from_hir_fmt(db, it, mod_path),
-            ModuleDef::Adt(Adt::Enum(it)) => from_hir_fmt(db, it, mod_path),
+            ModuleDef::Adt(it) => from_hir_fmt(db, it, mod_path),
             ModuleDef::Variant(it) => from_hir_fmt(db, it, mod_path),
             ModuleDef::Const(it) => from_hir_fmt(db, it, mod_path),
             ModuleDef::Static(it) => from_hir_fmt(db, it, mod_path),
@@ -353,18 +351,10 @@ fn hover_for_definition(
         },
         Definition::Local(it) => hover_for_local(it, db),
         Definition::SelfType(impl_def) => {
-            impl_def.target_ty(db).as_adt().and_then(|adt| match adt {
-                Adt::Struct(it) => from_hir_fmt(db, it, mod_path),
-                Adt::Union(it) => from_hir_fmt(db, it, mod_path),
-                Adt::Enum(it) => from_hir_fmt(db, it, mod_path),
-            })
+            impl_def.target_ty(db).as_adt().and_then(|adt| from_hir_fmt(db, adt, mod_path))
         }
+        Definition::GenericParam(it) => from_hir_fmt(db, it, None),
         Definition::Label(it) => Some(Markup::fenced_block(&it.name(db))),
-        Definition::GenericParam(it) => match it {
-            GenericParam::TypeParam(it) => Some(Markup::fenced_block(&it.display(db))),
-            GenericParam::LifetimeParam(it) => Some(Markup::fenced_block(&it.name(db))),
-            GenericParam::ConstParam(it) => Some(Markup::fenced_block(&it.display(db))),
-        },
     };
 
     fn from_hir_fmt<D>(db: &RootDatabase, def: D, mod_path: Option<String>) -> Option<Markup>
diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs
index 3796745306..e8a5666bc1 100644
--- a/crates/ide/src/references.rs
+++ b/crates/ide/src/references.rs
@@ -1271,27 +1271,4 @@ fn foo(_: bool) -> bo$0ol { true }
             "#]],
         );
     }
-
-    #[test]
-    fn test_transitive() {
-        check(
-            r#"
-//- /level3.rs new_source_root: crate:level3
-pub struct Fo$0o;
-//- /level2.rs new_source_root: crate:level2 deps:level3
-pub use level3::Foo;
-//- /level1.rs new_source_root: crate:level1 deps:level2
-pub use level2::Foo;
-//- /level0.rs new_source_root: crate:level0 deps:level1
-pub use level1::Foo;
-"#,
-            expect![[r#"
-                Foo Struct FileId(0) 0..15 11..14
-
-                FileId(1) 16..19
-                FileId(2) 16..19
-                FileId(3) 16..19
-            "#]],
-        );
-    }
 }
diff --git a/crates/ide_db/src/search.rs b/crates/ide_db/src/search.rs
index f56221a6c6..d00a8b6e70 100644
--- a/crates/ide_db/src/search.rs
+++ b/crates/ide_db/src/search.rs
@@ -260,7 +260,7 @@ impl Definition {
             let mut res = source_root.iter().map(|id| (id, None)).collect::<FxHashMap<_, _>>();
 
             let krate = module.krate();
-            for rev_dep in krate.transitive_reverse_dependencies(db) {
+            for rev_dep in krate.reverse_dependencies(db) {
                 let root_file = rev_dep.root_file(db);
                 let source_root_id = db.file_source_root(root_file);
                 let source_root = db.source_root(source_root_id);


Test patch:
diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs
index 6bc824e943..e3f57f3b2a 100644
--- a/crates/test_utils/src/fixture.rs
+++ b/crates/test_utils/src/fixture.rs
@@ -14,7 +14,6 @@ pub struct Fixture {
     pub cfg_key_values: Vec<(String, String)>,
     pub edition: Option<String>,
     pub env: FxHashMap<String, String>,
-    pub introduce_new_source_root: bool,
 }
 
 impl Fixture {
@@ -71,7 +70,6 @@ impl Fixture {
         let mut cfg_atoms = Vec::new();
         let mut cfg_key_values = Vec::new();
         let mut env = FxHashMap::default();
-        let mut introduce_new_source_root = false;
         for component in components[1..].iter() {
             let (key, value) = split_once(component, ':').unwrap();
             match key {
@@ -93,22 +91,11 @@ impl Fixture {
                         }
                     }
                 }
-                "new_source_root" => introduce_new_source_root = true,
                 _ => panic!("bad component: {:?}", component),
             }
         }
 
-        Fixture {
-            path,
-            text: String::new(),
-            krate,
-            deps,
-            cfg_atoms,
-            cfg_key_values,
-            edition,
-            env,
-            introduce_new_source_root,
-        }
+        Fixture { path, text: String::new(), krate, deps, cfg_atoms, cfg_key_values, edition, env }
     }
 }