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 =
41 import_assets.search_for_relative_paths(&ctx.sema, ctx.config.prefer_no_std);
42 if proposed_imports.is_empty() {
46 let range = match &syntax_under_caret {
47 NodeOrToken::Node(node) => ctx.sema.original_range(node).range,
48 NodeOrToken::Token(token) => token.text_range(),
50 let candidate = import_assets.import_candidate();
51 let qualify_candidate = match syntax_under_caret {
52 NodeOrToken::Node(syntax_under_caret) => match candidate {
53 ImportCandidate::Path(candidate) if candidate.qualifier.is_some() => {
54 cov_mark::hit!(qualify_path_qualifier_start);
55 let path = ast::Path::cast(syntax_under_caret)?;
56 let (prev_segment, segment) = (path.qualifier()?.segment()?, path.segment()?);
57 QualifyCandidate::QualifierStart(segment, prev_segment.generic_arg_list())
59 ImportCandidate::Path(_) => {
60 cov_mark::hit!(qualify_path_unqualified_name);
61 let path = ast::Path::cast(syntax_under_caret)?;
62 let generics = path.segment()?.generic_arg_list();
63 QualifyCandidate::UnqualifiedName(generics)
65 ImportCandidate::TraitAssocItem(_) => {
66 cov_mark::hit!(qualify_path_trait_assoc_item);
67 let path = ast::Path::cast(syntax_under_caret)?;
68 let (qualifier, segment) = (path.qualifier()?, path.segment()?);
69 QualifyCandidate::TraitAssocItem(qualifier, segment)
71 ImportCandidate::TraitMethod(_) => {
72 cov_mark::hit!(qualify_path_trait_method);
73 let mcall_expr = ast::MethodCallExpr::cast(syntax_under_caret)?;
74 QualifyCandidate::TraitMethod(ctx.sema.db, mcall_expr)
77 // derive attribute path
78 NodeOrToken::Token(_) => QualifyCandidate::UnqualifiedName(None),
81 // we aren't interested in different namespaces
82 proposed_imports.dedup_by(|a, b| a.import_path == b.import_path);
84 let group_label = group_label(candidate);
85 for import in proposed_imports {
88 AssistId("qualify_path", AssistKind::QuickFix),
89 label(candidate, &import),
92 qualify_candidate.qualify(
93 |replace_with: String| builder.replace(range, replace_with),
95 import.item_to_import,
102 pub(crate) enum QualifyCandidate<'db> {
103 QualifierStart(ast::PathSegment, Option<ast::GenericArgList>),
104 UnqualifiedName(Option<ast::GenericArgList>),
105 TraitAssocItem(ast::Path, ast::PathSegment),
106 TraitMethod(&'db RootDatabase, ast::MethodCallExpr),
107 ImplMethod(&'db RootDatabase, ast::MethodCallExpr, hir::Function),
110 impl QualifyCandidate<'_> {
111 pub(crate) fn qualify(
113 mut replacer: impl FnMut(String),
114 import: &hir::ModPath,
117 let import = mod_path_to_ast(import);
119 QualifyCandidate::QualifierStart(segment, generics) => {
120 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
121 replacer(format!("{}{}::{}", import, generics, segment));
123 QualifyCandidate::UnqualifiedName(generics) => {
124 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
125 replacer(format!("{}{}", import, generics));
127 QualifyCandidate::TraitAssocItem(qualifier, segment) => {
128 replacer(format!("<{} as {}>::{}", qualifier, import, segment));
130 QualifyCandidate::TraitMethod(db, mcall_expr) => {
131 Self::qualify_trait_method(db, mcall_expr, replacer, import, item);
133 QualifyCandidate::ImplMethod(db, mcall_expr, hir_fn) => {
134 Self::qualify_fn_call(db, mcall_expr, replacer, import, hir_fn);
141 mcall_expr: &ast::MethodCallExpr,
142 mut replacer: impl FnMut(String),
144 hir_fn: &hir::Function,
146 let receiver = mcall_expr.receiver()?;
147 let method_name = mcall_expr.name_ref()?;
149 mcall_expr.generic_arg_list().as_ref().map_or_else(String::new, ToString::to_string);
150 let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args());
152 if let Some(self_access) = hir_fn.self_param(db).map(|sp| sp.access(db)) {
153 let receiver = match self_access {
154 hir::Access::Shared => make::expr_ref(receiver, false),
155 hir::Access::Exclusive => make::expr_ref(receiver, true),
156 hir::Access::Owned => receiver,
164 Some(args) => make::arg_list(iter::once(receiver).chain(args)),
165 None => make::arg_list(iter::once(receiver)),
172 fn qualify_trait_method(
174 mcall_expr: &ast::MethodCallExpr,
175 replacer: impl FnMut(String),
179 let trait_method_name = mcall_expr.name_ref()?;
180 let trait_ = item_as_trait(db, item)?;
181 let method = find_trait_method(db, trait_, &trait_method_name)?;
182 Self::qualify_fn_call(db, mcall_expr, replacer, import, &method)
186 fn find_trait_method(
189 trait_method_name: &ast::NameRef,
190 ) -> Option<hir::Function> {
191 if let Some(hir::AssocItem::Function(method)) =
192 trait_.items(db).into_iter().find(|item: &hir::AssocItem| {
194 .map(|name| name.to_string() == trait_method_name.to_string())
204 fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option<hir::Trait> {
205 let item_module_def = item.as_module_def()?;
207 match item_module_def {
208 hir::ModuleDef::Trait(trait_) => Some(trait_),
209 _ => item_module_def.as_assoc_item(db)?.containing_trait(db),
213 fn group_label(candidate: &ImportCandidate) -> GroupLabel {
214 let name = match candidate {
215 ImportCandidate::Path(it) => &it.name,
216 ImportCandidate::TraitAssocItem(it) | ImportCandidate::TraitMethod(it) => {
221 GroupLabel(format!("Qualify {}", name))
224 fn label(candidate: &ImportCandidate, import: &LocatedImport) -> String {
226 ImportCandidate::Path(candidate) if candidate.qualifier.is_none() => {
227 format!("Qualify as `{}`", import.import_path)
229 _ => format!("Qualify with `{}`", import.import_path),
235 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
240 fn applicable_when_found_an_import_partial() {
241 cov_mark::check!(qualify_path_unqualified_name);
247 pub struct Formatter;
258 pub struct Formatter;
270 fn applicable_when_found_an_import() {
277 pub struct PubStruct;
284 pub struct PubStruct;
291 fn applicable_in_macros() {
296 ($i:ident) => { fn foo(a: $i) {} }
301 pub struct PubStruct;
306 ($i:ident) => { fn foo(a: $i) {} }
308 foo!(PubMod::PubStruct);
311 pub struct PubStruct;
318 fn applicable_when_found_multiple_imports() {
325 pub struct PubStruct;
328 pub struct PubStruct;
331 pub struct PubStruct;
338 pub struct PubStruct;
341 pub struct PubStruct;
344 pub struct PubStruct;
351 fn not_applicable_for_already_imported_types() {
352 check_assist_not_applicable(
355 use PubMod::PubStruct;
360 pub struct PubStruct;
367 fn not_applicable_for_types_with_private_paths() {
368 check_assist_not_applicable(
374 struct PrivateStruct;
381 fn not_applicable_when_no_imports_found() {
382 check_assist_not_applicable(qualify_path, r#"PubStruct$0"#);
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_struct_const_unqualified() {
548 // FIXME: non-trait assoc items completion is unsupported yet, see FIXME in the import_assets.rs for more details
549 check_assist_not_applicable(
553 pub struct TestStruct {}
555 const TEST_CONST: u8 = 42;
567 fn associated_trait_function() {
572 pub trait TestTrait {
575 pub struct TestStruct {}
576 impl TestTrait for TestStruct {
577 fn test_function() {}
582 test_mod::TestStruct::test_function$0
587 pub trait TestTrait {
590 pub struct TestStruct {}
591 impl TestTrait for TestStruct {
592 fn test_function() {}
597 <test_mod::TestStruct as test_mod::TestTrait>::test_function
604 fn not_applicable_for_imported_trait_for_function() {
605 check_assist_not_applicable(
609 pub trait TestTrait {
612 pub trait TestTrait2 {
619 impl TestTrait2 for TestEnum {
620 fn test_function() {}
622 impl TestTrait for TestEnum {
623 fn test_function() {}
627 use test_mod::TestTrait2;
629 test_mod::TestEnum::test_function$0;
636 fn associated_trait_const() {
637 cov_mark::check!(qualify_path_trait_assoc_item);
642 pub trait TestTrait {
643 const TEST_CONST: u8;
645 pub struct TestStruct {}
646 impl TestTrait for TestStruct {
647 const TEST_CONST: u8 = 42;
652 test_mod::TestStruct::TEST_CONST$0
657 pub trait TestTrait {
658 const TEST_CONST: u8;
660 pub struct TestStruct {}
661 impl TestTrait for TestStruct {
662 const TEST_CONST: u8 = 42;
667 <test_mod::TestStruct as test_mod::TestTrait>::TEST_CONST
674 fn not_applicable_for_imported_trait_for_const() {
675 check_assist_not_applicable(
679 pub trait TestTrait {
680 const TEST_CONST: u8;
682 pub trait TestTrait2 {
683 const TEST_CONST: f64;
689 impl TestTrait2 for TestEnum {
690 const TEST_CONST: f64 = 42.0;
692 impl TestTrait for TestEnum {
693 const TEST_CONST: u8 = 42;
697 use test_mod::TestTrait2;
699 test_mod::TestEnum::TEST_CONST$0;
707 cov_mark::check!(qualify_path_trait_method);
712 pub trait TestTrait {
713 fn test_method(&self);
715 pub struct TestStruct {}
716 impl TestTrait for TestStruct {
717 fn test_method(&self) {}
722 let test_struct = test_mod::TestStruct {};
723 test_struct.test_meth$0od()
728 pub trait TestTrait {
729 fn test_method(&self);
731 pub struct TestStruct {}
732 impl TestTrait for TestStruct {
733 fn test_method(&self) {}
738 let test_struct = test_mod::TestStruct {};
739 test_mod::TestTrait::test_method(&test_struct)
746 fn trait_method_multi_params() {
751 pub trait TestTrait {
752 fn test_method(&self, test: i32);
754 pub struct TestStruct {}
755 impl TestTrait for TestStruct {
756 fn test_method(&self, test: i32) {}
761 let test_struct = test_mod::TestStruct {};
762 test_struct.test_meth$0od(42)
767 pub trait TestTrait {
768 fn test_method(&self, test: i32);
770 pub struct TestStruct {}
771 impl TestTrait for TestStruct {
772 fn test_method(&self, test: i32) {}
777 let test_struct = test_mod::TestStruct {};
778 test_mod::TestTrait::test_method(&test_struct, 42)
785 fn trait_method_consume() {
790 pub trait TestTrait {
791 fn test_method(self);
793 pub struct TestStruct {}
794 impl TestTrait for TestStruct {
795 fn test_method(self) {}
800 let test_struct = test_mod::TestStruct {};
801 test_struct.test_meth$0od()
806 pub trait TestTrait {
807 fn test_method(self);
809 pub struct TestStruct {}
810 impl TestTrait for TestStruct {
811 fn test_method(self) {}
816 let test_struct = test_mod::TestStruct {};
817 test_mod::TestTrait::test_method(test_struct)
824 fn trait_method_cross_crate() {
828 //- /main.rs crate:main deps:dep
830 let test_struct = dep::test_mod::TestStruct {};
831 test_struct.test_meth$0od()
833 //- /dep.rs crate:dep
835 pub trait TestTrait {
836 fn test_method(&self);
838 pub struct TestStruct {}
839 impl TestTrait for TestStruct {
840 fn test_method(&self) {}
846 let test_struct = dep::test_mod::TestStruct {};
847 dep::test_mod::TestTrait::test_method(&test_struct)
854 fn assoc_fn_cross_crate() {
858 //- /main.rs crate:main deps:dep
860 dep::test_mod::TestStruct::test_func$0tion
862 //- /dep.rs crate:dep
864 pub trait TestTrait {
867 pub struct TestStruct {}
868 impl TestTrait for TestStruct {
869 fn test_function() {}
875 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::test_function
882 fn assoc_const_cross_crate() {
886 //- /main.rs crate:main deps:dep
888 dep::test_mod::TestStruct::CONST$0
890 //- /dep.rs crate:dep
892 pub trait TestTrait {
895 pub struct TestStruct {}
896 impl TestTrait for TestStruct {
897 const CONST: bool = true;
903 <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::CONST
910 fn assoc_fn_as_method_cross_crate() {
911 check_assist_not_applicable(
914 //- /main.rs crate:main deps:dep
916 let test_struct = dep::test_mod::TestStruct {};
917 test_struct.test_func$0tion()
919 //- /dep.rs crate:dep
921 pub trait TestTrait {
924 pub struct TestStruct {}
925 impl TestTrait for TestStruct {
926 fn test_function() {}
934 fn private_trait_cross_crate() {
935 check_assist_not_applicable(
938 //- /main.rs crate:main deps:dep
940 let test_struct = dep::test_mod::TestStruct {};
941 test_struct.test_meth$0od()
943 //- /dep.rs crate:dep
946 fn test_method(&self);
948 pub struct TestStruct {}
949 impl TestTrait for TestStruct {
950 fn test_method(&self) {}
958 fn not_applicable_for_imported_trait_for_method() {
959 check_assist_not_applicable(
963 pub trait TestTrait {
964 fn test_method(&self);
966 pub trait TestTrait2 {
967 fn test_method(&self);
973 impl TestTrait2 for TestEnum {
974 fn test_method(&self) {}
976 impl TestTrait for TestEnum {
977 fn test_method(&self) {}
981 use test_mod::TestTrait2;
983 let one = test_mod::TestEnum::One;
995 //- /lib.rs crate:dep
998 //- /main.rs crate:main deps:dep
1012 fn whole_segment() {
1013 // Tests that only imports whose last segment matches the identifier get suggested.
1017 //- /lib.rs crate:dep
1019 pub trait Display {}
1022 pub fn panic_fmt() {}
1024 //- /main.rs crate:main deps:dep
1027 impl f$0mt::Display for S {}
1032 impl dep::fmt::Display for S {}
1038 fn macro_generated() {
1039 // Tests that macro-generated items are suggested from external crates.
1043 //- /lib.rs crate:dep
1052 //- /main.rs crate:main deps:dep
1067 // Tests that differently cased names don't interfere and we only suggest the matching one.
1071 //- /lib.rs crate:dep
1075 //- /main.rs crate:main deps:dep
1089 fn keep_generic_annotations() {
1093 //- /lib.rs crate:dep
1094 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1096 //- /main.rs crate:main deps:dep
1097 fn foo() -> Thin$0g<'static, ()> {}
1102 fn foo() -> dep::generic::Thing<'static, ()> {}
1110 fn keep_generic_annotations_leading_colon() {
1114 //- /lib.rs crate:dep
1115 pub mod generic { pub struct Thing<'a, T>(&'a T); }
1117 //- /main.rs crate:main deps:dep
1118 fn foo() -> Thin$0g::<'static, ()> {}
1123 fn foo() -> dep::generic::Thing::<'static, ()> {}
1131 fn associated_struct_const_generic() {
1136 pub struct TestStruct<T> {}
1137 impl<T> TestStruct<T> {
1138 const TEST_CONST: u8 = 42;
1143 TestStruct::<()>::TEST_CONST$0
1148 pub struct TestStruct<T> {}
1149 impl<T> TestStruct<T> {
1150 const TEST_CONST: u8 = 42;
1155 test_mod::TestStruct::<()>::TEST_CONST
1162 fn associated_trait_const_generic() {
1167 pub trait TestTrait {
1168 const TEST_CONST: u8;
1170 pub struct TestStruct<T> {}
1171 impl<T> TestTrait for TestStruct<T> {
1172 const TEST_CONST: u8 = 42;
1177 test_mod::TestStruct::<()>::TEST_CONST$0
1182 pub trait TestTrait {
1183 const TEST_CONST: u8;
1185 pub struct TestStruct<T> {}
1186 impl<T> TestTrait for TestStruct<T> {
1187 const TEST_CONST: u8 = 42;
1192 <test_mod::TestStruct::<()> as test_mod::TestTrait>::TEST_CONST
1199 fn trait_method_generic() {
1204 pub trait TestTrait {
1205 fn test_method<T>(&self);
1207 pub struct TestStruct {}
1208 impl TestTrait for TestStruct {
1209 fn test_method<T>(&self) {}
1214 let test_struct = test_mod::TestStruct {};
1215 test_struct.test_meth$0od::<()>()
1220 pub trait TestTrait {
1221 fn test_method<T>(&self);
1223 pub struct TestStruct {}
1224 impl TestTrait for TestStruct {
1225 fn test_method<T>(&self) {}
1230 let test_struct = test_mod::TestStruct {};
1231 test_mod::TestTrait::test_method::<()>(&test_struct)
1238 fn works_in_derives() {
1244 #[rustc_builtin_macro]
1252 #[rustc_builtin_macro]
1255 #[derive(foo::Copy)]
1262 fn works_in_use_start() {
1285 fn not_applicable_in_non_start_use() {
1286 check_assist_not_applicable(