]> git.lizzy.rs Git - rust.git/blobdiff - crates/hir_def/src/find_path.rs
Rename `CrateDefMap` to `DefMap`
[rust.git] / crates / hir_def / src / find_path.rs
index ac2c54ac53645e7e84ba2bc2bfaa138e6dc583fc..422a6eeb4a87d63e6b4ef97b4e4626cc775b1717 100644 (file)
@@ -4,6 +4,7 @@
 use rustc_hash::FxHashSet;
 use test_utils::mark;
 
+use crate::nameres::DefMap;
 use crate::{
     db::DefDatabase,
     item_scope::ItemInNs,
 /// *from where* you're referring to the item, hence the `from` parameter.
 pub fn find_path(db: &dyn DefDatabase, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
     let _p = profile::span("find_path");
-    find_path_inner(db, item, from, MAX_PATH_LEN)
+    find_path_inner(db, item, from, MAX_PATH_LEN, None)
+}
+
+pub fn find_path_prefixed(
+    db: &dyn DefDatabase,
+    item: ItemInNs,
+    from: ModuleId,
+    prefix_kind: PrefixKind,
+) -> Option<ModPath> {
+    let _p = profile::span("find_path_prefixed");
+    find_path_inner(db, item, from, MAX_PATH_LEN, Some(prefix_kind))
 }
 
 const MAX_PATH_LEN: usize = 15;
@@ -36,11 +47,61 @@ fn can_start_with_std(&self) -> bool {
     }
 }
 
