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)?;
41 let mut proposed_imports = import_assets.search_for_relative_paths(&ctx.sema);
42 if proposed_imports.is_empty() {
46 let range = ctx.sema.original_range(&syntax_under_caret).range;
47 let candidate = import_assets.import_candidate();
48 let qualify_candidate = match candidate {
49 ImportCandidate::Path(candidate) if candidate.qualifier.is_some() => {
50 cov_mark::hit!(qualify_path_qualifier_start);
51 let path = ast::Path::cast(syntax_under_caret)?;
52 let (prev_segment, segment) = (path.qualifier()?.segment()?, path.segment()?);
53 QualifyCandidate::QualifierStart(segment, prev_segment.generic_arg_list())
55 ImportCandidate::Path(_) => {
56 cov_mark::hit!(qualify_path_unqualified_name);
57 let path = ast::Path::cast(syntax_under_caret)?;
58 let generics = path.segment()?.generic_arg_list();
59 QualifyCandidate::UnqualifiedName(generics)
61 ImportCandidate::TraitAssocItem(_) => {
62 cov_mark::hit!(qualify_path_trait_assoc_item);
63 let path = ast::Path::cast(syntax_under_caret)?;
64 let (qualifier, segment) = (path.qualifier()?, path.segment()?);
65 QualifyCandidate::TraitAssocItem(qualifier, segment)
67 ImportCandidate::TraitMethod(_) => {
68 cov_mark::hit!(qualify_path_trait_method);
69 let mcall_expr = ast::MethodCallExpr::cast(syntax_under_caret)?;
70 QualifyCandidate::TraitMethod(ctx.sema.db, mcall_expr)
74 // we aren't interested in different namespaces
75 proposed_imports.dedup_by(|a, b| a.import_path == b.import_path);
77 let group_label = group_label(candidate);
78 for import in proposed_imports {
81 AssistId("qualify_path", AssistKind::QuickFix),
82 label(candidate, &import),
85 qualify_candidate.qualify(
86 |replace_with: String| builder.replace(range, replace_with),
88 import.item_to_import,
96 pub(crate) enum QualifyCandidate<'db> {
97 QualifierStart(ast::PathSegment, Option<ast::GenericArgList>),
98 UnqualifiedName(Option<ast::GenericArgList>),
99 TraitAssocItem(ast::Path, ast::PathSegment),
100 TraitMethod(&'db RootDatabase, ast::MethodCallExpr),
101 ImplMethod(&'db RootDatabase, ast::MethodCallExpr, hir::Function),
104 impl QualifyCandidate<'_> {
105 pub(crate) fn qualify(
107 mut replacer: impl FnMut(String),
108 import: &hir::ModPath,
111 let import = mod_path_to_ast(import);
113 QualifyCandidate::QualifierStart(segment, generics) => {
114 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
115 replacer(format!("{}{}::{}", import, generics, segment));
117 QualifyCandidate::UnqualifiedName(generics) => {
118 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
119 replacer(format!("{}{}", import.to_string(), generics));
121 QualifyCandidate::TraitAssocItem(qualifier, segment) => {
122 replacer(format!("<{} as {}>::{}", qualifier, import, segment));
124 QualifyCandidate::TraitMethod(db, mcall_expr) => {
125 Self::qualify_trait_method(db, mcall_expr, replacer, import, item);
127 QualifyCandidate::ImplMethod(db, mcall_expr, hir_fn) => {
128 Self::qualify_fn_call(db, mcall_expr, replacer, import, hir_fn);
135 mcall_expr: &ast::MethodCallExpr,
136 mut replacer: impl FnMut(String),
138 hir_fn: &hir::Function,
140 let receiver = mcall_expr.receiver()?;
141 let method_name = mcall_expr.name_ref()?;
143 mcall_expr.generic_arg_list().as_ref().map_or_else(String::new, ToString::to_string);
144 let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args());
146 if let Some(self_access) = hir_fn.self_param(db).map(|sp| sp.access(db)) {
147 let receiver = match self_access {
148 hir::Access::Shared => make::expr_ref(receiver, false),
149 hir::Access::Exclusive => make::expr_ref(receiver, true),
150 hir::Access::Owned => receiver,
158 Some(args) => make::arg_list(iter::once(receiver).chain(args)),
159 None => make::arg_list(iter::once(receiver)),
166 fn qualify_trait_method(
168 mcall_expr: &ast::MethodCallExpr,
169 replacer: impl FnMut(String),
173 let trait_method_name = mcall_expr.name_ref()?;
174 let trait_ = item_as_trait(db, item)?;
175 let method = find_trait_method(db, trait_, &trait_method_name)?;
176 Self::qualify_fn_call(db, mcall_expr, replacer, import, &method);
181 fn find_trait_method(
184 trait_method_name: &ast::NameRef,
185 ) -> Option<hir::Function> {
186 if let Some(hir::AssocItem::Function(method)) =
187 trait_.items(db).into_iter().find(|item: &hir::AssocItem| {
189 .map(|name| name.to_string() == trait_method_name.to_string())
199 fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option<hir::Trait> {
200 let item_module_def = item.as_module_def()?;
202 match item_module_def {
203 hir::ModuleDef::Trait(trait_) => Some(trait_),
204 _ => item_module_def.as_assoc_item(db)?.containing_trait(db),
208 fn group_label(candidate: &ImportCandidate) -> GroupLabel {
209 let name = match candidate {
210 ImportCandidate::Path(it) => &it.name,
211 ImportCandidate::TraitAssocItem(it) | ImportCandidate::TraitMethod(it) => {
216 GroupLabel(format!("Qualify {}", name))
219 fn label(candidate: &ImportCandidate, import: &LocatedImport) -> String {
221 ImportCandidate::Path(candidate) if candidate.qualifier.is_none() => {
222 format!("Qualify as `{}`", import.import_path)
224 _ => format!("Qualify with `{}`", import.import_path),
230 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
235 fn applicable_when_found_an_import_partial() {
236 cov_mark::check!(qualify_path_unqualified_name);
242 pub struct Formatter;
253 pub struct Formatter;
265 fn applicable_when_found_an_import() {
272 pub struct PubStruct;
279 pub struct PubStruct;
286 fn applicable_in_macros() {
291 ($i:ident) => { fn foo(a: $i) {} }
296 pub struct PubStruct;
301 ($i:ident) => { fn foo(a: $i) {} }
303 foo!(PubMod::PubStruct);
306 pub struct PubStruct;
313 fn applicable_when_found_multiple_imports() {
320 pub struct PubStruct;
323 pub struct PubStruct;
326 pub struct PubStruct;
333 pub struct PubStruct;
336 pub struct PubStruct;
339 pub struct PubStruct;
346 fn not_applicable_for_already_imported_types() {
347 check_assist_not_applicable(
350 use PubMod::PubStruct;
355 pub struct PubStruct;
362 fn not_applicable_for_types_with_private_paths() {
363 check_assist_not_applicable(
369 struct PrivateStruct;
376 fn not_applicable_when_no_imports_found() {
377 check_assist_not_applicable(qualify_path, r#"PubStruct$0"#);
381 fn not_applicable_in_import_statements() {
382 check_assist_not_applicable(
388 pub struct PubStruct;
395 fn qualify_function() {
402 pub fn test_function() {};
406 PubMod::test_function
409 pub fn test_function() {};
420 //- /lib.rs crate:crate_with_macro
426 //- /main.rs crate:main deps:crate_with_macro
433 crate_with_macro::foo
440 fn qualify_path_target() {
445 group_label: Option<$0GroupLabel>,
448 mod m { pub struct GroupLabel; }
455 fn not_applicable_when_path_start_is_imported() {
456 check_assist_not_applicable(
462 pub struct TestStruct;
469 mod2::mod3::TestStruct$0
476 fn not_applicable_for_imported_function() {
477 check_assist_not_applicable(
481 pub fn test_function() {}
484 use test_mod::test_function;
493 fn associated_struct_function() {
498 pub struct TestStruct {}
500 pub fn test_function() {}
505 TestStruct::test_function$0
510 pub struct TestStruct {}
512 pub fn test_function() {}
517 test_mod::TestStruct::test_function
524 fn associated_struct_const() {
525 cov_mark::check!(qualify_path_qualifier_start);
530 pub struct TestStruct {}
532 const TEST_CONST: u8 = 42;
537 TestStruct::TEST_CONST$0
542 pub struct TestStruct {}
544 const TEST_CONST: u8 = 42;
549 test_mod::TestStruct::TEST_CONST
556 fn associated_struct_const_unqualified() {
557 // FIXME: non-trait assoc items completion is unsupported yet, see FIXME in the import_assets.rs for more details
558 check_assist_not_applicable(
562 pub struct TestStruct {}
564 const TEST_CONST: u8 = 42;
576 fn associated_trait_function() {
581 pub trait TestTrait {
584 pub struct TestStruct {}
585 impl TestTrait for TestStruct {
586 fn test_function() {}
591 test_mod::TestStruct::test_function$0
596 pub trait TestTrait {
599 pub struct TestStruct {}
600 impl TestTrait for TestStruct {
601 fn test_function() {}
606 <test_mod::TestStruct as test_mod::TestTrait>::test_function
613 fn not_applicable_for_imported_trait_for_function() {
614 check_assist_not_applicable(
618 pub trait TestTrait {
621 pub trait TestTrait2 {
628 impl TestTrait2 for TestEnum {
629 fn test_function() {}
631 impl TestTrait for TestEnum {
632 fn test_function() {}
636 use test_mod::TestTrait2;
638 test_mod::TestEnum::test_function$0;
645 fn associated_trait_const() {
646 cov_mark::check!(qualify_path_trait_assoc_item);
651 pub trait TestTrait {
652 const TEST_CONST: u8;
654 pub struct TestStruct {}
655 impl TestTrait for TestStruct {
656 const TEST_CONST: u8 = 42;
661 test_mod::TestStruct::TEST_CONST$0
666 pub trait TestTrait {
667 const TEST_CONST: u8;
669 pub struct TestStruct {}
670 impl TestTrait for TestStruct {
671 const TEST_CONST: u8 = 42;
676 <test_mod::TestStruct as test_mod::TestTrait>::TEST_CONST
683 fn not_applicable_for_imported_trait_for_const() {
684 check_assist_not_applicable(
688 pub trait TestTrait {
689 const TEST_CONST: u8;
691 pub trait TestTrait2 {
692 const TEST_CONST: f64;
698 impl TestTrait2 for TestEnum {
699 const TEST_CONST: f64 = 42.0;
701 impl TestTrait for TestEnum {
702 const TEST_CONST: u8 = 42;
706 use test_mod::TestTrait2;
708 test_mod::TestEnum::TEST_CONST$0;
716 cov_mark::check!(qualify_path_trait_method);
721 pub trait TestTrait {
722 fn test_method(&self);
724 pub struct TestStruct {}
725 impl TestTrait for TestStruct {
726 fn test_method(&self) {}
731 let test_struct = test_mod::TestStruct {};
732 test_struct.test_meth$0od()
737 pub trait TestTrait {
738 fn test_method(&self);
740 pub struct TestStruct {}
741 impl TestTrait for TestStruct {
742 fn test_method(&self) {}
747 let test_struct = test_mod::TestStruct {};
748 test_mod::TestTrait::test_method(&test_struct)
755 fn trait_method_multi_params() {
760 pub trait TestTrait {
761 fn test_method(&self, test: i32);
763 pub struct TestStruct {}
764 impl TestTrait for TestStruct {
765 fn test_method(&self, test: i32) {}
770 let test_struct = test_mod::TestStruct {};
771 test_struct.test_meth$0od(42)
776 pub trait TestTrait {
777 fn test_method(&self, test: i32);
779 pub struct TestStruct {}
780 impl TestTrait for TestStruct {
781 fn test_method(&self, test: i32) {}
786 let test_struct = test_mod::TestStruct {};
787 test_mod::TestTrait::test_method(&test_struct, 42)
794 fn trait_method_consume() {
799 pub trait TestTrait {
800 fn test_method(self);
802 pub struct TestStruct {}
803 impl TestTrait for TestStruct {
804 fn test_method(self) {}
809 let test_struct = test_mod::TestStruct {};
810 test_struct.test_meth$0od()
815 pub trait TestTrait {
816 fn test_method(self);
818 pub struct TestStruct {}
819 impl TestTrait for TestStruct {
820 fn test_method(self) {}
825 let test_struct = test_mod::TestStruct {};
826 test_mod::TestTrait::test_method(test_struct)
833 fn trait_method_cross_crate() {
837 //- /main.rs crate:main deps:dep
839 let test_struct = dep::test_mod::TestStruct {};
840 test_struct.test_meth$0od()
842 //- /dep.rs crate:dep
844 pub trait TestTrait {
845 fn test_method(&self);
847 pub struct TestStruct {}
848 impl TestTrait for TestStruct {
849 fn test_method(&self) {}
855 let test_struct = dep::test_mod::TestStruct {};
856 dep::test_mod::TestTrait::test_method(&test_struct)
863 fn assoc_fn_cross_crate() {
867 //- /main.rs crate:main deps:dep
869 dep::test_mod::TestStruct::test_func$0tion
871 //- /dep.rs crate:dep
873 pub trait TestTrait {
876 pub struct TestStruct {}
877 impl TestTrait for TestStruct {
878 fn test_function() {}
884 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::test_function
891 fn assoc_const_cross_crate() {
895 //- /main.rs crate:main deps:dep
897 dep::test_mod::TestStruct::CONST$0
899 //- /dep.rs crate:dep
901 pub trait TestTrait {
904 pub struct TestStruct {}
905 impl TestTrait for TestStruct {
906 const CONST: bool = true;
912 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::CONST
919 fn assoc_fn_as_method_cross_crate() {
920 check_assist_not_applicable(
923 //- /main.rs crate:main deps:dep
925 let test_struct = dep::test_mod::TestStruct {};
926 test_struct.test_func$0tion()
928 //- /dep.rs crate:dep
930 pub trait TestTrait {
933 pub struct TestStruct {}
934 impl TestTrait for TestStruct {
935 fn test_function() {}
943 fn private_trait_cross_crate() {
944 check_assist_not_applicable(
947 //- /main.rs crate:main deps:dep
949 let test_struct = dep::test_mod::TestStruct {};
950 test_struct.test_meth$0od()
952 //- /dep.rs crate:dep
955 fn test_method(&self);
957 pub struct TestStruct {}
958 impl TestTrait for TestStruct {
959 fn test_method(&self) {}
967 fn not_applicable_for_imported_trait_for_method() {
968 check_assist_not_applicable(
972 pub trait TestTrait {
973 fn test_method(&self);
975 pub trait TestTrait2 {
976 fn test_method(&self);
982 impl TestTrait2 for TestEnum {
983 fn test_method(&self) {}
985 impl TestTrait for TestEnum {
986 fn test_method(&self) {}
990 use test_mod::TestTrait2;
992 let one = test_mod::TestEnum::One;
1004 //- /lib.rs crate:dep
1007 //- /main.rs crate:main deps:dep
1021 fn whole_segment() {
1022 // Tests that only imports whose last segment matches the identifier get suggested.
1026 //- /lib.rs crate:dep
1028 pub trait Display {}
1031 pub fn panic_fmt() {}
1033 //- /main.rs crate:main deps:dep
1036 impl f$0mt::Display for S {}
1041 impl dep::fmt::Display for S {}
1047 fn macro_generated() {
1048 // Tests that macro-generated items are suggested from external crates.
1052 //- /lib.rs crate:dep
1061 //- /main.rs crate:main deps:dep
1076 // Tests that differently cased names don't interfere and we only suggest the matching one.
1080 //- /lib.rs crate:dep
1084 //- /main.rs crate:main deps:dep
1098 fn keep_generic_annotations() {
1102 //- /lib.rs crate:dep
1103 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1105 //- /main.rs crate:main deps:dep
1106 fn foo() -> Thin$0g<'static, ()> {}
1111 fn foo() -> dep::generic::Thing<'static, ()> {}
1119 fn keep_generic_annotations_leading_colon() {
1123 //- /lib.rs crate:dep
1124 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1126 //- /main.rs crate:main deps:dep
1127 fn foo() -> Thin$0g::<'static, ()> {}
1132 fn foo() -> dep::generic::Thing::<'static, ()> {}
1140 fn associated_struct_const_generic() {
1145 pub struct TestStruct<T> {}
1146 impl<T> TestStruct<T> {
1147 const TEST_CONST: u8 = 42;
1152 TestStruct::<()>::TEST_CONST$0
1157 pub struct TestStruct<T> {}
1158 impl<T> TestStruct<T> {
1159 const TEST_CONST: u8 = 42;
1164 test_mod::TestStruct::<()>::TEST_CONST
1171 fn associated_trait_const_generic() {
1176 pub trait TestTrait {
1177 const TEST_CONST: u8;
1179 pub struct TestStruct<T> {}
1180 impl<T> TestTrait for TestStruct<T> {
1181 const TEST_CONST: u8 = 42;
1186 test_mod::TestStruct::<()>::TEST_CONST$0
1191 pub trait TestTrait {
1192 const TEST_CONST: u8;
1194 pub struct TestStruct<T> {}
1195 impl<T> TestTrait for TestStruct<T> {
1196 const TEST_CONST: u8 = 42;
1201 <test_mod::TestStruct::<()> as test_mod::TestTrait>::TEST_CONST
1208 fn trait_method_generic() {
1213 pub trait TestTrait {
1214 fn test_method<T>(&self);
1216 pub struct TestStruct {}
1217 impl TestTrait for TestStruct {
1218 fn test_method<T>(&self) {}
1223 let test_struct = test_mod::TestStruct {};
1224 test_struct.test_meth$0od::<()>()
1229 pub trait TestTrait {
1230 fn test_method<T>(&self);
1232 pub struct TestStruct {}
1233 impl TestTrait for TestStruct {
1234 fn test_method<T>(&self) {}
1239 let test_struct = test_mod::TestStruct {};
1240 test_mod::TestTrait::test_method::<()>(&test_struct)