]> git.lizzy.rs Git - rust.git/commitdiff
Make find_path_prefixed configurable
authorLukas Wirth <lukastw97@gmail.com>
Mon, 5 Oct 2020 15:12:37 +0000 (17:12 +0200)
committerLukas Wirth <lukastw97@gmail.com>
Mon, 5 Oct 2020 15:12:37 +0000 (17:12 +0200)
crates/hir/src/code_model.rs
crates/hir_def/src/find_path.rs

index 5721a66c4a54dec5bc6ed323744d2aaeec99be0c..5f35d9d3c7f39554cd2e3c230fffa022cca774a6 100644 (file)
@@ -4,6 +4,7 @@
 use arrayvec::ArrayVec;
 use base_db::{CrateId, Edition, FileId};
 use either::Either;
+use hir_def::find_path::PrefixKind;
 use hir_def::{
     adt::ReprKind,
     adt::StructKind,
@@ -391,7 +392,7 @@ pub fn find_use_path_prefixed(
         db: &dyn DefDatabase,
         item: impl Into<ItemInNs>,
     ) -> Option<ModPath> {
-        hir_def::find_path::find_path_prefixed(db, item.into(), self.into())
+        hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), PrefixKind::Plain)
     }
 }
 
index baf3741448d2775f8cfffa096d2221a794c526b9..9106ed45fac1f23fccfbf94a484ce391c35caef5 100644 (file)
 /// *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, Prefixed::Not)
+    find_path_inner(db, item, from, MAX_PATH_LEN, None)
 }
 
-pub fn find_path_prefixed(db: &dyn DefDatabase, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
-    let _p = profile::span("find_path_absolute");
-    find_path_inner(db, item, from, MAX_PATH_LEN, Prefixed::Plain)
+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;
@@ -42,58 +47,52 @@ fn can_start_with_std(&self) -> bool {
     }
 }
 