+fn check_self_super(def_map: &DefMap, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
+    if item == ItemInNs::Types(from.into()) {
+        // - if the item is the module we're in, use `self`
+        Some(ModPath::from_segments(PathKind::Super(0), Vec::new()))
+    } else if let Some(parent_id) = def_map.modules[from.local_id].parent {
+        // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
+        if item
+            == ItemInNs::Types(ModuleDefId::ModuleId(ModuleId {
+                krate: from.krate,
+                local_id: parent_id,
+            }))
+        {
+            Some(ModPath::from_segments(PathKind::Super(1), Vec::new()))
+        } else {
+            None
+        }
+    } else {
+        None
+    }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum PrefixKind {
+    /// Causes paths to always start with either `self`, `super`, `crate` or a crate-name.
+    /// This is the same as plain, just that paths will start with `self` iprepended f the path
+    /// starts with an identifier that is not a crate.
+    BySelf,
+    /// Causes paths to ignore imports in the local module.
+    Plain,
+    /// Causes paths to start with `crate` where applicable, effectively forcing paths to be absolute.
+    ByCrate,
+}
+
+impl PrefixKind {
+    #[inline]
+    fn prefix(self) -> PathKind {
+        match self {
+            PrefixKind::BySelf => PathKind::Super(0),
+            PrefixKind::Plain => PathKind::Plain,
+            PrefixKind::ByCrate => PathKind::Crate,
+        }
+    }
+
+    #[inline]
+    fn is_absolute(&self) -> bool {
+        self == &PrefixKind::ByCrate
+    }
+}
+
 fn find_path_inner(
     db: &dyn DefDatabase,
     item: ItemInNs,
     from: ModuleId,
     max_len: usize,
+    prefixed: Option<PrefixKind>,
 ) -> Option<ModPath> {
     if max_len == 0 {
         return None;
@@ -51,8 +112,11 @@ fn find_path_inner(
     // - if the item is already in scope, return the name under which it is
     let def_map = db.crate_def_map(from.krate);
     let from_scope: &crate::item_scope::ItemScope = &def_map.modules[from.local_id].scope;
-    if let Some((name, _)) = from_scope.name_of(item) {
-        return Some(ModPath::from_segments(PathKind::Plain, vec![name.clone()]));
+    let scope_name =
+        if let Some((name, _)) = from_scope.name_of(item) { Some(name.clone()) } else { None };
+    if prefixed.is_none() && scope_name.is_some() {
+        return scope_name
+            .map(|scope_name| ModPath::from_segments(PathKind::Plain, vec![scope_name]));
     }
 
     // - if the item is the crate root, return `crate`
@@ -65,27 +129,17 @@ fn find_path_inner(
         return Some(ModPath::from_segments(PathKind::Crate, Vec::new()));
     }
 
-    // - if the item is the module we're in, use `self`
-    if item == ItemInNs::Types(from.into()) {
-        return Some(ModPath::from_segments(PathKind::Super(0), Vec::new()));
-    }
-
-    // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
-    if let Some(parent_id) = def_map.modules[from.local_id].parent {
-        if item
-            == ItemInNs::Types(ModuleDefId::ModuleId(ModuleId {
-                krate: from.krate,
-                local_id: parent_id,
-            }))
-        {
-            return Some(ModPath::from_segments(PathKind::Super(1), Vec::new()));
+    if prefixed.filter(PrefixKind::is_absolute).is_none() {
+        if let modpath @ Some(_) = check_self_super(&def_map, item, from) {
+            return modpath;
         }
     }
 
     // - if the item is the crate root of a dependency crate, return the name from the extern prelude
     for (name, def_id) in &def_map.extern_prelude {
         if item == ItemInNs::Types(*def_id) {
-            return Some(ModPath::from_segments(PathKind::Plain, vec![name.clone()]));
+            let name = scope_name.unwrap_or_else(|| name.clone());
+            return Some(ModPath::from_segments(PathKind::Plain, vec![name]));
         }
     }
 
@@ -138,6 +192,7 @@ fn find_path_inner(
                 ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
                 from,
                 best_path_len - 1,
+                prefixed,
             ) {
                 path.segments.push(name);
 
@@ -165,7 +220,9 @@ fn find_path_inner(
                     ItemInNs::Types(ModuleDefId::ModuleId(info.container)),
                     from,
                     best_path_len - 1,
+                    prefixed,
                 )?;
+                mark::hit!(partially_imported);
                 path.segments.push(info.path.segments.last().unwrap().clone());
                 Some(path)
             })
@@ -181,7 +238,13 @@ fn find_path_inner(
         }
     }
 
-    best_path
+    if let Some(prefix) = prefixed.map(PrefixKind::prefix) {
+        best_path.or_else(|| {
+            scope_name.map(|scope_name| ModPath::from_segments(prefix, vec![scope_name]))
+        })
+    } else {
+        best_path
+    }
 }
 
 fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
@@ -304,7 +367,7 @@ mod tests {
     /// `code` needs to contain a cursor marker; checks that `find_path` for the
     /// item the `path` refers to returns that same path when called from the
     /// module the cursor is in.
-    fn check_found_path(ra_fixture: &str, path: &str) {
+    fn check_found_path_(ra_fixture: &str, path: &str, prefix_kind: Option<PrefixKind>) {
         let (db, pos) = TestDB::with_position(ra_fixture);
         let module = db.module_for_file(pos.file_id);
         let parsed_path_file = syntax::SourceFile::parse(&format!("use {};", path));
@@ -324,9 +387,22 @@ fn check_found_path(ra_fixture: &str, path: &str) {
             .take_types()
             .unwrap();
 
-        let found_path = find_path(&db, ItemInNs::Types(resolved), module);
+        let found_path =
+            find_path_inner(&db, ItemInNs::Types(resolved), module, MAX_PATH_LEN, prefix_kind);
+        assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind);
+    }
 
-        assert_eq!(found_path, Some(mod_path));
+    fn check_found_path(
+        ra_fixture: &str,
+        unprefixed: &str,
+        prefixed: &str,
+        absolute: &str,
+        self_prefixed: &str,
+    ) {
+        check_found_path_(ra_fixture, unprefixed, None);
+        check_found_path_(ra_fixture, prefixed, Some(PrefixKind::Plain));
+        check_found_path_(ra_fixture, absolute, Some(PrefixKind::ByCrate));
+        check_found_path_(ra_fixture, self_prefixed, Some(PrefixKind::BySelf));
     }
 
     #[test]
@@ -334,9 +410,9 @@ fn same_module() {
         let code = r#"
             //- /main.rs
             struct S;
-            <|>
+            $0
         "#;
-        check_found_path(code, "S");
+        check_found_path(code, "S", "S", "crate::S", "self::S");
     }
 
     #[test]
@@ -344,9 +420,9 @@ fn enum_variant() {
         let code = r#"
             //- /main.rs
             enum E { A }
-            <|>
+            $0
         "#;
-        check_found_path(code, "E::A");
+        check_found_path(code, "E::A", "E::A", "E::A", "E::A");
     }
 
     #[test]
@@ -356,9 +432,9 @@ fn sub_module() {
             mod foo {
                 pub struct S;
             }
-            <|>
+            $0
         "#;
-        check_found_path(code, "foo::S");
+        check_found_path(code, "foo::S", "foo::S", "crate::foo::S", "self::foo::S");
     }
 
     #[test]
@@ -370,9 +446,9 @@ fn super_module() {
             mod bar;
             struct S;
             //- /foo/bar.rs
-            <|>
+            $0
         "#;
-        check_found_path(code, "super::S");
+        check_found_path(code, "super::S", "super::S", "crate::foo::S", "super::S");
     }
 
     #[test]
@@ -381,9 +457,9 @@ fn self_module() {
             //- /main.rs
             mod foo;
             //- /foo.rs
-            <|>
+            $0
         "#;
-        check_found_path(code, "self");
+        check_found_path(code, "self", "self", "crate::foo", "self");
     }
 
     #[test]
@@ -392,9 +468,9 @@ fn crate_root() {
             //- /main.rs
             mod foo;
             //- /foo.rs
-            <|>
+            $0
         "#;
-        check_found_path(code, "crate");
+        check_found_path(code, "crate", "crate", "crate", "crate");
     }
 
     #[test]
@@ -404,20 +480,20 @@ fn same_crate() {
             mod foo;
             struct S;
             //- /foo.rs
-            <|>
+            $0
         "#;
-        check_found_path(code, "crate::S");
+        check_found_path(code, "crate::S", "crate::S", "crate::S", "crate::S");
     }
 
     #[test]
     fn different_crate() {
         let code = r#"
             //- /main.rs crate:main deps:std
-            <|>
+            $0
             //- /std.rs crate:std
             pub struct S;
         "#;
-        check_found_path(code, "std::S");
+        check_found_path(code, "std::S", "std::S", "std::S", "std::S");
     }
 
     #[test]
@@ -425,23 +501,29 @@ fn different_crate_renamed() {
         let code = r#"
             //- /main.rs crate:main deps:std
             extern crate std as std_renamed;
-            <|>
+            $0
             //- /std.rs crate:std
             pub struct S;
         "#;
-        check_found_path(code, "std_renamed::S");
+        check_found_path(
+            code,
+            "std_renamed::S",
+            "std_renamed::S",
+            "std_renamed::S",
+            "std_renamed::S",
+        );
     }
 
     #[test]
     fn partially_imported() {
+        mark::check!(partially_imported);
         // Tests that short paths are used even for external items, when parts of the path are
         // already in scope.
-        check_found_path(
-            r#"
+        let code = r#"
             //- /main.rs crate:main deps:syntax
 
             use syntax::ast;
-            <|>
+            $0
 
             //- /lib.rs crate:syntax
             pub mod ast {
@@ -449,15 +531,19 @@ pub enum ModuleItem {
                     A, B, C,
                 }
             }
-        "#,
+        "#;
+        check_found_path(
+            code,
             "ast::ModuleItem",
+            "syntax::ast::ModuleItem",
+            "syntax::ast::ModuleItem",
+            "syntax::ast::ModuleItem",
         );
 
-        check_found_path(
-            r#"
+        let code = r#"
             //- /main.rs crate:main deps:syntax
 
-            <|>
+            $0
 
             //- /lib.rs crate:syntax
             pub mod ast {
@@ -465,7 +551,12 @@ pub enum ModuleItem {
                     A, B, C,
                 }
             }
-        "#,
+        "#;
+        check_found_path(
+            code,
+            "syntax::ast::ModuleItem",
+            "syntax::ast::ModuleItem",
+            "syntax::ast::ModuleItem",
             "syntax::ast::ModuleItem",
         );
     }
@@ -478,9 +569,9 @@ mod bar {
                 mod foo { pub(super) struct S; }
                 pub(crate) use foo::*;
             }
-            <|>
+            $0
         "#;
-        check_found_path(code, "bar::S");
+        check_found_path(code, "bar::S", "bar::S", "crate::bar::S", "self::bar::S");
     }
 
     #[test]
@@ -491,42 +582,42 @@ mod bar {
                 mod foo { pub(super) struct S; }
                 pub(crate) use foo::S as U;
             }
-            <|>
+            $0
         "#;
-        check_found_path(code, "bar::U");
+        check_found_path(code, "bar::U", "bar::U", "crate::bar::U", "self::bar::U");
     }
 
     #[test]
     fn different_crate_reexport() {
         let code = r#"
             //- /main.rs crate:main deps:std
-            <|>
+            $0
             //- /std.rs crate:std deps:core
             pub use core::S;
             //- /core.rs crate:core
             pub struct S;
         "#;
-        check_found_path(code, "std::S");
+        check_found_path(code, "std::S", "std::S", "std::S", "std::S");
     }
 
     #[test]
     fn prelude() {
         let code = r#"
             //- /main.rs crate:main deps:std
-            <|>
+            $0
             //- /std.rs crate:std
             pub mod prelude { pub struct S; }
             #[prelude_import]
             pub use prelude::*;
         "#;
-        check_found_path(code, "S");
+        check_found_path(code, "S", "S", "S", "S");
     }
 
     #[test]
     fn enum_variant_from_prelude() {
         let code = r#"
             //- /main.rs crate:main deps:std
-            <|>
+            $0
             //- /std.rs crate:std
             pub mod prelude {
                 pub enum Option<T> { Some(T), None }
@@ -535,8 +626,8 @@ pub enum Option<T> { Some(T), None }
             #[prelude_import]
             pub use prelude::*;
         "#;
-        check_found_path(code, "None");
-        check_found_path(code, "Some");
+        check_found_path(code, "None", "None", "None", "None");
+        check_found_path(code, "Some", "Some", "Some", "Some");
     }
 
     #[test]
@@ -546,13 +637,13 @@ fn shortest_path() {
             pub mod foo;
             pub mod baz;
             struct S;
-            <|>
+            $0
             //- /foo.rs
             pub mod bar { pub struct S; }
             //- /baz.rs
             pub use crate::foo::bar::S;
         "#;
-        check_found_path(code, "baz::S");
+        check_found_path(code, "baz::S", "baz::S", "crate::baz::S", "self::baz::S");
     }
 
     #[test]
@@ -563,10 +654,10 @@ fn discount_private_imports() {
             pub mod bar { pub struct S; }
             use bar::S;
             //- /foo.rs
-            <|>
+            $0
         "#;
         // crate::S would be shorter, but using private imports seems wrong
-        check_found_path(code, "crate::bar::S");
+        check_found_path(code, "crate::bar::S", "crate::bar::S", "crate::bar::S", "crate::bar::S");
     }
 
     #[test]
@@ -577,14 +668,14 @@ fn import_cycle() {
             pub mod bar;
             pub mod baz;
             //- /bar.rs
-            <|>
+            $0
             //- /foo.rs
             pub use super::baz;
             pub struct S;
             //- /baz.rs
             pub use super::foo;
         "#;
-        check_found_path(code, "crate::foo::S");
+        check_found_path(code, "crate::foo::S", "crate::foo::S", "crate::foo::S", "crate::foo::S");
     }
 
     #[test]
@@ -592,7 +683,7 @@ fn prefer_std_paths_over_alloc() {
         mark::check!(prefer_std_paths);
         let code = r#"
         //- /main.rs crate:main deps:alloc,std
-        <|>
+        $0
 
         //- /std.rs crate:std deps:alloc
         pub mod sync {
@@ -604,7 +695,13 @@ pub mod sync {
             pub struct Arc;
         }
         "#;
-        check_found_path(code, "std::sync::Arc");
+        check_found_path(
+            code,
+            "std::sync::Arc",
+            "std::sync::Arc",
+            "std::sync::Arc",
+            "std::sync::Arc",
+        );
     }
 
     #[test]
@@ -614,7 +711,7 @@ fn prefer_core_paths_over_std() {
         //- /main.rs crate:main deps:core,std
         #![no_std]
 
-        <|>
+        $0
 
         //- /std.rs crate:std deps:core
 
@@ -628,7 +725,13 @@ pub mod fmt {
             pub struct Error;
         }
         "#;
-        check_found_path(code, "core::fmt::Error");
+        check_found_path(
+            code,
+            "core::fmt::Error",
+            "core::fmt::Error",
+            "core::fmt::Error",
+            "core::fmt::Error",
+        );
     }
 
     #[test]
@@ -637,7 +740,7 @@ fn prefer_alloc_paths_over_std() {
         //- /main.rs crate:main deps:alloc,std
         #![no_std]
 
-        <|>
+        $0
 
         //- /std.rs crate:std deps:alloc
 
@@ -651,14 +754,20 @@ pub mod sync {
             pub struct Arc;
         }
         "#;
-        check_found_path(code, "alloc::sync::Arc");
+        check_found_path(
+            code,
+            "alloc::sync::Arc",
+            "alloc::sync::Arc",
+            "alloc::sync::Arc",
+            "alloc::sync::Arc",
+        );
     }
 
     #[test]
     fn prefer_shorter_paths_if_not_alloc() {
         let code = r#"
         //- /main.rs crate:main deps:megaalloc,std
-        <|>
+        $0
 
         //- /std.rs crate:std deps:megaalloc
         pub mod sync {
@@ -668,20 +777,26 @@ pub mod sync {
         //- /zzz.rs crate:megaalloc
         pub struct Arc;
         "#;
-        check_found_path(code, "megaalloc::Arc");
+        check_found_path(
+            code,
+            "megaalloc::Arc",
+            "megaalloc::Arc",
+            "megaalloc::Arc",
+            "megaalloc::Arc",
+        );
     }
 
     #[test]
     fn builtins_are_in_scope() {
         let code = r#"
         //- /main.rs
-        <|>
+        $0
 
         pub mod primitive {
             pub use u8;
         }
         "#;
-        check_found_path(code, "u8");
-        check_found_path(code, "u16");
+        check_found_path(code, "u8", "u8", "u8", "u8");
+        check_found_path(code, "u16", "u16", "u16", "u16");
     }
 }