5 import_assets::{ImportCandidate, LocatedImport, 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 in proposed_imports {
80 AssistId("qualify_path", AssistKind::QuickFix),
81 label(ctx.db(), 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) => &it.name,
197 GroupLabel(format!("Qualify {}", name))
200 fn label(db: &RootDatabase, candidate: &ImportCandidate, import: &LocatedImport) -> String {
201 let display_path = match import.original_item_name(db) {
202 Some(display_path) => display_path.to_string(),
203 None => "{unknown}".to_string(),
206 ImportCandidate::Path(candidate) => {
207 if !matches!(candidate.qualifier, Qualifier::Absent) {
208 format!("Qualify with `{}`", display_path)
210 format!("Qualify as `{}`", display_path)
213 ImportCandidate::TraitAssocItem(_) => format!("Qualify `{}`", display_path),
214 ImportCandidate::TraitMethod(_) => format!("Qualify with cast as `{}`", display_path),
220 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
225 fn applicable_when_found_an_import_partial() {
226 cov_mark::check!(qualify_path_unqualified_name);
232 pub struct Formatter;
243 pub struct Formatter;
255 fn applicable_when_found_an_import() {
262 pub struct PubStruct;
269 pub struct PubStruct;
276 fn applicable_in_macros() {
281 ($i:ident) => { fn foo(a: $i) {} }
286 pub struct PubStruct;
291 ($i:ident) => { fn foo(a: $i) {} }
293 foo!(PubMod::PubStruct);
296 pub struct PubStruct;
303 fn applicable_when_found_multiple_imports() {
310 pub struct PubStruct;
313 pub struct PubStruct;
316 pub struct PubStruct;
323 pub struct PubStruct;
326 pub struct PubStruct;
329 pub struct PubStruct;
336 fn not_applicable_for_already_imported_types() {
337 check_assist_not_applicable(
340 use PubMod::PubStruct;
345 pub struct PubStruct;
352 fn not_applicable_for_types_with_private_paths() {
353 check_assist_not_applicable(
359 struct PrivateStruct;
366 fn not_applicable_when_no_imports_found() {
367 check_assist_not_applicable(
375 fn not_applicable_in_import_statements() {
376 check_assist_not_applicable(
382 pub struct PubStruct;
388 fn qualify_function() {
395 pub fn test_function() {};
399 PubMod::test_function
402 pub fn test_function() {};
413 //- /lib.rs crate:crate_with_macro
419 //- /main.rs crate:main deps:crate_with_macro
426 crate_with_macro::foo
433 fn qualify_path_target() {
438 group_label: Option<$0GroupLabel>,
441 mod m { pub struct GroupLabel; }
448 fn not_applicable_when_path_start_is_imported() {
449 check_assist_not_applicable(
455 pub struct TestStruct;
462 mod2::mod3::TestStruct$0
469 fn not_applicable_for_imported_function() {
470 check_assist_not_applicable(
474 pub fn test_function() {}
477 use test_mod::test_function;
486 fn associated_struct_function() {
491 pub struct TestStruct {}
493 pub fn test_function() {}
498 TestStruct::test_function$0
503 pub struct TestStruct {}
505 pub fn test_function() {}
510 test_mod::TestStruct::test_function
517 fn associated_struct_const() {
518 cov_mark::check!(qualify_path_qualifier_start);
523 pub struct TestStruct {}
525 const TEST_CONST: u8 = 42;
530 TestStruct::TEST_CONST$0
535 pub struct TestStruct {}
537 const TEST_CONST: u8 = 42;
542 test_mod::TestStruct::TEST_CONST
549 fn associated_trait_function() {
554 pub trait TestTrait {
557 pub struct TestStruct {}
558 impl TestTrait for TestStruct {
559 fn test_function() {}
564 test_mod::TestStruct::test_function$0
569 pub trait TestTrait {
572 pub struct TestStruct {}
573 impl TestTrait for TestStruct {
574 fn test_function() {}
579 <test_mod::TestStruct as test_mod::TestTrait>::test_function
586 fn not_applicable_for_imported_trait_for_function() {
587 check_assist_not_applicable(
591 pub trait TestTrait {
594 pub trait TestTrait2 {
601 impl TestTrait2 for TestEnum {
602 fn test_function() {}
604 impl TestTrait for TestEnum {
605 fn test_function() {}
609 use test_mod::TestTrait2;
611 test_mod::TestEnum::test_function$0;
618 fn associated_trait_const() {
619 cov_mark::check!(qualify_path_trait_assoc_item);
624 pub trait TestTrait {
625 const TEST_CONST: u8;
627 pub struct TestStruct {}
628 impl TestTrait for TestStruct {
629 const TEST_CONST: u8 = 42;
634 test_mod::TestStruct::TEST_CONST$0
639 pub trait TestTrait {
640 const TEST_CONST: u8;
642 pub struct TestStruct {}
643 impl TestTrait for TestStruct {
644 const TEST_CONST: u8 = 42;
649 <test_mod::TestStruct as test_mod::TestTrait>::TEST_CONST
656 fn not_applicable_for_imported_trait_for_const() {
657 check_assist_not_applicable(
661 pub trait TestTrait {
662 const TEST_CONST: u8;
664 pub trait TestTrait2 {
665 const TEST_CONST: f64;
671 impl TestTrait2 for TestEnum {
672 const TEST_CONST: f64 = 42.0;
674 impl TestTrait for TestEnum {
675 const TEST_CONST: u8 = 42;
679 use test_mod::TestTrait2;
681 test_mod::TestEnum::TEST_CONST$0;
689 cov_mark::check!(qualify_path_trait_method);
694 pub trait TestTrait {
695 fn test_method(&self);
697 pub struct TestStruct {}
698 impl TestTrait for TestStruct {
699 fn test_method(&self) {}
704 let test_struct = test_mod::TestStruct {};
705 test_struct.test_meth$0od()
710 pub trait TestTrait {
711 fn test_method(&self);
713 pub struct TestStruct {}
714 impl TestTrait for TestStruct {
715 fn test_method(&self) {}
720 let test_struct = test_mod::TestStruct {};
721 test_mod::TestTrait::test_method(&test_struct)
728 fn trait_method_multi_params() {
733 pub trait TestTrait {
734 fn test_method(&self, test: i32);
736 pub struct TestStruct {}
737 impl TestTrait for TestStruct {
738 fn test_method(&self, test: i32) {}
743 let test_struct = test_mod::TestStruct {};
744 test_struct.test_meth$0od(42)
749 pub trait TestTrait {
750 fn test_method(&self, test: i32);
752 pub struct TestStruct {}
753 impl TestTrait for TestStruct {
754 fn test_method(&self, test: i32) {}
759 let test_struct = test_mod::TestStruct {};
760 test_mod::TestTrait::test_method(&test_struct, 42)
767 fn trait_method_consume() {
772 pub trait TestTrait {
773 fn test_method(self);
775 pub struct TestStruct {}
776 impl TestTrait for TestStruct {
777 fn test_method(self) {}
782 let test_struct = test_mod::TestStruct {};
783 test_struct.test_meth$0od()
788 pub trait TestTrait {
789 fn test_method(self);
791 pub struct TestStruct {}
792 impl TestTrait for TestStruct {
793 fn test_method(self) {}
798 let test_struct = test_mod::TestStruct {};
799 test_mod::TestTrait::test_method(test_struct)
806 fn trait_method_cross_crate() {
810 //- /main.rs crate:main deps:dep
812 let test_struct = dep::test_mod::TestStruct {};
813 test_struct.test_meth$0od()
815 //- /dep.rs crate:dep
817 pub trait TestTrait {
818 fn test_method(&self);
820 pub struct TestStruct {}
821 impl TestTrait for TestStruct {
822 fn test_method(&self) {}
828 let test_struct = dep::test_mod::TestStruct {};
829 dep::test_mod::TestTrait::test_method(&test_struct)
836 fn assoc_fn_cross_crate() {
840 //- /main.rs crate:main deps:dep
842 dep::test_mod::TestStruct::test_func$0tion
844 //- /dep.rs crate:dep
846 pub trait TestTrait {
849 pub struct TestStruct {}
850 impl TestTrait for TestStruct {
851 fn test_function() {}
857 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::test_function
864 fn assoc_const_cross_crate() {
868 //- /main.rs crate:main deps:dep
870 dep::test_mod::TestStruct::CONST$0
872 //- /dep.rs crate:dep
874 pub trait TestTrait {
877 pub struct TestStruct {}
878 impl TestTrait for TestStruct {
879 const CONST: bool = true;
885 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::CONST
892 fn assoc_fn_as_method_cross_crate() {
893 check_assist_not_applicable(
896 //- /main.rs crate:main deps:dep
898 let test_struct = dep::test_mod::TestStruct {};
899 test_struct.test_func$0tion()
901 //- /dep.rs crate:dep
903 pub trait TestTrait {
906 pub struct TestStruct {}
907 impl TestTrait for TestStruct {
908 fn test_function() {}
916 fn private_trait_cross_crate() {
917 check_assist_not_applicable(
920 //- /main.rs crate:main deps:dep
922 let test_struct = dep::test_mod::TestStruct {};
923 test_struct.test_meth$0od()
925 //- /dep.rs crate:dep
928 fn test_method(&self);
930 pub struct TestStruct {}
931 impl TestTrait for TestStruct {
932 fn test_method(&self) {}
940 fn not_applicable_for_imported_trait_for_method() {
941 check_assist_not_applicable(
945 pub trait TestTrait {
946 fn test_method(&self);
948 pub trait TestTrait2 {
949 fn test_method(&self);
955 impl TestTrait2 for TestEnum {
956 fn test_method(&self) {}
958 impl TestTrait for TestEnum {
959 fn test_method(&self) {}
963 use test_mod::TestTrait2;
965 let one = test_mod::TestEnum::One;
977 //- /lib.rs crate:dep
980 //- /main.rs crate:main deps:dep
995 // Tests that only imports whose last segment matches the identifier get suggested.
999 //- /lib.rs crate:dep
1001 pub trait Display {}
1004 pub fn panic_fmt() {}
1006 //- /main.rs crate:main deps:dep
1009 impl f$0mt::Display for S {}
1014 impl dep::fmt::Display for S {}
1020 fn macro_generated() {
1021 // Tests that macro-generated items are suggested from external crates.
1025 //- /lib.rs crate:dep
1034 //- /main.rs crate:main deps:dep
1049 // Tests that differently cased names don't interfere and we only suggest the matching one.
1053 //- /lib.rs crate:dep
1057 //- /main.rs crate:main deps:dep
1071 fn keep_generic_annotations() {
1075 //- /lib.rs crate:dep
1076 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1078 //- /main.rs crate:main deps:dep
1079 fn foo() -> Thin$0g<'static, ()> {}
1084 fn foo() -> dep::generic::Thing<'static, ()> {}
1092 fn keep_generic_annotations_leading_colon() {
1096 //- /lib.rs crate:dep
1097 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1099 //- /main.rs crate:main deps:dep
1100 fn foo() -> Thin$0g::<'static, ()> {}
1105 fn foo() -> dep::generic::Thing::<'static, ()> {}
1113 fn associated_struct_const_generic() {
1118 pub struct TestStruct<T> {}
1119 impl<T> TestStruct<T> {
1120 const TEST_CONST: u8 = 42;
1125 TestStruct::<()>::TEST_CONST$0
1130 pub struct TestStruct<T> {}
1131 impl<T> TestStruct<T> {
1132 const TEST_CONST: u8 = 42;
1137 test_mod::TestStruct::<()>::TEST_CONST
1144 fn associated_trait_const_generic() {
1149 pub trait TestTrait {
1150 const TEST_CONST: u8;
1152 pub struct TestStruct<T> {}
1153 impl<T> TestTrait for TestStruct<T> {
1154 const TEST_CONST: u8 = 42;
1159 test_mod::TestStruct::<()>::TEST_CONST$0
1164 pub trait TestTrait {
1165 const TEST_CONST: u8;
1167 pub struct TestStruct<T> {}
1168 impl<T> TestTrait for TestStruct<T> {
1169 const TEST_CONST: u8 = 42;
1174 <test_mod::TestStruct::<()> as test_mod::TestTrait>::TEST_CONST
1181 fn trait_method_generic() {
1186 pub trait TestTrait {
1187 fn test_method<T>(&self);
1189 pub struct TestStruct {}
1190 impl TestTrait for TestStruct {
1191 fn test_method<T>(&self) {}
1196 let test_struct = test_mod::TestStruct {};
1197 test_struct.test_meth$0od::<()>()
1202 pub trait TestTrait {
1203 fn test_method<T>(&self);
1205 pub struct TestStruct {}
1206 impl TestTrait for TestStruct {
1207 fn test_method<T>(&self) {}
1212 let test_struct = test_mod::TestStruct {};
1213 test_mod::TestTrait::test_method::<()>(&test_struct)