-fn check_crate_self_super(
-    def_map: &CrateDefMap,
-    item: ItemInNs,
-    from: ModuleId,
-) -> Option<ModPath> {
-    // - if the item is the crate root, return `crate`
-    if item
-        == ItemInNs::Types(ModuleDefId::ModuleId(ModuleId {
-            krate: from.krate,
-            local_id: def_map.root,
-        }))
-    {
-        Some(ModPath::from_segments(PathKind::Crate, Vec::new()))
-    } else if item == ItemInNs::Types(from.into()) {
+fn check_self_super(def_map: &CrateDefMap, 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,
-                }))
-            {
-                return Some(ModPath::from_segments(PathKind::Super(1), 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, PartialEq, Eq)]
-pub enum Prefixed {
-    Not,
+#[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 Prefixed {
+impl PrefixKind {
     #[inline]
-    fn prefix(self) -> Option<PathKind> {
+    fn prefix(self) -> PathKind {
         match self {
-            Prefixed::Not => None,
-            Prefixed::BySelf => Some(PathKind::Super(0)),
-            Prefixed::Plain => Some(PathKind::Plain),
+            PrefixKind::BySelf => PathKind::Super(0),
+            PrefixKind::Plain => PathKind::Plain,
+            PrefixKind::ByCrate => PathKind::Crate,
         }
     }
 
     #[inline]
-    fn prefixed(self) -> bool {
-        self != Prefixed::Not
+    fn is_absolute(&self) -> bool {
+        self == &PrefixKind::ByCrate
     }
 }
 
@@ -102,7 +101,7 @@ fn find_path_inner(
     item: ItemInNs,
     from: ModuleId,
     max_len: usize,
-    prefixed: Prefixed,
+    prefixed: Option<PrefixKind>,
 ) -> Option<ModPath> {
     if max_len == 0 {
         return None;
@@ -115,13 +114,25 @@ fn find_path_inner(
     let from_scope: &crate::item_scope::ItemScope = &def_map.modules[from.local_id].scope;
     let scope_name =
         if let Some((name, _)) = from_scope.name_of(item) { Some(name.clone()) } else { None };
-    if !prefixed.prefixed() && scope_name.is_some() {
+    if prefixed.is_none() && scope_name.is_some() {
         return scope_name
             .map(|scope_name| ModPath::from_segments(PathKind::Plain, vec![scope_name]));
     }
 
-    if let modpath @ Some(_) = check_crate_self_super(&def_map, item, from) {
-        return modpath;
+    // - if the item is the crate root, return `crate`
+    if item
+        == ItemInNs::Types(ModuleDefId::ModuleId(ModuleId {
+            krate: from.krate,
+            local_id: def_map.root,
+        }))
+    {
+        return Some(ModPath::from_segments(PathKind::Crate, 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
@@ -226,7 +237,7 @@ fn find_path_inner(
         }
     }
 
-    if let Some(prefix) = prefixed.prefix() {
+    if let Some(prefix) = prefixed.map(PrefixKind::prefix) {
         best_path.or_else(|| {
             scope_name.map(|scope_name| ModPath::from_segments(prefix, vec![scope_name]))
         })
@@ -355,7 +366,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, absolute: bool) {
+    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));
@@ -375,20 +386,22 @@ fn check_found_path_(ra_fixture: &str, path: &str, absolute: bool) {
             .take_types()
             .unwrap();
 
-        let found_path = if absolute { find_path_prefixed } else { find_path }(
-            &db,
-            ItemInNs::Types(resolved),
-            module,
-        );
-        assert_eq!(found_path, Some(mod_path), "absolute {}", absolute);
+        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);
     }
 
-    fn check_found_path(ra_fixture: &str, path: &str) {
-        check_found_path_(ra_fixture, path, false);
-    }
-
-    fn check_found_path_abs(ra_fixture: &str, path: &str) {
-        check_found_path_(ra_fixture, path, true);
+    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]
@@ -398,8 +411,7 @@ fn same_module() {
             struct S;
             <|>
         "#;
-        check_found_path(code, "S");
-        check_found_path_abs(code, "S");
+        check_found_path(code, "S", "S", "crate::S", "self::S");
     }
 
     #[test]
@@ -409,8 +421,7 @@ fn enum_variant() {
             enum E { A }
             <|>
         "#;
-        check_found_path(code, "E::A");
-        check_found_path_abs(code, "E::A");
+        check_found_path(code, "E::A", "E::A", "E::A", "E::A");
     }
 
     #[test]
@@ -422,8 +433,7 @@ mod foo {
             }
             <|>
         "#;
-        check_found_path(code, "foo::S");
-        check_found_path_abs(code, "foo::S");
+        check_found_path(code, "foo::S", "foo::S", "crate::foo::S", "self::foo::S");
     }
 
     #[test]
@@ -437,8 +447,7 @@ fn super_module() {
             //- /foo/bar.rs
             <|>
         "#;
-        check_found_path(code, "super::S");
-        check_found_path_abs(code, "super::S");
+        check_found_path(code, "super::S", "super::S", "crate::foo::S", "super::S");
     }
 
     #[test]
@@ -449,8 +458,7 @@ fn self_module() {
             //- /foo.rs
             <|>
         "#;
-        check_found_path(code, "self");
-        check_found_path_abs(code, "self");
+        check_found_path(code, "self", "self", "crate::foo", "self");
     }
 
     #[test]
@@ -461,8 +469,7 @@ fn crate_root() {
             //- /foo.rs
             <|>
         "#;
-        check_found_path(code, "crate");
-        check_found_path_abs(code, "crate");
+        check_found_path(code, "crate", "crate", "crate", "crate");
     }
 
     #[test]
@@ -474,8 +481,7 @@ fn same_crate() {
             //- /foo.rs
             <|>
         "#;
-        check_found_path(code, "crate::S");
-        check_found_path_abs(code, "crate::S");
+        check_found_path(code, "crate::S", "crate::S", "crate::S", "crate::S");
     }
 
     #[test]
@@ -486,8 +492,7 @@ fn different_crate() {
             //- /std.rs crate:std
             pub struct S;
         "#;
-        check_found_path(code, "std::S");
-        check_found_path_abs(code, "std::S");
+        check_found_path(code, "std::S", "std::S", "std::S", "std::S");
     }
 
     #[test]
@@ -499,8 +504,13 @@ fn different_crate_renamed() {
             //- /std.rs crate:std
             pub struct S;
         "#;
-        check_found_path(code, "std_renamed::S");
-        check_found_path_abs(code, "std_renamed::S");
+        check_found_path(
+            code,
+            "std_renamed::S",
+            "std_renamed::S",
+            "std_renamed::S",
+            "std_renamed::S",
+        );
     }
 
     #[test]
@@ -520,8 +530,13 @@ pub enum ModuleItem {
                 }
             }
         "#;
-        check_found_path(code, "ast::ModuleItem");
-        check_found_path_abs(code, "syntax::ast::ModuleItem");
+        check_found_path(
+            code,
+            "ast::ModuleItem",
+            "syntax::ast::ModuleItem",
+            "syntax::ast::ModuleItem",
+            "syntax::ast::ModuleItem",
+        );
 
         let code = r#"
             //- /main.rs crate:main deps:syntax
@@ -535,8 +550,13 @@ pub enum ModuleItem {
                 }
             }
         "#;
-        check_found_path(code, "syntax::ast::ModuleItem");
-        check_found_path_abs(code, "syntax::ast::ModuleItem");
+        check_found_path(
+            code,
+            "syntax::ast::ModuleItem",
+            "syntax::ast::ModuleItem",
+            "syntax::ast::ModuleItem",
+            "syntax::ast::ModuleItem",
+        );
     }
 
     #[test]
@@ -549,8 +569,7 @@ mod bar {
             }
             <|>
         "#;
-        check_found_path(code, "bar::S");
-        check_found_path_abs(code, "bar::S");
+        check_found_path(code, "bar::S", "bar::S", "crate::bar::S", "self::bar::S");
     }
 
     #[test]
@@ -563,8 +582,7 @@ mod bar {
             }
             <|>
         "#;
-        check_found_path(code, "bar::U");
-        check_found_path_abs(code, "bar::U");
+        check_found_path(code, "bar::U", "bar::U", "crate::bar::U", "self::bar::U");
     }
 
     #[test]
@@ -577,8 +595,7 @@ fn different_crate_reexport() {
             //- /core.rs crate:core
             pub struct S;
         "#;
-        check_found_path(code, "std::S");
-        check_found_path_abs(code, "std::S");
+        check_found_path(code, "std::S", "std::S", "std::S", "std::S");
     }
 
     #[test]
@@ -591,8 +608,7 @@ fn prelude() {
             #[prelude_import]
             pub use prelude::*;
         "#;
-        check_found_path(code, "S");
-        check_found_path_abs(code, "S");
+        check_found_path(code, "S", "S", "S", "S");
     }
 
     #[test]
@@ -608,10 +624,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_abs(code, "None");
-        check_found_path_abs(code, "Some");
+        check_found_path(code, "None", "None", "None", "None");
+        check_found_path(code, "Some", "Some", "Some", "Some");
     }
 
     #[test]
@@ -627,8 +641,7 @@ fn shortest_path() {
             //- /baz.rs
             pub use crate::foo::bar::S;
         "#;
-        check_found_path(code, "baz::S");
-        check_found_path_abs(code, "baz::S");
+        check_found_path(code, "baz::S", "baz::S", "crate::baz::S", "self::baz::S");
     }
 
     #[test]
@@ -642,8 +655,7 @@ fn discount_private_imports() {
             <|>
         "#;
         // crate::S would be shorter, but using private imports seems wrong
-        check_found_path(code, "crate::bar::S");
-        check_found_path_abs(code, "crate::bar::S");
+        check_found_path(code, "crate::bar::S", "crate::bar::S", "crate::bar::S", "crate::bar::S");
     }
 
     #[test]
@@ -661,8 +673,7 @@ fn import_cycle() {
             //- /baz.rs
             pub use super::foo;
         "#;
-        check_found_path(code, "crate::foo::S");
-        check_found_path_abs(code, "crate::foo::S");
+        check_found_path(code, "crate::foo::S", "crate::foo::S", "crate::foo::S", "crate::foo::S");
     }
 
     #[test]
@@ -682,8 +693,13 @@ pub mod sync {
             pub struct Arc;
         }
         "#;
-        check_found_path(code, "std::sync::Arc");
-        check_found_path_abs(code, "std::sync::Arc");
+        check_found_path(
+            code,
+            "std::sync::Arc",
+            "std::sync::Arc",
+            "std::sync::Arc",
+            "std::sync::Arc",
+        );
     }
 
     #[test]
@@ -707,8 +723,13 @@ pub mod fmt {
             pub struct Error;
         }
         "#;
-        check_found_path(code, "core::fmt::Error");
-        check_found_path_abs(code, "core::fmt::Error");
+        check_found_path(
+            code,
+            "core::fmt::Error",
+            "core::fmt::Error",
+            "core::fmt::Error",
+            "core::fmt::Error",
+        );
     }
 
     #[test]
@@ -731,8 +752,13 @@ pub mod sync {
             pub struct Arc;
         }
         "#;
-        check_found_path(code, "alloc::sync::Arc");
-        check_found_path_abs(code, "alloc::sync::Arc");
+        check_found_path(
+            code,
+            "alloc::sync::Arc",
+            "alloc::sync::Arc",
+            "alloc::sync::Arc",
+            "alloc::sync::Arc",
+        );
     }
 
     #[test]
@@ -749,8 +775,13 @@ pub mod sync {
         //- /zzz.rs crate:megaalloc
         pub struct Arc;
         "#;
-        check_found_path(code, "megaalloc::Arc");
-        check_found_path_abs(code, "megaalloc::Arc");
+        check_found_path(
+            code,
+            "megaalloc::Arc",
+            "megaalloc::Arc",
+            "megaalloc::Arc",
+            "megaalloc::Arc",
+        );
     }
 
     #[test]
@@ -763,9 +794,7 @@ pub mod primitive {
             pub use u8;
         }
         "#;
-        check_found_path(code, "u8");
-        check_found_path(code, "u16");
-        check_found_path_abs(code, "u8");
-        check_found_path_abs(code, "u16");
+        check_found_path(code, "u8", "u8", "u8", "u8");
+        check_found_path(code, "u16", "u16", "u16", "u16");
     }
 }