5 import_assets::{ImportCandidate, LocatedImport},
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 candidate.qualifier.is_some() {
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 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),
87 import.item_to_import,
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<'_> {
105 mut replacer: impl FnMut(String),
106 import: &hir::ModPath,
109 let import = mod_path_to_ast(import);
111 QualifyCandidate::QualifierStart(segment, generics) => {
112 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
113 replacer(format!("{}{}::{}", import, generics, segment));
115 QualifyCandidate::UnqualifiedName(generics) => {
116 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
117 replacer(format!("{}{}", import.to_string(), generics));
119 QualifyCandidate::TraitAssocItem(qualifier, segment) => {
120 replacer(format!("<{} as {}>::{}", qualifier, import, segment));
122 &QualifyCandidate::TraitMethod(db, ref mcall_expr) => {
123 Self::qualify_trait_method(db, mcall_expr, replacer, import, item);
128 fn qualify_trait_method(
130 mcall_expr: &ast::MethodCallExpr,
131 mut replacer: impl FnMut(String),
135 let receiver = mcall_expr.receiver()?;
136 let trait_method_name = mcall_expr.name_ref()?;
138 mcall_expr.generic_arg_list().as_ref().map_or_else(String::new, ToString::to_string);
139 let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args());
140 let trait_ = item_as_trait(db, item)?;
141 let method = find_trait_method(db, trait_, &trait_method_name)?;
142 if let Some(self_access) = method.self_param(db).map(|sp| sp.access(db)) {
143 let receiver = match self_access {
144 hir::Access::Shared => make::expr_ref(receiver, false),
145 hir::Access::Exclusive => make::expr_ref(receiver, true),
146 hir::Access::Owned => receiver,
154 Some(args) => make::arg_list(iter::once(receiver).chain(args)),
155 None => make::arg_list(iter::once(receiver)),
163 fn find_trait_method(
166 trait_method_name: &ast::NameRef,
167 ) -> Option<hir::Function> {
168 if let Some(hir::AssocItem::Function(method)) =
169 trait_.items(db).into_iter().find(|item: &hir::AssocItem| {
171 .map(|name| name.to_string() == trait_method_name.to_string())
181 fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option<hir::Trait> {
182 let item_module_def = hir::ModuleDef::from(item.as_module_def_id()?);
184 if let hir::ModuleDef::Trait(trait_) = item_module_def {
187 item_module_def.as_assoc_item(db)?.containing_trait(db)
191 fn group_label(candidate: &ImportCandidate) -> GroupLabel {
192 let name = match candidate {
193 ImportCandidate::Path(it) => &it.name,
194 ImportCandidate::TraitAssocItem(it) | ImportCandidate::TraitMethod(it) => {
199 GroupLabel(format!("Qualify {}", name))
202 fn label(candidate: &ImportCandidate, import: &LocatedImport) -> String {
204 ImportCandidate::Path(candidate) => {
205 if candidate.qualifier.is_some() {
206 format!("Qualify with `{}`", import.import_path)
208 format!("Qualify as `{}`", import.import_path)
211 ImportCandidate::TraitAssocItem(_) => format!("Qualify `{}`", import.import_path),
212 ImportCandidate::TraitMethod(_) => format!("Qualify with cast as `{}`", import.import_path),
218 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
223 fn applicable_when_found_an_import_partial() {
224 cov_mark::check!(qualify_path_unqualified_name);
230 pub struct Formatter;
241 pub struct Formatter;
253 fn applicable_when_found_an_import() {
260 pub struct PubStruct;
267 pub struct PubStruct;
274 fn applicable_in_macros() {
279 ($i:ident) => { fn foo(a: $i) {} }
284 pub struct PubStruct;
289 ($i:ident) => { fn foo(a: $i) {} }
291 foo!(PubMod::PubStruct);
294 pub struct PubStruct;
301 fn applicable_when_found_multiple_imports() {
308 pub struct PubStruct;
311 pub struct PubStruct;
314 pub struct PubStruct;
321 pub struct PubStruct;
324 pub struct PubStruct;
327 pub struct PubStruct;
334 fn not_applicable_for_already_imported_types() {
335 check_assist_not_applicable(
338 use PubMod::PubStruct;
343 pub struct PubStruct;
350 fn not_applicable_for_types_with_private_paths() {
351 check_assist_not_applicable(
357 struct PrivateStruct;
364 fn not_applicable_when_no_imports_found() {
365 check_assist_not_applicable(
373 fn not_applicable_in_import_statements() {
374 check_assist_not_applicable(
380 pub struct PubStruct;
386 fn qualify_function() {
393 pub fn test_function() {};
397 PubMod::test_function
400 pub fn test_function() {};
411 //- /lib.rs crate:crate_with_macro
417 //- /main.rs crate:main deps:crate_with_macro
424 crate_with_macro::foo
431 fn qualify_path_target() {
436 group_label: Option<$0GroupLabel>,
439 mod m { pub struct GroupLabel; }
446 fn not_applicable_when_path_start_is_imported() {
447 check_assist_not_applicable(
453 pub struct TestStruct;
460 mod2::mod3::TestStruct$0
467 fn not_applicable_for_imported_function() {
468 check_assist_not_applicable(
472 pub fn test_function() {}
475 use test_mod::test_function;
484 fn associated_struct_function() {
489 pub struct TestStruct {}
491 pub fn test_function() {}
496 TestStruct::test_function$0
501 pub struct TestStruct {}
503 pub fn test_function() {}
508 test_mod::TestStruct::test_function
515 fn associated_struct_const() {
516 cov_mark::check!(qualify_path_qualifier_start);
521 pub struct TestStruct {}
523 const TEST_CONST: u8 = 42;
528 TestStruct::TEST_CONST$0
533 pub struct TestStruct {}
535 const TEST_CONST: u8 = 42;
540 test_mod::TestStruct::TEST_CONST
547 fn associated_trait_function() {
552 pub trait TestTrait {
555 pub struct TestStruct {}
556 impl TestTrait for TestStruct {
557 fn test_function() {}
562 test_mod::TestStruct::test_function$0
567 pub trait TestTrait {
570 pub struct TestStruct {}
571 impl TestTrait for TestStruct {
572 fn test_function() {}
577 <test_mod::TestStruct as test_mod::TestTrait>::test_function
584 fn not_applicable_for_imported_trait_for_function() {
585 check_assist_not_applicable(
589 pub trait TestTrait {
592 pub trait TestTrait2 {
599 impl TestTrait2 for TestEnum {
600 fn test_function() {}
602 impl TestTrait for TestEnum {
603 fn test_function() {}
607 use test_mod::TestTrait2;
609 test_mod::TestEnum::test_function$0;
616 fn associated_trait_const() {
617 cov_mark::check!(qualify_path_trait_assoc_item);
622 pub trait TestTrait {
623 const TEST_CONST: u8;
625 pub struct TestStruct {}
626 impl TestTrait for TestStruct {
627 const TEST_CONST: u8 = 42;
632 test_mod::TestStruct::TEST_CONST$0
637 pub trait TestTrait {
638 const TEST_CONST: u8;
640 pub struct TestStruct {}
641 impl TestTrait for TestStruct {
642 const TEST_CONST: u8 = 42;
647 <test_mod::TestStruct as test_mod::TestTrait>::TEST_CONST
654 fn not_applicable_for_imported_trait_for_const() {
655 check_assist_not_applicable(
659 pub trait TestTrait {
660 const TEST_CONST: u8;
662 pub trait TestTrait2 {
663 const TEST_CONST: f64;
669 impl TestTrait2 for TestEnum {
670 const TEST_CONST: f64 = 42.0;
672 impl TestTrait for TestEnum {
673 const TEST_CONST: u8 = 42;
677 use test_mod::TestTrait2;
679 test_mod::TestEnum::TEST_CONST$0;
687 cov_mark::check!(qualify_path_trait_method);
692 pub trait TestTrait {
693 fn test_method(&self);
695 pub struct TestStruct {}
696 impl TestTrait for TestStruct {
697 fn test_method(&self) {}
702 let test_struct = test_mod::TestStruct {};
703 test_struct.test_meth$0od()
708 pub trait TestTrait {
709 fn test_method(&self);
711 pub struct TestStruct {}
712 impl TestTrait for TestStruct {
713 fn test_method(&self) {}
718 let test_struct = test_mod::TestStruct {};
719 test_mod::TestTrait::test_method(&test_struct)
726 fn trait_method_multi_params() {
731 pub trait TestTrait {
732 fn test_method(&self, test: i32);
734 pub struct TestStruct {}
735 impl TestTrait for TestStruct {
736 fn test_method(&self, test: i32) {}
741 let test_struct = test_mod::TestStruct {};
742 test_struct.test_meth$0od(42)
747 pub trait TestTrait {
748 fn test_method(&self, test: i32);
750 pub struct TestStruct {}
751 impl TestTrait for TestStruct {
752 fn test_method(&self, test: i32) {}
757 let test_struct = test_mod::TestStruct {};
758 test_mod::TestTrait::test_method(&test_struct, 42)
765 fn trait_method_consume() {
770 pub trait TestTrait {
771 fn test_method(self);
773 pub struct TestStruct {}
774 impl TestTrait for TestStruct {
775 fn test_method(self) {}
780 let test_struct = test_mod::TestStruct {};
781 test_struct.test_meth$0od()
786 pub trait TestTrait {
787 fn test_method(self);
789 pub struct TestStruct {}
790 impl TestTrait for TestStruct {
791 fn test_method(self) {}
796 let test_struct = test_mod::TestStruct {};
797 test_mod::TestTrait::test_method(test_struct)
804 fn trait_method_cross_crate() {
808 //- /main.rs crate:main deps:dep
810 let test_struct = dep::test_mod::TestStruct {};
811 test_struct.test_meth$0od()
813 //- /dep.rs crate:dep
815 pub trait TestTrait {
816 fn test_method(&self);
818 pub struct TestStruct {}
819 impl TestTrait for TestStruct {
820 fn test_method(&self) {}
826 let test_struct = dep::test_mod::TestStruct {};
827 dep::test_mod::TestTrait::test_method(&test_struct)
834 fn assoc_fn_cross_crate() {
838 //- /main.rs crate:main deps:dep
840 dep::test_mod::TestStruct::test_func$0tion
842 //- /dep.rs crate:dep
844 pub trait TestTrait {
847 pub struct TestStruct {}
848 impl TestTrait for TestStruct {
849 fn test_function() {}
855 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::test_function
862 fn assoc_const_cross_crate() {
866 //- /main.rs crate:main deps:dep
868 dep::test_mod::TestStruct::CONST$0
870 //- /dep.rs crate:dep
872 pub trait TestTrait {
875 pub struct TestStruct {}
876 impl TestTrait for TestStruct {
877 const CONST: bool = true;
883 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::CONST
890 fn assoc_fn_as_method_cross_crate() {
891 check_assist_not_applicable(
894 //- /main.rs crate:main deps:dep
896 let test_struct = dep::test_mod::TestStruct {};
897 test_struct.test_func$0tion()
899 //- /dep.rs crate:dep
901 pub trait TestTrait {
904 pub struct TestStruct {}
905 impl TestTrait for TestStruct {
906 fn test_function() {}
914 fn private_trait_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_meth$0od()
923 //- /dep.rs crate:dep
926 fn test_method(&self);
928 pub struct TestStruct {}
929 impl TestTrait for TestStruct {
930 fn test_method(&self) {}
938 fn not_applicable_for_imported_trait_for_method() {
939 check_assist_not_applicable(
943 pub trait TestTrait {
944 fn test_method(&self);
946 pub trait TestTrait2 {
947 fn test_method(&self);
953 impl TestTrait2 for TestEnum {
954 fn test_method(&self) {}
956 impl TestTrait for TestEnum {
957 fn test_method(&self) {}
961 use test_mod::TestTrait2;
963 let one = test_mod::TestEnum::One;
975 //- /lib.rs crate:dep
978 //- /main.rs crate:main deps:dep
993 // Tests that only imports whose last segment matches the identifier get suggested.
997 //- /lib.rs crate:dep
1002 pub fn panic_fmt() {}
1004 //- /main.rs crate:main deps:dep
1007 impl f$0mt::Display for S {}
1012 impl dep::fmt::Display for S {}
1018 fn macro_generated() {
1019 // Tests that macro-generated items are suggested from external crates.
1023 //- /lib.rs crate:dep
1032 //- /main.rs crate:main deps:dep
1047 // Tests that differently cased names don't interfere and we only suggest the matching one.
1051 //- /lib.rs crate:dep
1055 //- /main.rs crate:main deps:dep
1069 fn keep_generic_annotations() {
1073 //- /lib.rs crate:dep
1074 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1076 //- /main.rs crate:main deps:dep
1077 fn foo() -> Thin$0g<'static, ()> {}
1082 fn foo() -> dep::generic::Thing<'static, ()> {}
1090 fn keep_generic_annotations_leading_colon() {
1094 //- /lib.rs crate:dep
1095 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1097 //- /main.rs crate:main deps:dep
1098 fn foo() -> Thin$0g::<'static, ()> {}
1103 fn foo() -> dep::generic::Thing::<'static, ()> {}
1111 fn associated_struct_const_generic() {
1116 pub struct TestStruct<T> {}
1117 impl<T> TestStruct<T> {
1118 const TEST_CONST: u8 = 42;
1123 TestStruct::<()>::TEST_CONST$0
1128 pub struct TestStruct<T> {}
1129 impl<T> TestStruct<T> {
1130 const TEST_CONST: u8 = 42;
1135 test_mod::TestStruct::<()>::TEST_CONST
1142 fn associated_trait_const_generic() {
1147 pub trait TestTrait {
1148 const TEST_CONST: u8;
1150 pub struct TestStruct<T> {}
1151 impl<T> TestTrait for TestStruct<T> {
1152 const TEST_CONST: u8 = 42;
1157 test_mod::TestStruct::<()>::TEST_CONST$0
1162 pub trait TestTrait {
1163 const TEST_CONST: u8;
1165 pub struct TestStruct<T> {}
1166 impl<T> TestTrait for TestStruct<T> {
1167 const TEST_CONST: u8 = 42;
1172 <test_mod::TestStruct::<()> as test_mod::TestTrait>::TEST_CONST
1179 fn trait_method_generic() {
1184 pub trait TestTrait {
1185 fn test_method<T>(&self);
1187 pub struct TestStruct {}
1188 impl TestTrait for TestStruct {
1189 fn test_method<T>(&self) {}
1194 let test_struct = test_mod::TestStruct {};
1195 test_struct.test_meth$0od::<()>()
1200 pub trait TestTrait {
1201 fn test_method<T>(&self);
1203 pub struct TestStruct {}
1204 impl TestTrait for TestStruct {
1205 fn test_method<T>(&self) {}
1210 let test_struct = test_mod::TestStruct {};
1211 test_mod::TestTrait::test_method::<()>(&test_struct)