5 import_assets::{ImportCandidate, Qualifier},
8 use ide_db::RootDatabase;
11 ast::{make, ArgListOwner},
16 assist_context::{AssistContext, Assists},
17 AssistId, AssistKind, GroupLabel,
20 use super::auto_import::find_importable_node;
22 // Assist: qualify_path
24 // If the name is unresolved, provides all possible qualified paths for it.
28 // let map = HashMap$0::new();
30 // # pub mod std { pub mod collections { pub struct HashMap { } } }
35 // let map = std::collections::HashMap::new();
37 // # pub mod std { pub mod collections { pub struct HashMap { } } }
39 pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
40 let (import_assets, syntax_under_caret) = find_importable_node(ctx)?;
41 let proposed_imports = import_assets.search_for_relative_paths(&ctx.sema);
42 if proposed_imports.is_empty() {
46 let candidate = import_assets.import_candidate();
47 let range = ctx.sema.original_range(&syntax_under_caret).range;
49 let qualify_candidate = match candidate {
50 ImportCandidate::Path(candidate) => {
51 if !matches!(candidate.qualifier, Qualifier::Absent) {
52 cov_mark::hit!(qualify_path_qualifier_start);
53 let path = ast::Path::cast(syntax_under_caret)?;
54 let (prev_segment, segment) = (path.qualifier()?.segment()?, path.segment()?);
55 QualifyCandidate::QualifierStart(segment, prev_segment.generic_arg_list())
57 cov_mark::hit!(qualify_path_unqualified_name);
58 let path = ast::Path::cast(syntax_under_caret)?;
59 let generics = path.segment()?.generic_arg_list();
60 QualifyCandidate::UnqualifiedName(generics)
63 ImportCandidate::TraitAssocItem(_) => {
64 cov_mark::hit!(qualify_path_trait_assoc_item);
65 let path = ast::Path::cast(syntax_under_caret)?;
66 let (qualifier, segment) = (path.qualifier()?, path.segment()?);
67 QualifyCandidate::TraitAssocItem(qualifier, segment)
69 ImportCandidate::TraitMethod(_) => {
70 cov_mark::hit!(qualify_path_trait_method);
71 let mcall_expr = ast::MethodCallExpr::cast(syntax_under_caret)?;
72 QualifyCandidate::TraitMethod(ctx.sema.db, mcall_expr)
76 let group_label = group_label(candidate);
77 for (import, item) in proposed_imports {
80 AssistId("qualify_path", AssistKind::QuickFix),
81 label(candidate, &import),
84 qualify_candidate.qualify(
85 |replace_with: String| builder.replace(range, replace_with),
95 enum QualifyCandidate<'db> {
96 QualifierStart(ast::PathSegment, Option<ast::GenericArgList>),
97 UnqualifiedName(Option<ast::GenericArgList>),
98 TraitAssocItem(ast::Path, ast::PathSegment),
99 TraitMethod(&'db RootDatabase, ast::MethodCallExpr),
102 impl QualifyCandidate<'_> {
103 fn qualify(&self, mut replacer: impl FnMut(String), import: hir::ModPath, item: hir::ItemInNs) {
104 let import = mod_path_to_ast(&import);
106 QualifyCandidate::QualifierStart(segment, generics) => {
107 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
108 replacer(format!("{}{}::{}", import, generics, segment));
110 QualifyCandidate::UnqualifiedName(generics) => {
111 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
112 replacer(format!("{}{}", import.to_string(), generics));
114 QualifyCandidate::TraitAssocItem(qualifier, segment) => {
115 replacer(format!("<{} as {}>::{}", qualifier, import, segment));
117 &QualifyCandidate::TraitMethod(db, ref mcall_expr) => {
118 Self::qualify_trait_method(db, mcall_expr, replacer, import, item);
123 fn qualify_trait_method(
125 mcall_expr: &ast::MethodCallExpr,
126 mut replacer: impl FnMut(String),
130 let receiver = mcall_expr.receiver()?;
131 let trait_method_name = mcall_expr.name_ref()?;
133 mcall_expr.generic_arg_list().as_ref().map_or_else(String::new, ToString::to_string);
134 let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args());
135 let trait_ = item_as_trait(db, item)?;
136 let method = find_trait_method(db, trait_, &trait_method_name)?;
137 if let Some(self_access) = method.self_param(db).map(|sp| sp.access(db)) {
138 let receiver = match self_access {
139 hir::Access::Shared => make::expr_ref(receiver, false),
140 hir::Access::Exclusive => make::expr_ref(receiver, true),
141 hir::Access::Owned => receiver,
149 Some(args) => make::arg_list(iter::once(receiver).chain(args)),
150 None => make::arg_list(iter::once(receiver)),
158 fn find_trait_method(
161 trait_method_name: &ast::NameRef,
162 ) -> Option<hir::Function> {
163 if let Some(hir::AssocItem::Function(method)) =
164 trait_.items(db).into_iter().find(|item: &hir::AssocItem| {
166 .map(|name| name.to_string() == trait_method_name.to_string())
176 fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option<hir::Trait> {
177 let item_module_def = hir::ModuleDef::from(item.as_module_def_id()?);
179 if let hir::ModuleDef::Trait(trait_) = item_module_def {
182 item_module_def.as_assoc_item(db)?.containing_trait(db)
186 fn group_label(candidate: &ImportCandidate) -> GroupLabel {
187 let name = match candidate {
188 ImportCandidate::Path(it) => &it.name,
189 ImportCandidate::TraitAssocItem(it) | ImportCandidate::TraitMethod(it) => &it.name,
192 GroupLabel(format!("Qualify {}", name))
195 fn label(candidate: &ImportCandidate, import: &hir::ModPath) -> String {
197 ImportCandidate::Path(candidate) => {
198 if !matches!(candidate.qualifier, Qualifier::Absent) {
199 format!("Qualify with `{}`", &import)
201 format!("Qualify as `{}`", &import)
204 ImportCandidate::TraitAssocItem(_) => format!("Qualify `{}`", &import),
205 ImportCandidate::TraitMethod(_) => format!("Qualify with cast as `{}`", &import),
211 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
216 fn applicable_when_found_an_import_partial() {
217 cov_mark::check!(qualify_path_unqualified_name);
223 pub struct Formatter;
234 pub struct Formatter;
246 fn applicable_when_found_an_import() {
253 pub struct PubStruct;
260 pub struct PubStruct;
267 fn applicable_in_macros() {
272 ($i:ident) => { fn foo(a: $i) {} }
277 pub struct PubStruct;
282 ($i:ident) => { fn foo(a: $i) {} }
284 foo!(PubMod::PubStruct);
287 pub struct PubStruct;
294 fn applicable_when_found_multiple_imports() {
301 pub struct PubStruct;
304 pub struct PubStruct;
307 pub struct PubStruct;
314 pub struct PubStruct;
317 pub struct PubStruct;
320 pub struct PubStruct;
327 fn not_applicable_for_already_imported_types() {
328 check_assist_not_applicable(
331 use PubMod::PubStruct;
336 pub struct PubStruct;
343 fn not_applicable_for_types_with_private_paths() {
344 check_assist_not_applicable(
350 struct PrivateStruct;
357 fn not_applicable_when_no_imports_found() {
358 check_assist_not_applicable(
366 fn not_applicable_in_import_statements() {
367 check_assist_not_applicable(
373 pub struct PubStruct;
379 fn qualify_function() {
386 pub fn test_function() {};
390 PubMod::test_function
393 pub fn test_function() {};
404 //- /lib.rs crate:crate_with_macro
410 //- /main.rs crate:main deps:crate_with_macro
417 crate_with_macro::foo
424 fn qualify_path_target() {
429 group_label: Option<$0GroupLabel>,
432 mod m { pub struct GroupLabel; }
439 fn not_applicable_when_path_start_is_imported() {
440 check_assist_not_applicable(
446 pub struct TestStruct;
453 mod2::mod3::TestStruct$0
460 fn not_applicable_for_imported_function() {
461 check_assist_not_applicable(
465 pub fn test_function() {}
468 use test_mod::test_function;
477 fn associated_struct_function() {
482 pub struct TestStruct {}
484 pub fn test_function() {}
489 TestStruct::test_function$0
494 pub struct TestStruct {}
496 pub fn test_function() {}
501 test_mod::TestStruct::test_function
508 fn associated_struct_const() {
509 cov_mark::check!(qualify_path_qualifier_start);
514 pub struct TestStruct {}
516 const TEST_CONST: u8 = 42;
521 TestStruct::TEST_CONST$0
526 pub struct TestStruct {}
528 const TEST_CONST: u8 = 42;
533 test_mod::TestStruct::TEST_CONST
540 fn associated_trait_function() {
545 pub trait TestTrait {
548 pub struct TestStruct {}
549 impl TestTrait for TestStruct {
550 fn test_function() {}
555 test_mod::TestStruct::test_function$0
560 pub trait TestTrait {
563 pub struct TestStruct {}
564 impl TestTrait for TestStruct {
565 fn test_function() {}
570 <test_mod::TestStruct as test_mod::TestTrait>::test_function
577 fn not_applicable_for_imported_trait_for_function() {
578 check_assist_not_applicable(
582 pub trait TestTrait {
585 pub trait TestTrait2 {
592 impl TestTrait2 for TestEnum {
593 fn test_function() {}
595 impl TestTrait for TestEnum {
596 fn test_function() {}
600 use test_mod::TestTrait2;
602 test_mod::TestEnum::test_function$0;
609 fn associated_trait_const() {
610 cov_mark::check!(qualify_path_trait_assoc_item);
615 pub trait TestTrait {
616 const TEST_CONST: u8;
618 pub struct TestStruct {}
619 impl TestTrait for TestStruct {
620 const TEST_CONST: u8 = 42;
625 test_mod::TestStruct::TEST_CONST$0
630 pub trait TestTrait {
631 const TEST_CONST: u8;
633 pub struct TestStruct {}
634 impl TestTrait for TestStruct {
635 const TEST_CONST: u8 = 42;
640 <test_mod::TestStruct as test_mod::TestTrait>::TEST_CONST
647 fn not_applicable_for_imported_trait_for_const() {
648 check_assist_not_applicable(
652 pub trait TestTrait {
653 const TEST_CONST: u8;
655 pub trait TestTrait2 {
656 const TEST_CONST: f64;
662 impl TestTrait2 for TestEnum {
663 const TEST_CONST: f64 = 42.0;
665 impl TestTrait for TestEnum {
666 const TEST_CONST: u8 = 42;
670 use test_mod::TestTrait2;
672 test_mod::TestEnum::TEST_CONST$0;
680 cov_mark::check!(qualify_path_trait_method);
685 pub trait TestTrait {
686 fn test_method(&self);
688 pub struct TestStruct {}
689 impl TestTrait for TestStruct {
690 fn test_method(&self) {}
695 let test_struct = test_mod::TestStruct {};
696 test_struct.test_meth$0od()
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_mod::TestTrait::test_method(&test_struct)
719 fn trait_method_multi_params() {
724 pub trait TestTrait {
725 fn test_method(&self, test: i32);
727 pub struct TestStruct {}
728 impl TestTrait for TestStruct {
729 fn test_method(&self, test: i32) {}
734 let test_struct = test_mod::TestStruct {};
735 test_struct.test_meth$0od(42)
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_mod::TestTrait::test_method(&test_struct, 42)
758 fn trait_method_consume() {
763 pub trait TestTrait {
764 fn test_method(self);
766 pub struct TestStruct {}
767 impl TestTrait for TestStruct {
768 fn test_method(self) {}
773 let test_struct = test_mod::TestStruct {};
774 test_struct.test_meth$0od()
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_mod::TestTrait::test_method(test_struct)
797 fn trait_method_cross_crate() {
801 //- /main.rs crate:main deps:dep
803 let test_struct = dep::test_mod::TestStruct {};
804 test_struct.test_meth$0od()
806 //- /dep.rs crate:dep
808 pub trait TestTrait {
809 fn test_method(&self);
811 pub struct TestStruct {}
812 impl TestTrait for TestStruct {
813 fn test_method(&self) {}
819 let test_struct = dep::test_mod::TestStruct {};
820 dep::test_mod::TestTrait::test_method(&test_struct)
827 fn assoc_fn_cross_crate() {
831 //- /main.rs crate:main deps:dep
833 dep::test_mod::TestStruct::test_func$0tion
835 //- /dep.rs crate:dep
837 pub trait TestTrait {
840 pub struct TestStruct {}
841 impl TestTrait for TestStruct {
842 fn test_function() {}
848 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::test_function
855 fn assoc_const_cross_crate() {
859 //- /main.rs crate:main deps:dep
861 dep::test_mod::TestStruct::CONST$0
863 //- /dep.rs crate:dep
865 pub trait TestTrait {
868 pub struct TestStruct {}
869 impl TestTrait for TestStruct {
870 const CONST: bool = true;
876 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::CONST
883 fn assoc_fn_as_method_cross_crate() {
884 check_assist_not_applicable(
887 //- /main.rs crate:main deps:dep
889 let test_struct = dep::test_mod::TestStruct {};
890 test_struct.test_func$0tion()
892 //- /dep.rs crate:dep
894 pub trait TestTrait {
897 pub struct TestStruct {}
898 impl TestTrait for TestStruct {
899 fn test_function() {}
907 fn private_trait_cross_crate() {
908 check_assist_not_applicable(
911 //- /main.rs crate:main deps:dep
913 let test_struct = dep::test_mod::TestStruct {};
914 test_struct.test_meth$0od()
916 //- /dep.rs crate:dep
919 fn test_method(&self);
921 pub struct TestStruct {}
922 impl TestTrait for TestStruct {
923 fn test_method(&self) {}
931 fn not_applicable_for_imported_trait_for_method() {
932 check_assist_not_applicable(
936 pub trait TestTrait {
937 fn test_method(&self);
939 pub trait TestTrait2 {
940 fn test_method(&self);
946 impl TestTrait2 for TestEnum {
947 fn test_method(&self) {}
949 impl TestTrait for TestEnum {
950 fn test_method(&self) {}
954 use test_mod::TestTrait2;
956 let one = test_mod::TestEnum::One;
968 //- /lib.rs crate:dep
971 //- /main.rs crate:main deps:dep
986 // Tests that only imports whose last segment matches the identifier get suggested.
990 //- /lib.rs crate:dep
995 pub fn panic_fmt() {}
997 //- /main.rs crate:main deps:dep
1000 impl f$0mt::Display for S {}
1005 impl dep::fmt::Display for S {}
1011 fn macro_generated() {
1012 // Tests that macro-generated items are suggested from external crates.
1016 //- /lib.rs crate:dep
1025 //- /main.rs crate:main deps:dep
1040 // Tests that differently cased names don't interfere and we only suggest the matching one.
1044 //- /lib.rs crate:dep
1048 //- /main.rs crate:main deps:dep
1062 fn keep_generic_annotations() {
1066 //- /lib.rs crate:dep
1067 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1069 //- /main.rs crate:main deps:dep
1070 fn foo() -> Thin$0g<'static, ()> {}
1075 fn foo() -> dep::generic::Thing<'static, ()> {}
1083 fn keep_generic_annotations_leading_colon() {
1087 //- /lib.rs crate:dep
1088 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1090 //- /main.rs crate:main deps:dep
1091 fn foo() -> Thin$0g::<'static, ()> {}
1096 fn foo() -> dep::generic::Thing::<'static, ()> {}
1104 fn associated_struct_const_generic() {
1109 pub struct TestStruct<T> {}
1110 impl<T> TestStruct<T> {
1111 const TEST_CONST: u8 = 42;
1116 TestStruct::<()>::TEST_CONST$0
1121 pub struct TestStruct<T> {}
1122 impl<T> TestStruct<T> {
1123 const TEST_CONST: u8 = 42;
1128 test_mod::TestStruct::<()>::TEST_CONST
1135 fn associated_trait_const_generic() {
1140 pub trait TestTrait {
1141 const TEST_CONST: u8;
1143 pub struct TestStruct<T> {}
1144 impl<T> TestTrait for TestStruct<T> {
1145 const TEST_CONST: u8 = 42;
1150 test_mod::TestStruct::<()>::TEST_CONST$0
1155 pub trait TestTrait {
1156 const TEST_CONST: u8;
1158 pub struct TestStruct<T> {}
1159 impl<T> TestTrait for TestStruct<T> {
1160 const TEST_CONST: u8 = 42;
1165 <test_mod::TestStruct::<()> as test_mod::TestTrait>::TEST_CONST
1172 fn trait_method_generic() {
1177 pub trait TestTrait {
1178 fn test_method<T>(&self);
1180 pub struct TestStruct {}
1181 impl TestTrait for TestStruct {
1182 fn test_method<T>(&self) {}
1187 let test_struct = test_mod::TestStruct {};
1188 test_struct.test_meth$0od::<()>()
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_mod::TestTrait::test_method::<()>(&test_struct)