5 import_assets::{ImportCandidate, LocatedImport},
8 use ide_db::RootDatabase;
11 ast::{make, ArgListOwner},
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 proposed_imports = import_assets.search_for_relative_paths(&ctx.sema);
41 if proposed_imports.is_empty() {
45 let range = ctx.sema.original_range(&syntax_under_caret).range;
46 let candidate = import_assets.import_candidate();
47 let qualify_candidate = match candidate {
48 ImportCandidate::Path(candidate) if candidate.qualifier.is_some() => {
49 cov_mark::hit!(qualify_path_qualifier_start);
50 let path = ast::Path::cast(syntax_under_caret)?;
51 let (prev_segment, segment) = (path.qualifier()?.segment()?, path.segment()?);
52 QualifyCandidate::QualifierStart(segment, prev_segment.generic_arg_list())
54 ImportCandidate::Path(_) => {
55 cov_mark::hit!(qualify_path_unqualified_name);
56 let path = ast::Path::cast(syntax_under_caret)?;
57 let generics = path.segment()?.generic_arg_list();
58 QualifyCandidate::UnqualifiedName(generics)
60 ImportCandidate::TraitAssocItem(_) => {
61 cov_mark::hit!(qualify_path_trait_assoc_item);
62 let path = ast::Path::cast(syntax_under_caret)?;
63 let (qualifier, segment) = (path.qualifier()?, path.segment()?);
64 QualifyCandidate::TraitAssocItem(qualifier, segment)
66 ImportCandidate::TraitMethod(_) => {
67 cov_mark::hit!(qualify_path_trait_method);
68 let mcall_expr = ast::MethodCallExpr::cast(syntax_under_caret)?;
69 QualifyCandidate::TraitMethod(ctx.sema.db, mcall_expr)
73 let group_label = group_label(candidate);
74 for import in proposed_imports {
77 AssistId("qualify_path", AssistKind::QuickFix),
78 label(candidate, &import),
81 qualify_candidate.qualify(
82 |replace_with: String| builder.replace(range, replace_with),
84 import.item_to_import,
92 enum QualifyCandidate<'db> {
93 QualifierStart(ast::PathSegment, Option<ast::GenericArgList>),
94 UnqualifiedName(Option<ast::GenericArgList>),
95 TraitAssocItem(ast::Path, ast::PathSegment),
96 TraitMethod(&'db RootDatabase, ast::MethodCallExpr),
99 impl QualifyCandidate<'_> {
102 mut replacer: impl FnMut(String),
103 import: &hir::ModPath,
106 let import = mod_path_to_ast(import);
108 QualifyCandidate::QualifierStart(segment, generics) => {
109 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
110 replacer(format!("{}{}::{}", import, generics, segment));
112 QualifyCandidate::UnqualifiedName(generics) => {
113 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
114 replacer(format!("{}{}", import.to_string(), generics));
116 QualifyCandidate::TraitAssocItem(qualifier, segment) => {
117 replacer(format!("<{} as {}>::{}", qualifier, import, segment));
119 QualifyCandidate::TraitMethod(db, mcall_expr) => {
120 Self::qualify_trait_method(db, mcall_expr, replacer, import, item);
125 fn qualify_trait_method(
127 mcall_expr: &ast::MethodCallExpr,
128 mut replacer: impl FnMut(String),
132 let receiver = mcall_expr.receiver()?;
133 let trait_method_name = mcall_expr.name_ref()?;
135 mcall_expr.generic_arg_list().as_ref().map_or_else(String::new, ToString::to_string);
136 let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args());
137 let trait_ = item_as_trait(db, item)?;
138 let method = find_trait_method(db, trait_, &trait_method_name)?;
139 if let Some(self_access) = method.self_param(db).map(|sp| sp.access(db)) {
140 let receiver = match self_access {
141 hir::Access::Shared => make::expr_ref(receiver, false),
142 hir::Access::Exclusive => make::expr_ref(receiver, true),
143 hir::Access::Owned => receiver,
151 Some(args) => make::arg_list(iter::once(receiver).chain(args)),
152 None => make::arg_list(iter::once(receiver)),
160 fn find_trait_method(
163 trait_method_name: &ast::NameRef,
164 ) -> Option<hir::Function> {
165 if let Some(hir::AssocItem::Function(method)) =
166 trait_.items(db).into_iter().find(|item: &hir::AssocItem| {
168 .map(|name| name.to_string() == trait_method_name.to_string())
178 fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option<hir::Trait> {
179 let item_module_def = hir::ModuleDef::from(item.as_module_def_id()?);
181 if let hir::ModuleDef::Trait(trait_) = item_module_def {
184 item_module_def.as_assoc_item(db)?.containing_trait(db)
188 fn group_label(candidate: &ImportCandidate) -> GroupLabel {
189 let name = match candidate {
190 ImportCandidate::Path(it) => &it.name,
191 ImportCandidate::TraitAssocItem(it) | ImportCandidate::TraitMethod(it) => {
196 GroupLabel(format!("Qualify {}", name))
199 fn label(candidate: &ImportCandidate, import: &LocatedImport) -> String {
201 ImportCandidate::Path(candidate) if candidate.qualifier.is_none() => {
202 format!("Qualify as `{}`", import.import_path)
204 _ => format!("Qualify with `{}`", import.import_path),
210 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
215 fn applicable_when_found_an_import_partial() {
216 cov_mark::check!(qualify_path_unqualified_name);
222 pub struct Formatter;
233 pub struct Formatter;
245 fn applicable_when_found_an_import() {
252 pub struct PubStruct;
259 pub struct PubStruct;
266 fn applicable_in_macros() {
271 ($i:ident) => { fn foo(a: $i) {} }
276 pub struct PubStruct;
281 ($i:ident) => { fn foo(a: $i) {} }
283 foo!(PubMod::PubStruct);
286 pub struct PubStruct;
293 fn applicable_when_found_multiple_imports() {
300 pub struct PubStruct;
303 pub struct PubStruct;
306 pub struct PubStruct;
313 pub struct PubStruct;
316 pub struct PubStruct;
319 pub struct PubStruct;
326 fn not_applicable_for_already_imported_types() {
327 check_assist_not_applicable(
330 use PubMod::PubStruct;
335 pub struct PubStruct;
342 fn not_applicable_for_types_with_private_paths() {
343 check_assist_not_applicable(
349 struct PrivateStruct;
356 fn not_applicable_when_no_imports_found() {
357 check_assist_not_applicable(
365 fn not_applicable_in_import_statements() {
366 check_assist_not_applicable(
372 pub struct PubStruct;
378 fn qualify_function() {
385 pub fn test_function() {};
389 PubMod::test_function
392 pub fn test_function() {};
403 //- /lib.rs crate:crate_with_macro
409 //- /main.rs crate:main deps:crate_with_macro
416 crate_with_macro::foo
423 fn qualify_path_target() {
428 group_label: Option<$0GroupLabel>,
431 mod m { pub struct GroupLabel; }
438 fn not_applicable_when_path_start_is_imported() {
439 check_assist_not_applicable(
445 pub struct TestStruct;
452 mod2::mod3::TestStruct$0
459 fn not_applicable_for_imported_function() {
460 check_assist_not_applicable(
464 pub fn test_function() {}
467 use test_mod::test_function;
476 fn associated_struct_function() {
481 pub struct TestStruct {}
483 pub fn test_function() {}
488 TestStruct::test_function$0
493 pub struct TestStruct {}
495 pub fn test_function() {}
500 test_mod::TestStruct::test_function
507 fn associated_struct_const() {
508 cov_mark::check!(qualify_path_qualifier_start);
513 pub struct TestStruct {}
515 const TEST_CONST: u8 = 42;
520 TestStruct::TEST_CONST$0
525 pub struct TestStruct {}
527 const TEST_CONST: u8 = 42;
532 test_mod::TestStruct::TEST_CONST
539 #[ignore = "FIXME: non-trait assoc items completion is unsupported yet, see FIXME in the import_assets.rs for more details"]
540 fn associated_struct_const_unqualified() {
545 pub struct TestStruct {}
547 const TEST_CONST: u8 = 42;
557 pub struct TestStruct {}
559 const TEST_CONST: u8 = 42;
564 test_mod::TestStruct::TEST_CONST
571 fn associated_trait_function() {
576 pub trait TestTrait {
579 pub struct TestStruct {}
580 impl TestTrait for TestStruct {
581 fn test_function() {}
586 test_mod::TestStruct::test_function$0
591 pub trait TestTrait {
594 pub struct TestStruct {}
595 impl TestTrait for TestStruct {
596 fn test_function() {}
601 <test_mod::TestStruct as test_mod::TestTrait>::test_function
608 fn not_applicable_for_imported_trait_for_function() {
609 check_assist_not_applicable(
613 pub trait TestTrait {
616 pub trait TestTrait2 {
623 impl TestTrait2 for TestEnum {
624 fn test_function() {}
626 impl TestTrait for TestEnum {
627 fn test_function() {}
631 use test_mod::TestTrait2;
633 test_mod::TestEnum::test_function$0;
640 fn associated_trait_const() {
641 cov_mark::check!(qualify_path_trait_assoc_item);
646 pub trait TestTrait {
647 const TEST_CONST: u8;
649 pub struct TestStruct {}
650 impl TestTrait for TestStruct {
651 const TEST_CONST: u8 = 42;
656 test_mod::TestStruct::TEST_CONST$0
661 pub trait TestTrait {
662 const TEST_CONST: u8;
664 pub struct TestStruct {}
665 impl TestTrait for TestStruct {
666 const TEST_CONST: u8 = 42;
671 <test_mod::TestStruct as test_mod::TestTrait>::TEST_CONST
678 fn not_applicable_for_imported_trait_for_const() {
679 check_assist_not_applicable(
683 pub trait TestTrait {
684 const TEST_CONST: u8;
686 pub trait TestTrait2 {
687 const TEST_CONST: f64;
693 impl TestTrait2 for TestEnum {
694 const TEST_CONST: f64 = 42.0;
696 impl TestTrait for TestEnum {
697 const TEST_CONST: u8 = 42;
701 use test_mod::TestTrait2;
703 test_mod::TestEnum::TEST_CONST$0;
711 cov_mark::check!(qualify_path_trait_method);
716 pub trait TestTrait {
717 fn test_method(&self);
719 pub struct TestStruct {}
720 impl TestTrait for TestStruct {
721 fn test_method(&self) {}
726 let test_struct = test_mod::TestStruct {};
727 test_struct.test_meth$0od()
732 pub trait TestTrait {
733 fn test_method(&self);
735 pub struct TestStruct {}
736 impl TestTrait for TestStruct {
737 fn test_method(&self) {}
742 let test_struct = test_mod::TestStruct {};
743 test_mod::TestTrait::test_method(&test_struct)
750 fn trait_method_multi_params() {
755 pub trait TestTrait {
756 fn test_method(&self, test: i32);
758 pub struct TestStruct {}
759 impl TestTrait for TestStruct {
760 fn test_method(&self, test: i32) {}
765 let test_struct = test_mod::TestStruct {};
766 test_struct.test_meth$0od(42)
771 pub trait TestTrait {
772 fn test_method(&self, test: i32);
774 pub struct TestStruct {}
775 impl TestTrait for TestStruct {
776 fn test_method(&self, test: i32) {}
781 let test_struct = test_mod::TestStruct {};
782 test_mod::TestTrait::test_method(&test_struct, 42)
789 fn trait_method_consume() {
794 pub trait TestTrait {
795 fn test_method(self);
797 pub struct TestStruct {}
798 impl TestTrait for TestStruct {
799 fn test_method(self) {}
804 let test_struct = test_mod::TestStruct {};
805 test_struct.test_meth$0od()
810 pub trait TestTrait {
811 fn test_method(self);
813 pub struct TestStruct {}
814 impl TestTrait for TestStruct {
815 fn test_method(self) {}
820 let test_struct = test_mod::TestStruct {};
821 test_mod::TestTrait::test_method(test_struct)
828 fn trait_method_cross_crate() {
832 //- /main.rs crate:main deps:dep
834 let test_struct = dep::test_mod::TestStruct {};
835 test_struct.test_meth$0od()
837 //- /dep.rs crate:dep
839 pub trait TestTrait {
840 fn test_method(&self);
842 pub struct TestStruct {}
843 impl TestTrait for TestStruct {
844 fn test_method(&self) {}
850 let test_struct = dep::test_mod::TestStruct {};
851 dep::test_mod::TestTrait::test_method(&test_struct)
858 fn assoc_fn_cross_crate() {
862 //- /main.rs crate:main deps:dep
864 dep::test_mod::TestStruct::test_func$0tion
866 //- /dep.rs crate:dep
868 pub trait TestTrait {
871 pub struct TestStruct {}
872 impl TestTrait for TestStruct {
873 fn test_function() {}
879 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::test_function
886 fn assoc_const_cross_crate() {
890 //- /main.rs crate:main deps:dep
892 dep::test_mod::TestStruct::CONST$0
894 //- /dep.rs crate:dep
896 pub trait TestTrait {
899 pub struct TestStruct {}
900 impl TestTrait for TestStruct {
901 const CONST: bool = true;
907 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::CONST
914 fn assoc_fn_as_method_cross_crate() {
915 check_assist_not_applicable(
918 //- /main.rs crate:main deps:dep
920 let test_struct = dep::test_mod::TestStruct {};
921 test_struct.test_func$0tion()
923 //- /dep.rs crate:dep
925 pub trait TestTrait {
928 pub struct TestStruct {}
929 impl TestTrait for TestStruct {
930 fn test_function() {}
938 fn private_trait_cross_crate() {
939 check_assist_not_applicable(
942 //- /main.rs crate:main deps:dep
944 let test_struct = dep::test_mod::TestStruct {};
945 test_struct.test_meth$0od()
947 //- /dep.rs crate:dep
950 fn test_method(&self);
952 pub struct TestStruct {}
953 impl TestTrait for TestStruct {
954 fn test_method(&self) {}
962 fn not_applicable_for_imported_trait_for_method() {
963 check_assist_not_applicable(
967 pub trait TestTrait {
968 fn test_method(&self);
970 pub trait TestTrait2 {
971 fn test_method(&self);
977 impl TestTrait2 for TestEnum {
978 fn test_method(&self) {}
980 impl TestTrait for TestEnum {
981 fn test_method(&self) {}
985 use test_mod::TestTrait2;
987 let one = test_mod::TestEnum::One;
999 //- /lib.rs crate:dep
1002 //- /main.rs crate:main deps:dep
1016 fn whole_segment() {
1017 // Tests that only imports whose last segment matches the identifier get suggested.
1021 //- /lib.rs crate:dep
1023 pub trait Display {}
1026 pub fn panic_fmt() {}
1028 //- /main.rs crate:main deps:dep
1031 impl f$0mt::Display for S {}
1036 impl dep::fmt::Display for S {}
1042 fn macro_generated() {
1043 // Tests that macro-generated items are suggested from external crates.
1047 //- /lib.rs crate:dep
1056 //- /main.rs crate:main deps:dep
1071 // Tests that differently cased names don't interfere and we only suggest the matching one.
1075 //- /lib.rs crate:dep
1079 //- /main.rs crate:main deps:dep
1093 fn keep_generic_annotations() {
1097 //- /lib.rs crate:dep
1098 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1100 //- /main.rs crate:main deps:dep
1101 fn foo() -> Thin$0g<'static, ()> {}
1106 fn foo() -> dep::generic::Thing<'static, ()> {}
1114 fn keep_generic_annotations_leading_colon() {
1118 //- /lib.rs crate:dep
1119 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1121 //- /main.rs crate:main deps:dep
1122 fn foo() -> Thin$0g::<'static, ()> {}
1127 fn foo() -> dep::generic::Thing::<'static, ()> {}
1135 fn associated_struct_const_generic() {
1140 pub struct TestStruct<T> {}
1141 impl<T> TestStruct<T> {
1142 const TEST_CONST: u8 = 42;
1147 TestStruct::<()>::TEST_CONST$0
1152 pub struct TestStruct<T> {}
1153 impl<T> TestStruct<T> {
1154 const TEST_CONST: u8 = 42;
1159 test_mod::TestStruct::<()>::TEST_CONST
1166 fn associated_trait_const_generic() {
1171 pub trait TestTrait {
1172 const TEST_CONST: u8;
1174 pub struct TestStruct<T> {}
1175 impl<T> TestTrait for TestStruct<T> {
1176 const TEST_CONST: u8 = 42;
1181 test_mod::TestStruct::<()>::TEST_CONST$0
1186 pub trait TestTrait {
1187 const TEST_CONST: u8;
1189 pub struct TestStruct<T> {}
1190 impl<T> TestTrait for TestStruct<T> {
1191 const TEST_CONST: u8 = 42;
1196 <test_mod::TestStruct::<()> as test_mod::TestTrait>::TEST_CONST
1203 fn trait_method_generic() {
1208 pub trait TestTrait {
1209 fn test_method<T>(&self);
1211 pub struct TestStruct {}
1212 impl TestTrait for TestStruct {
1213 fn test_method<T>(&self) {}
1218 let test_struct = test_mod::TestStruct {};
1219 test_struct.test_meth$0od::<()>()
1224 pub trait TestTrait {
1225 fn test_method<T>(&self);
1227 pub struct TestStruct {}
1228 impl TestTrait for TestStruct {
1229 fn test_method<T>(&self) {}
1234 let test_struct = test_mod::TestStruct {};
1235 test_mod::TestTrait::test_method::<()>(&test_struct)