5 import_assets::{ImportCandidate, LocatedImport},
8 use ide_db::RootDatabase;
11 ast::{make, HasArgList},
16 assist_context::{AssistContext, Assists},
17 handlers::auto_import::find_importable_node,
18 AssistId, AssistKind, GroupLabel,
21 // Assist: qualify_path
23 // If the name is unresolved, provides all possible qualified paths for it.
27 // let map = HashMap$0::new();
29 // # pub mod std { pub mod collections { pub struct HashMap { } } }
34 // let map = std::collections::HashMap::new();
36 // # pub mod std { pub mod collections { pub struct HashMap { } } }
38 pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
39 let (import_assets, syntax_under_caret) = find_importable_node(ctx)?;
40 let mut proposed_imports = import_assets.search_for_relative_paths(&ctx.sema);
41 if proposed_imports.is_empty() {
45 let range = match &syntax_under_caret {
46 NodeOrToken::Node(node) => ctx.sema.original_range(node).range,
47 NodeOrToken::Token(token) => token.text_range(),
49 let candidate = import_assets.import_candidate();
50 let qualify_candidate = match syntax_under_caret {
51 NodeOrToken::Node(syntax_under_caret) => match candidate {
52 ImportCandidate::Path(candidate) if candidate.qualifier.is_some() => {
53 cov_mark::hit!(qualify_path_qualifier_start);
54 let path = ast::Path::cast(syntax_under_caret)?;
55 let (prev_segment, segment) = (path.qualifier()?.segment()?, path.segment()?);
56 QualifyCandidate::QualifierStart(segment, prev_segment.generic_arg_list())
58 ImportCandidate::Path(_) => {
59 cov_mark::hit!(qualify_path_unqualified_name);
60 let path = ast::Path::cast(syntax_under_caret)?;
61 let generics = path.segment()?.generic_arg_list();
62 QualifyCandidate::UnqualifiedName(generics)
64 ImportCandidate::TraitAssocItem(_) => {
65 cov_mark::hit!(qualify_path_trait_assoc_item);
66 let path = ast::Path::cast(syntax_under_caret)?;
67 let (qualifier, segment) = (path.qualifier()?, path.segment()?);
68 QualifyCandidate::TraitAssocItem(qualifier, segment)
70 ImportCandidate::TraitMethod(_) => {
71 cov_mark::hit!(qualify_path_trait_method);
72 let mcall_expr = ast::MethodCallExpr::cast(syntax_under_caret)?;
73 QualifyCandidate::TraitMethod(ctx.sema.db, mcall_expr)
76 // derive attribute path
77 NodeOrToken::Token(_) => QualifyCandidate::UnqualifiedName(None),
80 // we aren't interested in different namespaces
81 proposed_imports.dedup_by(|a, b| a.import_path == b.import_path);
83 let group_label = group_label(candidate);
84 for import in proposed_imports {
87 AssistId("qualify_path", AssistKind::QuickFix),
88 label(candidate, &import),
91 qualify_candidate.qualify(
92 |replace_with: String| builder.replace(range, replace_with),
94 import.item_to_import,
101 pub(crate) enum QualifyCandidate<'db> {
102 QualifierStart(ast::PathSegment, Option<ast::GenericArgList>),
103 UnqualifiedName(Option<ast::GenericArgList>),
104 TraitAssocItem(ast::Path, ast::PathSegment),
105 TraitMethod(&'db RootDatabase, ast::MethodCallExpr),
106 ImplMethod(&'db RootDatabase, ast::MethodCallExpr, hir::Function),
109 impl QualifyCandidate<'_> {
110 pub(crate) fn qualify(
112 mut replacer: impl FnMut(String),
113 import: &hir::ModPath,
116 let import = mod_path_to_ast(import);
118 QualifyCandidate::QualifierStart(segment, generics) => {
119 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
120 replacer(format!("{}{}::{}", import, generics, segment));
122 QualifyCandidate::UnqualifiedName(generics) => {
123 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
124 replacer(format!("{}{}", import.to_string(), generics));
126 QualifyCandidate::TraitAssocItem(qualifier, segment) => {
127 replacer(format!("<{} as {}>::{}", qualifier, import, segment));
129 QualifyCandidate::TraitMethod(db, mcall_expr) => {
130 Self::qualify_trait_method(db, mcall_expr, replacer, import, item);
132 QualifyCandidate::ImplMethod(db, mcall_expr, hir_fn) => {
133 Self::qualify_fn_call(db, mcall_expr, replacer, import, hir_fn);
140 mcall_expr: &ast::MethodCallExpr,
141 mut replacer: impl FnMut(String),
143 hir_fn: &hir::Function,
145 let receiver = mcall_expr.receiver()?;
146 let method_name = mcall_expr.name_ref()?;
148 mcall_expr.generic_arg_list().as_ref().map_or_else(String::new, ToString::to_string);
149 let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args());
151 if let Some(self_access) = hir_fn.self_param(db).map(|sp| sp.access(db)) {
152 let receiver = match self_access {
153 hir::Access::Shared => make::expr_ref(receiver, false),
154 hir::Access::Exclusive => make::expr_ref(receiver, true),
155 hir::Access::Owned => receiver,
163 Some(args) => make::arg_list(iter::once(receiver).chain(args)),
164 None => make::arg_list(iter::once(receiver)),
171 fn qualify_trait_method(
173 mcall_expr: &ast::MethodCallExpr,
174 replacer: impl FnMut(String),
178 let trait_method_name = mcall_expr.name_ref()?;
179 let trait_ = item_as_trait(db, item)?;
180 let method = find_trait_method(db, trait_, &trait_method_name)?;
181 Self::qualify_fn_call(db, mcall_expr, replacer, import, &method)
185 fn find_trait_method(
188 trait_method_name: &ast::NameRef,
189 ) -> Option<hir::Function> {
190 if let Some(hir::AssocItem::Function(method)) =
191 trait_.items(db).into_iter().find(|item: &hir::AssocItem| {
193 .map(|name| name.to_string() == trait_method_name.to_string())
203 fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option<hir::Trait> {
204 let item_module_def = item.as_module_def()?;
206 match item_module_def {
207 hir::ModuleDef::Trait(trait_) => Some(trait_),
208 _ => item_module_def.as_assoc_item(db)?.containing_trait(db),
212 fn group_label(candidate: &ImportCandidate) -> GroupLabel {
213 let name = match candidate {
214 ImportCandidate::Path(it) => &it.name,
215 ImportCandidate::TraitAssocItem(it) | ImportCandidate::TraitMethod(it) => {
220 GroupLabel(format!("Qualify {}", name))
223 fn label(candidate: &ImportCandidate, import: &LocatedImport) -> String {
225 ImportCandidate::Path(candidate) if candidate.qualifier.is_none() => {
226 format!("Qualify as `{}`", import.import_path)
228 _ => format!("Qualify with `{}`", import.import_path),
234 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
239 fn applicable_when_found_an_import_partial() {
240 cov_mark::check!(qualify_path_unqualified_name);
246 pub struct Formatter;
257 pub struct Formatter;
269 fn applicable_when_found_an_import() {
276 pub struct PubStruct;
283 pub struct PubStruct;
290 fn applicable_in_macros() {
295 ($i:ident) => { fn foo(a: $i) {} }
300 pub struct PubStruct;
305 ($i:ident) => { fn foo(a: $i) {} }
307 foo!(PubMod::PubStruct);
310 pub struct PubStruct;
317 fn applicable_when_found_multiple_imports() {
324 pub struct PubStruct;
327 pub struct PubStruct;
330 pub struct PubStruct;
337 pub struct PubStruct;
340 pub struct PubStruct;
343 pub struct PubStruct;
350 fn not_applicable_for_already_imported_types() {
351 check_assist_not_applicable(
354 use PubMod::PubStruct;
359 pub struct PubStruct;
366 fn not_applicable_for_types_with_private_paths() {
367 check_assist_not_applicable(
373 struct PrivateStruct;
380 fn not_applicable_when_no_imports_found() {
381 check_assist_not_applicable(qualify_path, r#"PubStruct$0"#);
385 fn not_applicable_in_import_statements() {
386 check_assist_not_applicable(
392 pub struct PubStruct;
399 fn qualify_function() {
406 pub fn test_function() {};
410 PubMod::test_function
413 pub fn test_function() {};
424 //- /lib.rs crate:crate_with_macro
430 //- /main.rs crate:main deps:crate_with_macro
437 crate_with_macro::foo
444 fn qualify_path_target() {
449 group_label: Option<$0GroupLabel>,
452 mod m { pub struct GroupLabel; }
459 fn not_applicable_when_path_start_is_imported() {
460 check_assist_not_applicable(
466 pub struct TestStruct;
473 mod2::mod3::TestStruct$0
480 fn not_applicable_for_imported_function() {
481 check_assist_not_applicable(
485 pub fn test_function() {}
488 use test_mod::test_function;
497 fn associated_struct_function() {
502 pub struct TestStruct {}
504 pub fn test_function() {}
509 TestStruct::test_function$0
514 pub struct TestStruct {}
516 pub fn test_function() {}
521 test_mod::TestStruct::test_function
528 fn associated_struct_const() {
529 cov_mark::check!(qualify_path_qualifier_start);
534 pub struct TestStruct {}
536 const TEST_CONST: u8 = 42;
541 TestStruct::TEST_CONST$0
546 pub struct TestStruct {}
548 const TEST_CONST: u8 = 42;
553 test_mod::TestStruct::TEST_CONST
560 fn associated_struct_const_unqualified() {
561 // FIXME: non-trait assoc items completion is unsupported yet, see FIXME in the import_assets.rs for more details
562 check_assist_not_applicable(
566 pub struct TestStruct {}
568 const TEST_CONST: u8 = 42;
580 fn associated_trait_function() {
585 pub trait TestTrait {
588 pub struct TestStruct {}
589 impl TestTrait for TestStruct {
590 fn test_function() {}
595 test_mod::TestStruct::test_function$0
600 pub trait TestTrait {
603 pub struct TestStruct {}
604 impl TestTrait for TestStruct {
605 fn test_function() {}
610 <test_mod::TestStruct as test_mod::TestTrait>::test_function
617 fn not_applicable_for_imported_trait_for_function() {
618 check_assist_not_applicable(
622 pub trait TestTrait {
625 pub trait TestTrait2 {
632 impl TestTrait2 for TestEnum {
633 fn test_function() {}
635 impl TestTrait for TestEnum {
636 fn test_function() {}
640 use test_mod::TestTrait2;
642 test_mod::TestEnum::test_function$0;
649 fn associated_trait_const() {
650 cov_mark::check!(qualify_path_trait_assoc_item);
655 pub trait TestTrait {
656 const TEST_CONST: u8;
658 pub struct TestStruct {}
659 impl TestTrait for TestStruct {
660 const TEST_CONST: u8 = 42;
665 test_mod::TestStruct::TEST_CONST$0
670 pub trait TestTrait {
671 const TEST_CONST: u8;
673 pub struct TestStruct {}
674 impl TestTrait for TestStruct {
675 const TEST_CONST: u8 = 42;
680 <test_mod::TestStruct as test_mod::TestTrait>::TEST_CONST
687 fn not_applicable_for_imported_trait_for_const() {
688 check_assist_not_applicable(
692 pub trait TestTrait {
693 const TEST_CONST: u8;
695 pub trait TestTrait2 {
696 const TEST_CONST: f64;
702 impl TestTrait2 for TestEnum {
703 const TEST_CONST: f64 = 42.0;
705 impl TestTrait for TestEnum {
706 const TEST_CONST: u8 = 42;
710 use test_mod::TestTrait2;
712 test_mod::TestEnum::TEST_CONST$0;
720 cov_mark::check!(qualify_path_trait_method);
725 pub trait TestTrait {
726 fn test_method(&self);
728 pub struct TestStruct {}
729 impl TestTrait for TestStruct {
730 fn test_method(&self) {}
735 let test_struct = test_mod::TestStruct {};
736 test_struct.test_meth$0od()
741 pub trait TestTrait {
742 fn test_method(&self);
744 pub struct TestStruct {}
745 impl TestTrait for TestStruct {
746 fn test_method(&self) {}
751 let test_struct = test_mod::TestStruct {};
752 test_mod::TestTrait::test_method(&test_struct)
759 fn trait_method_multi_params() {
764 pub trait TestTrait {
765 fn test_method(&self, test: i32);
767 pub struct TestStruct {}
768 impl TestTrait for TestStruct {
769 fn test_method(&self, test: i32) {}
774 let test_struct = test_mod::TestStruct {};
775 test_struct.test_meth$0od(42)
780 pub trait TestTrait {
781 fn test_method(&self, test: i32);
783 pub struct TestStruct {}
784 impl TestTrait for TestStruct {
785 fn test_method(&self, test: i32) {}
790 let test_struct = test_mod::TestStruct {};
791 test_mod::TestTrait::test_method(&test_struct, 42)
798 fn trait_method_consume() {
803 pub trait TestTrait {
804 fn test_method(self);
806 pub struct TestStruct {}
807 impl TestTrait for TestStruct {
808 fn test_method(self) {}
813 let test_struct = test_mod::TestStruct {};
814 test_struct.test_meth$0od()
819 pub trait TestTrait {
820 fn test_method(self);
822 pub struct TestStruct {}
823 impl TestTrait for TestStruct {
824 fn test_method(self) {}
829 let test_struct = test_mod::TestStruct {};
830 test_mod::TestTrait::test_method(test_struct)
837 fn trait_method_cross_crate() {
841 //- /main.rs crate:main deps:dep
843 let test_struct = dep::test_mod::TestStruct {};
844 test_struct.test_meth$0od()
846 //- /dep.rs crate:dep
848 pub trait TestTrait {
849 fn test_method(&self);
851 pub struct TestStruct {}
852 impl TestTrait for TestStruct {
853 fn test_method(&self) {}
859 let test_struct = dep::test_mod::TestStruct {};
860 dep::test_mod::TestTrait::test_method(&test_struct)
867 fn assoc_fn_cross_crate() {
871 //- /main.rs crate:main deps:dep
873 dep::test_mod::TestStruct::test_func$0tion
875 //- /dep.rs crate:dep
877 pub trait TestTrait {
880 pub struct TestStruct {}
881 impl TestTrait for TestStruct {
882 fn test_function() {}
888 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::test_function
895 fn assoc_const_cross_crate() {
899 //- /main.rs crate:main deps:dep
901 dep::test_mod::TestStruct::CONST$0
903 //- /dep.rs crate:dep
905 pub trait TestTrait {
908 pub struct TestStruct {}
909 impl TestTrait for TestStruct {
910 const CONST: bool = true;
916 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::CONST
923 fn assoc_fn_as_method_cross_crate() {
924 check_assist_not_applicable(
927 //- /main.rs crate:main deps:dep
929 let test_struct = dep::test_mod::TestStruct {};
930 test_struct.test_func$0tion()
932 //- /dep.rs crate:dep
934 pub trait TestTrait {
937 pub struct TestStruct {}
938 impl TestTrait for TestStruct {
939 fn test_function() {}
947 fn private_trait_cross_crate() {
948 check_assist_not_applicable(
951 //- /main.rs crate:main deps:dep
953 let test_struct = dep::test_mod::TestStruct {};
954 test_struct.test_meth$0od()
956 //- /dep.rs crate:dep
959 fn test_method(&self);
961 pub struct TestStruct {}
962 impl TestTrait for TestStruct {
963 fn test_method(&self) {}
971 fn not_applicable_for_imported_trait_for_method() {
972 check_assist_not_applicable(
976 pub trait TestTrait {
977 fn test_method(&self);
979 pub trait TestTrait2 {
980 fn test_method(&self);
986 impl TestTrait2 for TestEnum {
987 fn test_method(&self) {}
989 impl TestTrait for TestEnum {
990 fn test_method(&self) {}
994 use test_mod::TestTrait2;
996 let one = test_mod::TestEnum::One;
1008 //- /lib.rs crate:dep
1011 //- /main.rs crate:main deps:dep
1025 fn whole_segment() {
1026 // Tests that only imports whose last segment matches the identifier get suggested.
1030 //- /lib.rs crate:dep
1032 pub trait Display {}
1035 pub fn panic_fmt() {}
1037 //- /main.rs crate:main deps:dep
1040 impl f$0mt::Display for S {}
1045 impl dep::fmt::Display for S {}
1051 fn macro_generated() {
1052 // Tests that macro-generated items are suggested from external crates.
1056 //- /lib.rs crate:dep
1065 //- /main.rs crate:main deps:dep
1080 // Tests that differently cased names don't interfere and we only suggest the matching one.
1084 //- /lib.rs crate:dep
1088 //- /main.rs crate:main deps:dep
1102 fn keep_generic_annotations() {
1106 //- /lib.rs crate:dep
1107 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1109 //- /main.rs crate:main deps:dep
1110 fn foo() -> Thin$0g<'static, ()> {}
1115 fn foo() -> dep::generic::Thing<'static, ()> {}
1123 fn keep_generic_annotations_leading_colon() {
1127 //- /lib.rs crate:dep
1128 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1130 //- /main.rs crate:main deps:dep
1131 fn foo() -> Thin$0g::<'static, ()> {}
1136 fn foo() -> dep::generic::Thing::<'static, ()> {}
1144 fn associated_struct_const_generic() {
1149 pub struct TestStruct<T> {}
1150 impl<T> TestStruct<T> {
1151 const TEST_CONST: u8 = 42;
1156 TestStruct::<()>::TEST_CONST$0
1161 pub struct TestStruct<T> {}
1162 impl<T> TestStruct<T> {
1163 const TEST_CONST: u8 = 42;
1168 test_mod::TestStruct::<()>::TEST_CONST
1175 fn associated_trait_const_generic() {
1180 pub trait TestTrait {
1181 const TEST_CONST: u8;
1183 pub struct TestStruct<T> {}
1184 impl<T> TestTrait for TestStruct<T> {
1185 const TEST_CONST: u8 = 42;
1190 test_mod::TestStruct::<()>::TEST_CONST$0
1195 pub trait TestTrait {
1196 const TEST_CONST: u8;
1198 pub struct TestStruct<T> {}
1199 impl<T> TestTrait for TestStruct<T> {
1200 const TEST_CONST: u8 = 42;
1205 <test_mod::TestStruct::<()> as test_mod::TestTrait>::TEST_CONST
1212 fn trait_method_generic() {
1217 pub trait TestTrait {
1218 fn test_method<T>(&self);
1220 pub struct TestStruct {}
1221 impl TestTrait for TestStruct {
1222 fn test_method<T>(&self) {}
1227 let test_struct = test_mod::TestStruct {};
1228 test_struct.test_meth$0od::<()>()
1233 pub trait TestTrait {
1234 fn test_method<T>(&self);
1236 pub struct TestStruct {}
1237 impl TestTrait for TestStruct {
1238 fn test_method<T>(&self) {}
1243 let test_struct = test_mod::TestStruct {};
1244 test_mod::TestTrait::test_method::<()>(&test_struct)
1251 fn works_in_derives() {
1257 #[rustc_builtin_macro]
1265 #[rustc_builtin_macro]
1268 #[derive(foo::Copy)]