1 use std::collections::BTreeSet;
5 AsAssocItem, AssocItemContainer, ModPath, Module, ModuleDef, PathResolution, Semantics, Trait,
8 use ra_ide_db::{imports_locator::ImportsLocator, RootDatabase};
14 use rustc_hash::FxHashSet;
16 use crate::{utils::insert_use_statement, AssistContext, AssistId, Assists, GroupLabel};
18 // Assist: auto_import
20 // If the name is unresolved, provides all possible imports for it.
24 // let map = HashMap<|>::new();
26 // # pub mod std { pub mod collections { pub struct HashMap { } } }
30 // use std::collections::HashMap;
33 // let map = HashMap::new();
35 // # pub mod std { pub mod collections { pub struct HashMap { } } }
37 pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
38 let auto_import_assets = AutoImportAssets::new(&ctx)?;
39 let proposed_imports = auto_import_assets.search_for_imports(ctx.db);
40 if proposed_imports.is_empty() {
44 let range = ctx.sema.original_range(&auto_import_assets.syntax_under_caret).range;
45 let group = auto_import_assets.get_import_group_message();
46 for import in proposed_imports {
49 AssistId("auto_import"),
50 format!("Import `{}`", &import),
54 &auto_import_assets.syntax_under_caret,
57 builder.text_edit_builder(),
66 struct AutoImportAssets {
67 import_candidate: ImportCandidate,
68 module_with_name_to_import: Module,
69 syntax_under_caret: SyntaxNode,
72 impl AutoImportAssets {
73 fn new(ctx: &AssistContext) -> Option<Self> {
74 if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() {
75 Self::for_regular_path(path_under_caret, &ctx)
77 Self::for_method_call(ctx.find_node_at_offset_with_descend()?, &ctx)
81 fn for_method_call(method_call: ast::MethodCallExpr, ctx: &AssistContext) -> Option<Self> {
82 let syntax_under_caret = method_call.syntax().to_owned();
83 let module_with_name_to_import = ctx.sema.scope(&syntax_under_caret).module()?;
85 import_candidate: ImportCandidate::for_method_call(&ctx.sema, &method_call)?,
86 module_with_name_to_import,
91 fn for_regular_path(path_under_caret: ast::Path, ctx: &AssistContext) -> Option<Self> {
92 let syntax_under_caret = path_under_caret.syntax().to_owned();
93 if syntax_under_caret.ancestors().find_map(ast::UseItem::cast).is_some() {
97 let module_with_name_to_import = ctx.sema.scope(&syntax_under_caret).module()?;
99 import_candidate: ImportCandidate::for_regular_path(&ctx.sema, &path_under_caret)?,
100 module_with_name_to_import,
105 fn get_search_query(&self) -> &str {
106 match &self.import_candidate {
107 ImportCandidate::UnqualifiedName(name) => name,
108 ImportCandidate::QualifierStart(qualifier_start) => qualifier_start,
109 ImportCandidate::TraitAssocItem(_, trait_assoc_item_name) => trait_assoc_item_name,
110 ImportCandidate::TraitMethod(_, trait_method_name) => trait_method_name,
114 fn get_import_group_message(&self) -> GroupLabel {
115 let name = match &self.import_candidate {
116 ImportCandidate::UnqualifiedName(name) => format!("Import {}", name),
117 ImportCandidate::QualifierStart(qualifier_start) => {
118 format!("Import {}", qualifier_start)
120 ImportCandidate::TraitAssocItem(_, trait_assoc_item_name) => {
121 format!("Import a trait for item {}", trait_assoc_item_name)
123 ImportCandidate::TraitMethod(_, trait_method_name) => {
124 format!("Import a trait for method {}", trait_method_name)
130 fn search_for_imports(&self, db: &RootDatabase) -> BTreeSet<ModPath> {
131 let _p = profile("auto_import::search_for_imports");
132 let current_crate = self.module_with_name_to_import.krate();
133 ImportsLocator::new(db, current_crate)
134 .find_imports(&self.get_search_query())
136 .filter_map(|candidate| match &self.import_candidate {
137 ImportCandidate::TraitAssocItem(assoc_item_type, _) => {
138 let located_assoc_item = match candidate {
139 Either::Left(ModuleDef::Function(located_function)) => located_function
141 .map(|assoc| assoc.container(db))
142 .and_then(Self::assoc_to_trait),
143 Either::Left(ModuleDef::Const(located_const)) => located_const
145 .map(|assoc| assoc.container(db))
146 .and_then(Self::assoc_to_trait),
150 let mut trait_candidates = FxHashSet::default();
151 trait_candidates.insert(located_assoc_item.into());
154 .iterate_path_candidates(
159 |_, assoc| Self::assoc_to_trait(assoc.container(db)),
161 .map(ModuleDef::from)
164 ImportCandidate::TraitMethod(function_callee, _) => {
165 let located_assoc_item =
166 if let Either::Left(ModuleDef::Function(located_function)) = candidate {
169 .map(|assoc| assoc.container(db))
170 .and_then(Self::assoc_to_trait)
175 let mut trait_candidates = FxHashSet::default();
176 trait_candidates.insert(located_assoc_item.into());
179 .iterate_method_candidates(
185 Self::assoc_to_trait(function.as_assoc_item(db)?.container(db))
188 .map(ModuleDef::from)
191 _ => Some(candidate),
193 .filter_map(|candidate| match candidate {
194 Either::Left(module_def) => {
195 self.module_with_name_to_import.find_use_path(db, module_def)
197 Either::Right(macro_def) => {
198 self.module_with_name_to_import.find_use_path(db, macro_def)
201 .filter(|use_path| !use_path.segments.is_empty())
203 .collect::<BTreeSet<_>>()
206 fn assoc_to_trait(assoc: AssocItemContainer) -> Option<Trait> {
207 if let AssocItemContainer::Trait(extracted_trait) = assoc {
208 Some(extracted_trait)
216 enum ImportCandidate {
217 /// Simple name like 'HashMap'
218 UnqualifiedName(String),
219 /// First part of the qualified name.
220 /// For 'std::collections::HashMap', that will be 'std'.
221 QualifierStart(String),
222 /// A trait associated function (with no self parameter) or associated constant.
223 /// For 'test_mod::TestEnum::test_function', `Type` is the `test_mod::TestEnum` expression type
224 /// and `String` is the `test_function`
225 TraitAssocItem(Type, String),
226 /// A trait method with self parameter.
227 /// For 'test_enum.test_method()', `Type` is the `test_enum` expression type
228 /// and `String` is the `test_method`
229 TraitMethod(Type, String),
232 impl ImportCandidate {
234 sema: &Semantics<RootDatabase>,
235 method_call: &ast::MethodCallExpr,
237 if sema.resolve_method_call(method_call).is_some() {
240 Some(Self::TraitMethod(
241 sema.type_of_expr(&method_call.expr()?)?,
242 method_call.name_ref()?.syntax().to_string(),
247 sema: &Semantics<RootDatabase>,
248 path_under_caret: &ast::Path,
250 if sema.resolve_path(path_under_caret).is_some() {
254 let segment = path_under_caret.segment()?;
255 if let Some(qualifier) = path_under_caret.qualifier() {
256 let qualifier_start = qualifier.syntax().descendants().find_map(ast::NameRef::cast)?;
257 let qualifier_start_path =
258 qualifier_start.syntax().ancestors().find_map(ast::Path::cast)?;
259 if let Some(qualifier_start_resolution) = sema.resolve_path(&qualifier_start_path) {
260 let qualifier_resolution = if qualifier_start_path == qualifier {
261 qualifier_start_resolution
263 sema.resolve_path(&qualifier)?
265 if let PathResolution::Def(ModuleDef::Adt(assoc_item_path)) = qualifier_resolution {
266 Some(ImportCandidate::TraitAssocItem(
267 assoc_item_path.ty(sema.db),
268 segment.syntax().to_string(),
274 Some(ImportCandidate::QualifierStart(qualifier_start.syntax().to_string()))
277 Some(ImportCandidate::UnqualifiedName(
278 segment.syntax().descendants().find_map(ast::NameRef::cast)?.syntax().to_string(),
287 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
290 fn applicable_when_found_an_import() {
297 pub struct PubStruct;
301 use PubMod::PubStruct;
306 pub struct PubStruct;
313 fn applicable_when_found_an_import_in_macros() {
318 ($i:ident) => { fn foo(a: $i) {} }
323 pub struct PubStruct;
327 use PubMod::PubStruct;
330 ($i:ident) => { fn foo(a: $i) {} }
335 pub struct PubStruct;
342 fn auto_imports_are_merged() {
346 use PubMod::PubStruct1;
349 test: Pub<|>Struct2<u8>,
353 pub struct PubStruct1;
354 pub struct PubStruct2<T> {
360 use PubMod::{PubStruct2, PubStruct1};
363 test: PubStruct2<u8>,
367 pub struct PubStruct1;
368 pub struct PubStruct2<T> {
377 fn applicable_when_found_multiple_imports() {
384 pub struct PubStruct;
387 pub struct PubStruct;
390 pub struct PubStruct;
394 use PubMod3::PubStruct;
399 pub struct PubStruct;
402 pub struct PubStruct;
405 pub struct PubStruct;
412 fn not_applicable_for_already_imported_types() {
413 check_assist_not_applicable(
416 use PubMod::PubStruct;
421 pub struct PubStruct;
428 fn not_applicable_for_types_with_private_paths() {
429 check_assist_not_applicable(
435 struct PrivateStruct;
442 fn not_applicable_when_no_imports_found() {
443 check_assist_not_applicable(
451 fn not_applicable_in_import_statements() {
452 check_assist_not_applicable(
458 pub struct PubStruct;
464 fn function_import() {
471 pub fn test_function() {};
475 use PubMod::test_function;
480 pub fn test_function() {};
491 //- /lib.rs crate:crate_with_macro
497 //- /main.rs crate:main deps:crate_with_macro
502 r"use crate_with_macro::foo;
512 fn auto_import_target() {
517 group_label: Option<<|>GroupLabel>,
520 mod m { pub struct GroupLabel; }
527 fn not_applicable_when_path_start_is_imported() {
528 check_assist_not_applicable(
534 pub struct TestStruct;
541 mod2::mod3::TestStruct<|>
548 fn not_applicable_for_imported_function() {
549 check_assist_not_applicable(
553 pub fn test_function() {}
556 use test_mod::test_function;
565 fn associated_struct_function() {
570 pub struct TestStruct {}
572 pub fn test_function() {}
577 TestStruct::test_function<|>
581 use test_mod::TestStruct;
584 pub struct TestStruct {}
586 pub fn test_function() {}
591 TestStruct::test_function
598 fn associated_struct_const() {
603 pub struct TestStruct {}
605 const TEST_CONST: u8 = 42;
610 TestStruct::TEST_CONST<|>
614 use test_mod::TestStruct;
617 pub struct TestStruct {}
619 const TEST_CONST: u8 = 42;
624 TestStruct::TEST_CONST
631 fn associated_trait_function() {
636 pub trait TestTrait {
639 pub struct TestStruct {}
640 impl TestTrait for TestStruct {
641 fn test_function() {}
646 test_mod::TestStruct::test_function<|>
650 use test_mod::TestTrait;
653 pub trait TestTrait {
656 pub struct TestStruct {}
657 impl TestTrait for TestStruct {
658 fn test_function() {}
663 test_mod::TestStruct::test_function
670 fn not_applicable_for_imported_trait_for_function() {
671 check_assist_not_applicable(
675 pub trait TestTrait {
678 pub trait TestTrait2 {
685 impl TestTrait2 for TestEnum {
686 fn test_function() {}
688 impl TestTrait for TestEnum {
689 fn test_function() {}
693 use test_mod::TestTrait2;
695 test_mod::TestEnum::test_function<|>;
702 fn associated_trait_const() {
707 pub trait TestTrait {
708 const TEST_CONST: u8;
710 pub struct TestStruct {}
711 impl TestTrait for TestStruct {
712 const TEST_CONST: u8 = 42;
717 test_mod::TestStruct::TEST_CONST<|>
721 use test_mod::TestTrait;
724 pub trait TestTrait {
725 const TEST_CONST: u8;
727 pub struct TestStruct {}
728 impl TestTrait for TestStruct {
729 const TEST_CONST: u8 = 42;
734 test_mod::TestStruct::TEST_CONST
741 fn not_applicable_for_imported_trait_for_const() {
742 check_assist_not_applicable(
746 pub trait TestTrait {
747 const TEST_CONST: u8;
749 pub trait TestTrait2 {
750 const TEST_CONST: f64;
756 impl TestTrait2 for TestEnum {
757 const TEST_CONST: f64 = 42.0;
759 impl TestTrait for TestEnum {
760 const TEST_CONST: u8 = 42;
764 use test_mod::TestTrait2;
766 test_mod::TestEnum::TEST_CONST<|>;
778 pub trait TestTrait {
779 fn test_method(&self);
781 pub struct TestStruct {}
782 impl TestTrait for TestStruct {
783 fn test_method(&self) {}
788 let test_struct = test_mod::TestStruct {};
789 test_struct.test_meth<|>od()
793 use test_mod::TestTrait;
796 pub trait TestTrait {
797 fn test_method(&self);
799 pub struct TestStruct {}
800 impl TestTrait for TestStruct {
801 fn test_method(&self) {}
806 let test_struct = test_mod::TestStruct {};
807 test_struct.test_method()
814 fn not_applicable_for_imported_trait_for_method() {
815 check_assist_not_applicable(
819 pub trait TestTrait {
820 fn test_method(&self);
822 pub trait TestTrait2 {
823 fn test_method(&self);
829 impl TestTrait2 for TestEnum {
830 fn test_method(&self) {}
832 impl TestTrait for TestEnum {
833 fn test_method(&self) {}
837 use test_mod::TestTrait2;
839 let one = test_mod::TestEnum::One;
840 one.test<|>_method();
851 //- /lib.rs crate:dep
854 //- /main.rs crate:main deps:dep
870 // Tests that only imports whose last segment matches the identifier get suggested.
874 //- /lib.rs crate:dep
879 pub fn panic_fmt() {}
881 //- /main.rs crate:main deps:dep
884 impl f<|>mt::Display for S {}
890 impl fmt::Display for S {}
896 fn macro_generated() {
897 // Tests that macro-generated items are suggested from external crates.
901 //- /lib.rs crate:dep
910 //- /main.rs crate:main deps:dep
926 // Tests that differently cased names don't interfere and we only suggest the matching one.
930 //- /lib.rs crate:dep
934 //- /main.rs crate:main deps:dep