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 = item.as_module_def()?;
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(qualify_path, r#"PubStruct$0"#);
361 fn not_applicable_in_import_statements() {
362 check_assist_not_applicable(
368 pub struct PubStruct;
375 fn qualify_function() {
382 pub fn test_function() {};
386 PubMod::test_function
389 pub fn test_function() {};
400 //- /lib.rs crate:crate_with_macro
406 //- /main.rs crate:main deps:crate_with_macro
413 crate_with_macro::foo
420 fn qualify_path_target() {
425 group_label: Option<$0GroupLabel>,
428 mod m { pub struct GroupLabel; }
435 fn not_applicable_when_path_start_is_imported() {
436 check_assist_not_applicable(
442 pub struct TestStruct;
449 mod2::mod3::TestStruct$0
456 fn not_applicable_for_imported_function() {
457 check_assist_not_applicable(
461 pub fn test_function() {}
464 use test_mod::test_function;
473 fn associated_struct_function() {
478 pub struct TestStruct {}
480 pub fn test_function() {}
485 TestStruct::test_function$0
490 pub struct TestStruct {}
492 pub fn test_function() {}
497 test_mod::TestStruct::test_function
504 fn associated_struct_const() {
505 cov_mark::check!(qualify_path_qualifier_start);
510 pub struct TestStruct {}
512 const TEST_CONST: u8 = 42;
517 TestStruct::TEST_CONST$0
522 pub struct TestStruct {}
524 const TEST_CONST: u8 = 42;
529 test_mod::TestStruct::TEST_CONST
536 fn associated_struct_const_unqualified() {
537 // FIXME: non-trait assoc items completion is unsupported yet, see FIXME in the import_assets.rs for more details
538 check_assist_not_applicable(
542 pub struct TestStruct {}
544 const TEST_CONST: u8 = 42;
556 fn associated_trait_function() {
561 pub trait TestTrait {
564 pub struct TestStruct {}
565 impl TestTrait for TestStruct {
566 fn test_function() {}
571 test_mod::TestStruct::test_function$0
576 pub trait TestTrait {
579 pub struct TestStruct {}
580 impl TestTrait for TestStruct {
581 fn test_function() {}
586 <test_mod::TestStruct as test_mod::TestTrait>::test_function
593 fn not_applicable_for_imported_trait_for_function() {
594 check_assist_not_applicable(
598 pub trait TestTrait {
601 pub trait TestTrait2 {
608 impl TestTrait2 for TestEnum {
609 fn test_function() {}
611 impl TestTrait for TestEnum {
612 fn test_function() {}
616 use test_mod::TestTrait2;
618 test_mod::TestEnum::test_function$0;
625 fn associated_trait_const() {
626 cov_mark::check!(qualify_path_trait_assoc_item);
631 pub trait TestTrait {
632 const TEST_CONST: u8;
634 pub struct TestStruct {}
635 impl TestTrait for TestStruct {
636 const TEST_CONST: u8 = 42;
641 test_mod::TestStruct::TEST_CONST$0
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 as test_mod::TestTrait>::TEST_CONST
663 fn not_applicable_for_imported_trait_for_const() {
664 check_assist_not_applicable(
668 pub trait TestTrait {
669 const TEST_CONST: u8;
671 pub trait TestTrait2 {
672 const TEST_CONST: f64;
678 impl TestTrait2 for TestEnum {
679 const TEST_CONST: f64 = 42.0;
681 impl TestTrait for TestEnum {
682 const TEST_CONST: u8 = 42;
686 use test_mod::TestTrait2;
688 test_mod::TestEnum::TEST_CONST$0;
696 cov_mark::check!(qualify_path_trait_method);
701 pub trait TestTrait {
702 fn test_method(&self);
704 pub struct TestStruct {}
705 impl TestTrait for TestStruct {
706 fn test_method(&self) {}
711 let test_struct = test_mod::TestStruct {};
712 test_struct.test_meth$0od()
717 pub trait TestTrait {
718 fn test_method(&self);
720 pub struct TestStruct {}
721 impl TestTrait for TestStruct {
722 fn test_method(&self) {}
727 let test_struct = test_mod::TestStruct {};
728 test_mod::TestTrait::test_method(&test_struct)
735 fn trait_method_multi_params() {
740 pub trait TestTrait {
741 fn test_method(&self, test: i32);
743 pub struct TestStruct {}
744 impl TestTrait for TestStruct {
745 fn test_method(&self, test: i32) {}
750 let test_struct = test_mod::TestStruct {};
751 test_struct.test_meth$0od(42)
756 pub trait TestTrait {
757 fn test_method(&self, test: i32);
759 pub struct TestStruct {}
760 impl TestTrait for TestStruct {
761 fn test_method(&self, test: i32) {}
766 let test_struct = test_mod::TestStruct {};
767 test_mod::TestTrait::test_method(&test_struct, 42)
774 fn trait_method_consume() {
779 pub trait TestTrait {
780 fn test_method(self);
782 pub struct TestStruct {}
783 impl TestTrait for TestStruct {
784 fn test_method(self) {}
789 let test_struct = test_mod::TestStruct {};
790 test_struct.test_meth$0od()
795 pub trait TestTrait {
796 fn test_method(self);
798 pub struct TestStruct {}
799 impl TestTrait for TestStruct {
800 fn test_method(self) {}
805 let test_struct = test_mod::TestStruct {};
806 test_mod::TestTrait::test_method(test_struct)
813 fn trait_method_cross_crate() {
817 //- /main.rs crate:main deps:dep
819 let test_struct = dep::test_mod::TestStruct {};
820 test_struct.test_meth$0od()
822 //- /dep.rs crate:dep
824 pub trait TestTrait {
825 fn test_method(&self);
827 pub struct TestStruct {}
828 impl TestTrait for TestStruct {
829 fn test_method(&self) {}
835 let test_struct = dep::test_mod::TestStruct {};
836 dep::test_mod::TestTrait::test_method(&test_struct)
843 fn assoc_fn_cross_crate() {
847 //- /main.rs crate:main deps:dep
849 dep::test_mod::TestStruct::test_func$0tion
851 //- /dep.rs crate:dep
853 pub trait TestTrait {
856 pub struct TestStruct {}
857 impl TestTrait for TestStruct {
858 fn test_function() {}
864 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::test_function
871 fn assoc_const_cross_crate() {
875 //- /main.rs crate:main deps:dep
877 dep::test_mod::TestStruct::CONST$0
879 //- /dep.rs crate:dep
881 pub trait TestTrait {
884 pub struct TestStruct {}
885 impl TestTrait for TestStruct {
886 const CONST: bool = true;
892 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::CONST
899 fn assoc_fn_as_method_cross_crate() {
900 check_assist_not_applicable(
903 //- /main.rs crate:main deps:dep
905 let test_struct = dep::test_mod::TestStruct {};
906 test_struct.test_func$0tion()
908 //- /dep.rs crate:dep
910 pub trait TestTrait {
913 pub struct TestStruct {}
914 impl TestTrait for TestStruct {
915 fn test_function() {}
923 fn private_trait_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_meth$0od()
932 //- /dep.rs crate:dep
935 fn test_method(&self);
937 pub struct TestStruct {}
938 impl TestTrait for TestStruct {
939 fn test_method(&self) {}
947 fn not_applicable_for_imported_trait_for_method() {
948 check_assist_not_applicable(
952 pub trait TestTrait {
953 fn test_method(&self);
955 pub trait TestTrait2 {
956 fn test_method(&self);
962 impl TestTrait2 for TestEnum {
963 fn test_method(&self) {}
965 impl TestTrait for TestEnum {
966 fn test_method(&self) {}
970 use test_mod::TestTrait2;
972 let one = test_mod::TestEnum::One;
984 //- /lib.rs crate:dep
987 //- /main.rs crate:main deps:dep
1001 fn whole_segment() {
1002 // Tests that only imports whose last segment matches the identifier get suggested.
1006 //- /lib.rs crate:dep
1008 pub trait Display {}
1011 pub fn panic_fmt() {}
1013 //- /main.rs crate:main deps:dep
1016 impl f$0mt::Display for S {}
1021 impl dep::fmt::Display for S {}
1027 fn macro_generated() {
1028 // Tests that macro-generated items are suggested from external crates.
1032 //- /lib.rs crate:dep
1041 //- /main.rs crate:main deps:dep
1056 // Tests that differently cased names don't interfere and we only suggest the matching one.
1060 //- /lib.rs crate:dep
1064 //- /main.rs crate:main deps:dep
1078 fn keep_generic_annotations() {
1082 //- /lib.rs crate:dep
1083 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1085 //- /main.rs crate:main deps:dep
1086 fn foo() -> Thin$0g<'static, ()> {}
1091 fn foo() -> dep::generic::Thing<'static, ()> {}
1099 fn keep_generic_annotations_leading_colon() {
1103 //- /lib.rs crate:dep
1104 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1106 //- /main.rs crate:main deps:dep
1107 fn foo() -> Thin$0g::<'static, ()> {}
1112 fn foo() -> dep::generic::Thing::<'static, ()> {}
1120 fn associated_struct_const_generic() {
1125 pub struct TestStruct<T> {}
1126 impl<T> TestStruct<T> {
1127 const TEST_CONST: u8 = 42;
1132 TestStruct::<()>::TEST_CONST$0
1137 pub struct TestStruct<T> {}
1138 impl<T> TestStruct<T> {
1139 const TEST_CONST: u8 = 42;
1144 test_mod::TestStruct::<()>::TEST_CONST
1151 fn associated_trait_const_generic() {
1156 pub trait TestTrait {
1157 const TEST_CONST: u8;
1159 pub struct TestStruct<T> {}
1160 impl<T> TestTrait for TestStruct<T> {
1161 const TEST_CONST: u8 = 42;
1166 test_mod::TestStruct::<()>::TEST_CONST$0
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::<()> as test_mod::TestTrait>::TEST_CONST
1188 fn trait_method_generic() {
1193 pub trait TestTrait {
1194 fn test_method<T>(&self);
1196 pub struct TestStruct {}
1197 impl TestTrait for TestStruct {
1198 fn test_method<T>(&self) {}
1203 let test_struct = test_mod::TestStruct {};
1204 test_struct.test_meth$0od::<()>()
1209 pub trait TestTrait {
1210 fn test_method<T>(&self);
1212 pub struct TestStruct {}
1213 impl TestTrait for TestStruct {
1214 fn test_method<T>(&self) {}
1219 let test_struct = test_mod::TestStruct {};
1220 test_mod::TestTrait::test_method::<()>(&test_struct)