4 use ide_db::RootDatabase;
6 helpers::mod_path_to_ast,
7 imports::import_assets::{ImportCandidate, LocatedImport},
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)?;
40 let mut proposed_imports = import_assets.search_for_relative_paths(&ctx.sema);
41 if proposed_imports.is_empty() {
45 let range = match &syntax_under_caret {
46 NodeOrToken::Node(node) => ctx.sema.original_range(node).range,
47 NodeOrToken::Token(token) => token.text_range(),
49 let candidate = import_assets.import_candidate();
50 let qualify_candidate = match syntax_under_caret {
51 NodeOrToken::Node(syntax_under_caret) => match candidate {
52 ImportCandidate::Path(candidate) if candidate.qualifier.is_some() => {
53 cov_mark::hit!(qualify_path_qualifier_start);
54 let path = ast::Path::cast(syntax_under_caret)?;
55 let (prev_segment, segment) = (path.qualifier()?.segment()?, path.segment()?);
56 QualifyCandidate::QualifierStart(segment, prev_segment.generic_arg_list())
58 ImportCandidate::Path(_) => {
59 cov_mark::hit!(qualify_path_unqualified_name);
60 let path = ast::Path::cast(syntax_under_caret)?;
61 let generics = path.segment()?.generic_arg_list();
62 QualifyCandidate::UnqualifiedName(generics)
64 ImportCandidate::TraitAssocItem(_) => {
65 cov_mark::hit!(qualify_path_trait_assoc_item);
66 let path = ast::Path::cast(syntax_under_caret)?;
67 let (qualifier, segment) = (path.qualifier()?, path.segment()?);
68 QualifyCandidate::TraitAssocItem(qualifier, segment)
70 ImportCandidate::TraitMethod(_) => {
71 cov_mark::hit!(qualify_path_trait_method);
72 let mcall_expr = ast::MethodCallExpr::cast(syntax_under_caret)?;
73 QualifyCandidate::TraitMethod(ctx.sema.db, mcall_expr)
76 // derive attribute path
77 NodeOrToken::Token(_) => QualifyCandidate::UnqualifiedName(None),
80 // we aren't interested in different namespaces
81 proposed_imports.dedup_by(|a, b| a.import_path == b.import_path);
83 let group_label = group_label(candidate);
84 for import in proposed_imports {
87 AssistId("qualify_path", AssistKind::QuickFix),
88 label(candidate, &import),
91 qualify_candidate.qualify(
92 |replace_with: String| builder.replace(range, replace_with),
94 import.item_to_import,
101 pub(crate) enum QualifyCandidate<'db> {
102 QualifierStart(ast::PathSegment, Option<ast::GenericArgList>),
103 UnqualifiedName(Option<ast::GenericArgList>),
104 TraitAssocItem(ast::Path, ast::PathSegment),
105 TraitMethod(&'db RootDatabase, ast::MethodCallExpr),
106 ImplMethod(&'db RootDatabase, ast::MethodCallExpr, hir::Function),
109 impl QualifyCandidate<'_> {
110 pub(crate) fn qualify(
112 mut replacer: impl FnMut(String),
113 import: &hir::ModPath,
116 let import = mod_path_to_ast(import);
118 QualifyCandidate::QualifierStart(segment, generics) => {
119 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
120 replacer(format!("{}{}::{}", import, generics, segment));
122 QualifyCandidate::UnqualifiedName(generics) => {
123 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
124 replacer(format!("{}{}", import, generics));
126 QualifyCandidate::TraitAssocItem(qualifier, segment) => {
127 replacer(format!("<{} as {}>::{}", qualifier, import, segment));
129 QualifyCandidate::TraitMethod(db, mcall_expr) => {
130 Self::qualify_trait_method(db, mcall_expr, replacer, import, item);
132 QualifyCandidate::ImplMethod(db, mcall_expr, hir_fn) => {
133 Self::qualify_fn_call(db, mcall_expr, replacer, import, hir_fn);
140 mcall_expr: &ast::MethodCallExpr,
141 mut replacer: impl FnMut(String),
143 hir_fn: &hir::Function,
145 let receiver = mcall_expr.receiver()?;
146 let method_name = mcall_expr.name_ref()?;
148 mcall_expr.generic_arg_list().as_ref().map_or_else(String::new, ToString::to_string);
149 let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args());
151 if let Some(self_access) = hir_fn.self_param(db).map(|sp| sp.access(db)) {
152 let receiver = match self_access {
153 hir::Access::Shared => make::expr_ref(receiver, false),
154 hir::Access::Exclusive => make::expr_ref(receiver, true),
155 hir::Access::Owned => receiver,
163 Some(args) => make::arg_list(iter::once(receiver).chain(args)),
164 None => make::arg_list(iter::once(receiver)),
171 fn qualify_trait_method(
173 mcall_expr: &ast::MethodCallExpr,
174 replacer: impl FnMut(String),
178 let trait_method_name = mcall_expr.name_ref()?;
179 let trait_ = item_as_trait(db, item)?;
180 let method = find_trait_method(db, trait_, &trait_method_name)?;
181 Self::qualify_fn_call(db, mcall_expr, replacer, import, &method)
185 fn find_trait_method(
188 trait_method_name: &ast::NameRef,
189 ) -> Option<hir::Function> {
190 if let Some(hir::AssocItem::Function(method)) =
191 trait_.items(db).into_iter().find(|item: &hir::AssocItem| {
193 .map(|name| name.to_string() == trait_method_name.to_string())
203 fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option<hir::Trait> {
204 let item_module_def = item.as_module_def()?;
206 match item_module_def {
207 hir::ModuleDef::Trait(trait_) => Some(trait_),
208 _ => item_module_def.as_assoc_item(db)?.containing_trait(db),
212 fn group_label(candidate: &ImportCandidate) -> GroupLabel {
213 let name = match candidate {
214 ImportCandidate::Path(it) => &it.name,
215 ImportCandidate::TraitAssocItem(it) | ImportCandidate::TraitMethod(it) => {
220 GroupLabel(format!("Qualify {}", name))
223 fn label(candidate: &ImportCandidate, import: &LocatedImport) -> String {
225 ImportCandidate::Path(candidate) if candidate.qualifier.is_none() => {
226 format!("Qualify as `{}`", import.import_path)
228 _ => format!("Qualify with `{}`", import.import_path),
234 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
239 fn applicable_when_found_an_import_partial() {
240 cov_mark::check!(qualify_path_unqualified_name);
246 pub struct Formatter;
257 pub struct Formatter;
269 fn applicable_when_found_an_import() {
276 pub struct PubStruct;
283 pub struct PubStruct;
290 fn applicable_in_macros() {
295 ($i:ident) => { fn foo(a: $i) {} }
300 pub struct PubStruct;
305 ($i:ident) => { fn foo(a: $i) {} }
307 foo!(PubMod::PubStruct);
310 pub struct PubStruct;
317 fn applicable_when_found_multiple_imports() {
324 pub struct PubStruct;
327 pub struct PubStruct;
330 pub struct PubStruct;
337 pub struct PubStruct;
340 pub struct PubStruct;
343 pub struct PubStruct;
350 fn not_applicable_for_already_imported_types() {
351 check_assist_not_applicable(
354 use PubMod::PubStruct;
359 pub struct PubStruct;
366 fn not_applicable_for_types_with_private_paths() {
367 check_assist_not_applicable(
373 struct PrivateStruct;
380 fn not_applicable_when_no_imports_found() {
381 check_assist_not_applicable(qualify_path, r#"PubStruct$0"#);
385 fn qualify_function() {
392 pub fn test_function() {};
396 PubMod::test_function
399 pub fn test_function() {};
410 //- /lib.rs crate:crate_with_macro
416 //- /main.rs crate:main deps:crate_with_macro
423 crate_with_macro::foo
430 fn qualify_path_target() {
435 group_label: Option<$0GroupLabel>,
438 mod m { pub struct GroupLabel; }
445 fn not_applicable_when_path_start_is_imported() {
446 check_assist_not_applicable(
452 pub struct TestStruct;
459 mod2::mod3::TestStruct$0
466 fn not_applicable_for_imported_function() {
467 check_assist_not_applicable(
471 pub fn test_function() {}
474 use test_mod::test_function;
483 fn associated_struct_function() {
488 pub struct TestStruct {}
490 pub fn test_function() {}
495 TestStruct::test_function$0
500 pub struct TestStruct {}
502 pub fn test_function() {}
507 test_mod::TestStruct::test_function
514 fn associated_struct_const() {
515 cov_mark::check!(qualify_path_qualifier_start);
520 pub struct TestStruct {}
522 const TEST_CONST: u8 = 42;
527 TestStruct::TEST_CONST$0
532 pub struct TestStruct {}
534 const TEST_CONST: u8 = 42;
539 test_mod::TestStruct::TEST_CONST
546 fn associated_struct_const_unqualified() {
547 // FIXME: non-trait assoc items completion is unsupported yet, see FIXME in the import_assets.rs for more details
548 check_assist_not_applicable(
552 pub struct TestStruct {}
554 const TEST_CONST: u8 = 42;
566 fn associated_trait_function() {
571 pub trait TestTrait {
574 pub struct TestStruct {}
575 impl TestTrait for TestStruct {
576 fn test_function() {}
581 test_mod::TestStruct::test_function$0
586 pub trait TestTrait {
589 pub struct TestStruct {}
590 impl TestTrait for TestStruct {
591 fn test_function() {}
596 <test_mod::TestStruct as test_mod::TestTrait>::test_function
603 fn not_applicable_for_imported_trait_for_function() {
604 check_assist_not_applicable(
608 pub trait TestTrait {
611 pub trait TestTrait2 {
618 impl TestTrait2 for TestEnum {
619 fn test_function() {}
621 impl TestTrait for TestEnum {
622 fn test_function() {}
626 use test_mod::TestTrait2;
628 test_mod::TestEnum::test_function$0;
635 fn associated_trait_const() {
636 cov_mark::check!(qualify_path_trait_assoc_item);
641 pub trait TestTrait {
642 const TEST_CONST: u8;
644 pub struct TestStruct {}
645 impl TestTrait for TestStruct {
646 const TEST_CONST: u8 = 42;
651 test_mod::TestStruct::TEST_CONST$0
656 pub trait TestTrait {
657 const TEST_CONST: u8;
659 pub struct TestStruct {}
660 impl TestTrait for TestStruct {
661 const TEST_CONST: u8 = 42;
666 <test_mod::TestStruct as test_mod::TestTrait>::TEST_CONST
673 fn not_applicable_for_imported_trait_for_const() {
674 check_assist_not_applicable(
678 pub trait TestTrait {
679 const TEST_CONST: u8;
681 pub trait TestTrait2 {
682 const TEST_CONST: f64;
688 impl TestTrait2 for TestEnum {
689 const TEST_CONST: f64 = 42.0;
691 impl TestTrait for TestEnum {
692 const TEST_CONST: u8 = 42;
696 use test_mod::TestTrait2;
698 test_mod::TestEnum::TEST_CONST$0;
706 cov_mark::check!(qualify_path_trait_method);
711 pub trait TestTrait {
712 fn test_method(&self);
714 pub struct TestStruct {}
715 impl TestTrait for TestStruct {
716 fn test_method(&self) {}
721 let test_struct = test_mod::TestStruct {};
722 test_struct.test_meth$0od()
727 pub trait TestTrait {
728 fn test_method(&self);
730 pub struct TestStruct {}
731 impl TestTrait for TestStruct {
732 fn test_method(&self) {}
737 let test_struct = test_mod::TestStruct {};
738 test_mod::TestTrait::test_method(&test_struct)
745 fn trait_method_multi_params() {
750 pub trait TestTrait {
751 fn test_method(&self, test: i32);
753 pub struct TestStruct {}
754 impl TestTrait for TestStruct {
755 fn test_method(&self, test: i32) {}
760 let test_struct = test_mod::TestStruct {};
761 test_struct.test_meth$0od(42)
766 pub trait TestTrait {
767 fn test_method(&self, test: i32);
769 pub struct TestStruct {}
770 impl TestTrait for TestStruct {
771 fn test_method(&self, test: i32) {}
776 let test_struct = test_mod::TestStruct {};
777 test_mod::TestTrait::test_method(&test_struct, 42)
784 fn trait_method_consume() {
789 pub trait TestTrait {
790 fn test_method(self);
792 pub struct TestStruct {}
793 impl TestTrait for TestStruct {
794 fn test_method(self) {}
799 let test_struct = test_mod::TestStruct {};
800 test_struct.test_meth$0od()
805 pub trait TestTrait {
806 fn test_method(self);
808 pub struct TestStruct {}
809 impl TestTrait for TestStruct {
810 fn test_method(self) {}
815 let test_struct = test_mod::TestStruct {};
816 test_mod::TestTrait::test_method(test_struct)
823 fn trait_method_cross_crate() {
827 //- /main.rs crate:main deps:dep
829 let test_struct = dep::test_mod::TestStruct {};
830 test_struct.test_meth$0od()
832 //- /dep.rs crate:dep
834 pub trait TestTrait {
835 fn test_method(&self);
837 pub struct TestStruct {}
838 impl TestTrait for TestStruct {
839 fn test_method(&self) {}
845 let test_struct = dep::test_mod::TestStruct {};
846 dep::test_mod::TestTrait::test_method(&test_struct)
853 fn assoc_fn_cross_crate() {
857 //- /main.rs crate:main deps:dep
859 dep::test_mod::TestStruct::test_func$0tion
861 //- /dep.rs crate:dep
863 pub trait TestTrait {
866 pub struct TestStruct {}
867 impl TestTrait for TestStruct {
868 fn test_function() {}
874 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::test_function
881 fn assoc_const_cross_crate() {
885 //- /main.rs crate:main deps:dep
887 dep::test_mod::TestStruct::CONST$0
889 //- /dep.rs crate:dep
891 pub trait TestTrait {
894 pub struct TestStruct {}
895 impl TestTrait for TestStruct {
896 const CONST: bool = true;
902 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::CONST
909 fn assoc_fn_as_method_cross_crate() {
910 check_assist_not_applicable(
913 //- /main.rs crate:main deps:dep
915 let test_struct = dep::test_mod::TestStruct {};
916 test_struct.test_func$0tion()
918 //- /dep.rs crate:dep
920 pub trait TestTrait {
923 pub struct TestStruct {}
924 impl TestTrait for TestStruct {
925 fn test_function() {}
933 fn private_trait_cross_crate() {
934 check_assist_not_applicable(
937 //- /main.rs crate:main deps:dep
939 let test_struct = dep::test_mod::TestStruct {};
940 test_struct.test_meth$0od()
942 //- /dep.rs crate:dep
945 fn test_method(&self);
947 pub struct TestStruct {}
948 impl TestTrait for TestStruct {
949 fn test_method(&self) {}
957 fn not_applicable_for_imported_trait_for_method() {
958 check_assist_not_applicable(
962 pub trait TestTrait {
963 fn test_method(&self);
965 pub trait TestTrait2 {
966 fn test_method(&self);
972 impl TestTrait2 for TestEnum {
973 fn test_method(&self) {}
975 impl TestTrait for TestEnum {
976 fn test_method(&self) {}
980 use test_mod::TestTrait2;
982 let one = test_mod::TestEnum::One;
994 //- /lib.rs crate:dep
997 //- /main.rs crate:main deps:dep
1011 fn whole_segment() {
1012 // Tests that only imports whose last segment matches the identifier get suggested.
1016 //- /lib.rs crate:dep
1018 pub trait Display {}
1021 pub fn panic_fmt() {}
1023 //- /main.rs crate:main deps:dep
1026 impl f$0mt::Display for S {}
1031 impl dep::fmt::Display for S {}
1037 fn macro_generated() {
1038 // Tests that macro-generated items are suggested from external crates.
1042 //- /lib.rs crate:dep
1051 //- /main.rs crate:main deps:dep
1066 // Tests that differently cased names don't interfere and we only suggest the matching one.
1070 //- /lib.rs crate:dep
1074 //- /main.rs crate:main deps:dep
1088 fn keep_generic_annotations() {
1092 //- /lib.rs crate:dep
1093 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1095 //- /main.rs crate:main deps:dep
1096 fn foo() -> Thin$0g<'static, ()> {}
1101 fn foo() -> dep::generic::Thing<'static, ()> {}
1109 fn keep_generic_annotations_leading_colon() {
1113 //- /lib.rs crate:dep
1114 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1116 //- /main.rs crate:main deps:dep
1117 fn foo() -> Thin$0g::<'static, ()> {}
1122 fn foo() -> dep::generic::Thing::<'static, ()> {}
1130 fn associated_struct_const_generic() {
1135 pub struct TestStruct<T> {}
1136 impl<T> TestStruct<T> {
1137 const TEST_CONST: u8 = 42;
1142 TestStruct::<()>::TEST_CONST$0
1147 pub struct TestStruct<T> {}
1148 impl<T> TestStruct<T> {
1149 const TEST_CONST: u8 = 42;
1154 test_mod::TestStruct::<()>::TEST_CONST
1161 fn associated_trait_const_generic() {
1166 pub trait TestTrait {
1167 const TEST_CONST: u8;
1169 pub struct TestStruct<T> {}
1170 impl<T> TestTrait for TestStruct<T> {
1171 const TEST_CONST: u8 = 42;
1176 test_mod::TestStruct::<()>::TEST_CONST$0
1181 pub trait TestTrait {
1182 const TEST_CONST: u8;
1184 pub struct TestStruct<T> {}
1185 impl<T> TestTrait for TestStruct<T> {
1186 const TEST_CONST: u8 = 42;
1191 <test_mod::TestStruct::<()> as test_mod::TestTrait>::TEST_CONST
1198 fn trait_method_generic() {
1203 pub trait TestTrait {
1204 fn test_method<T>(&self);
1206 pub struct TestStruct {}
1207 impl TestTrait for TestStruct {
1208 fn test_method<T>(&self) {}
1213 let test_struct = test_mod::TestStruct {};
1214 test_struct.test_meth$0od::<()>()
1219 pub trait TestTrait {
1220 fn test_method<T>(&self);
1222 pub struct TestStruct {}
1223 impl TestTrait for TestStruct {
1224 fn test_method<T>(&self) {}
1229 let test_struct = test_mod::TestStruct {};
1230 test_mod::TestTrait::test_method::<()>(&test_struct)
1237 fn works_in_derives() {
1243 #[rustc_builtin_macro]
1251 #[rustc_builtin_macro]
1254 #[derive(foo::Copy)]
1261 fn works_in_use_start() {
1284 fn not_applicable_in_non_start_use() {
1285 check_assist_not_applicable(