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),
53 insert_use_statement(&auto_import_assets.syntax_under_caret, &import, ctx, builder);
61 struct AutoImportAssets {
62 import_candidate: ImportCandidate,
63 module_with_name_to_import: Module,
64 syntax_under_caret: SyntaxNode,
67 impl AutoImportAssets {
68 fn new(ctx: &AssistContext) -> Option<Self> {
69 if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() {
70 Self::for_regular_path(path_under_caret, &ctx)
72 Self::for_method_call(ctx.find_node_at_offset_with_descend()?, &ctx)
76 fn for_method_call(method_call: ast::MethodCallExpr, ctx: &AssistContext) -> Option<Self> {
77 let syntax_under_caret = method_call.syntax().to_owned();
78 let module_with_name_to_import = ctx.sema.scope(&syntax_under_caret).module()?;
80 import_candidate: ImportCandidate::for_method_call(&ctx.sema, &method_call)?,
81 module_with_name_to_import,
86 fn for_regular_path(path_under_caret: ast::Path, ctx: &AssistContext) -> Option<Self> {
87 let syntax_under_caret = path_under_caret.syntax().to_owned();
88 if syntax_under_caret.ancestors().find_map(ast::UseItem::cast).is_some() {
92 let module_with_name_to_import = ctx.sema.scope(&syntax_under_caret).module()?;
94 import_candidate: ImportCandidate::for_regular_path(&ctx.sema, &path_under_caret)?,
95 module_with_name_to_import,
100 fn get_search_query(&self) -> &str {
101 match &self.import_candidate {
102 ImportCandidate::UnqualifiedName(name) => name,
103 ImportCandidate::QualifierStart(qualifier_start) => qualifier_start,
104 ImportCandidate::TraitAssocItem(_, trait_assoc_item_name) => trait_assoc_item_name,
105 ImportCandidate::TraitMethod(_, trait_method_name) => trait_method_name,
109 fn get_import_group_message(&self) -> GroupLabel {
110 let name = match &self.import_candidate {
111 ImportCandidate::UnqualifiedName(name) => format!("Import {}", name),
112 ImportCandidate::QualifierStart(qualifier_start) => {
113 format!("Import {}", qualifier_start)
115 ImportCandidate::TraitAssocItem(_, trait_assoc_item_name) => {
116 format!("Import a trait for item {}", trait_assoc_item_name)
118 ImportCandidate::TraitMethod(_, trait_method_name) => {
119 format!("Import a trait for method {}", trait_method_name)
125 fn search_for_imports(&self, db: &RootDatabase) -> BTreeSet<ModPath> {
126 let _p = profile("auto_import::search_for_imports");
127 let current_crate = self.module_with_name_to_import.krate();
128 ImportsLocator::new(db)
129 .find_imports(&self.get_search_query())
131 .filter_map(|candidate| match &self.import_candidate {
132 ImportCandidate::TraitAssocItem(assoc_item_type, _) => {
133 let located_assoc_item = match candidate {
134 Either::Left(ModuleDef::Function(located_function)) => located_function
136 .map(|assoc| assoc.container(db))
137 .and_then(Self::assoc_to_trait),
138 Either::Left(ModuleDef::Const(located_const)) => located_const
140 .map(|assoc| assoc.container(db))
141 .and_then(Self::assoc_to_trait),
145 let mut trait_candidates = FxHashSet::default();
146 trait_candidates.insert(located_assoc_item.into());
149 .iterate_path_candidates(
154 |_, assoc| Self::assoc_to_trait(assoc.container(db)),
156 .map(ModuleDef::from)
159 ImportCandidate::TraitMethod(function_callee, _) => {
160 let located_assoc_item =
161 if let Either::Left(ModuleDef::Function(located_function)) = candidate {
164 .map(|assoc| assoc.container(db))
165 .and_then(Self::assoc_to_trait)
170 let mut trait_candidates = FxHashSet::default();
171 trait_candidates.insert(located_assoc_item.into());
174 .iterate_method_candidates(
180 Self::assoc_to_trait(function.as_assoc_item(db)?.container(db))
183 .map(ModuleDef::from)
186 _ => Some(candidate),
188 .filter_map(|candidate| match candidate {
189 Either::Left(module_def) => {
190 self.module_with_name_to_import.find_use_path(db, module_def)
192 Either::Right(macro_def) => {
193 self.module_with_name_to_import.find_use_path(db, macro_def)
196 .filter(|use_path| !use_path.segments.is_empty())
198 .collect::<BTreeSet<_>>()
201 fn assoc_to_trait(assoc: AssocItemContainer) -> Option<Trait> {
202 if let AssocItemContainer::Trait(extracted_trait) = assoc {
203 Some(extracted_trait)
211 enum ImportCandidate {
212 /// Simple name like 'HashMap'
213 UnqualifiedName(String),
214 /// First part of the qualified name.
215 /// For 'std::collections::HashMap', that will be 'std'.
216 QualifierStart(String),
217 /// A trait associated function (with no self parameter) or associated constant.
218 /// For 'test_mod::TestEnum::test_function', `Type` is the `test_mod::TestEnum` expression type
219 /// and `String` is the `test_function`
220 TraitAssocItem(Type, String),
221 /// A trait method with self parameter.
222 /// For 'test_enum.test_method()', `Type` is the `test_enum` expression type
223 /// and `String` is the `test_method`
224 TraitMethod(Type, String),
227 impl ImportCandidate {
229 sema: &Semantics<RootDatabase>,
230 method_call: &ast::MethodCallExpr,
232 if sema.resolve_method_call(method_call).is_some() {
235 Some(Self::TraitMethod(
236 sema.type_of_expr(&method_call.expr()?)?,
237 method_call.name_ref()?.syntax().to_string(),
242 sema: &Semantics<RootDatabase>,
243 path_under_caret: &ast::Path,
245 if sema.resolve_path(path_under_caret).is_some() {
249 let segment = path_under_caret.segment()?;
250 if let Some(qualifier) = path_under_caret.qualifier() {
251 let qualifier_start = qualifier.syntax().descendants().find_map(ast::NameRef::cast)?;
252 let qualifier_start_path =
253 qualifier_start.syntax().ancestors().find_map(ast::Path::cast)?;
254 if let Some(qualifier_start_resolution) = sema.resolve_path(&qualifier_start_path) {
255 let qualifier_resolution = if qualifier_start_path == qualifier {
256 qualifier_start_resolution
258 sema.resolve_path(&qualifier)?
260 if let PathResolution::Def(ModuleDef::Adt(assoc_item_path)) = qualifier_resolution {
261 Some(ImportCandidate::TraitAssocItem(
262 assoc_item_path.ty(sema.db),
263 segment.syntax().to_string(),
269 Some(ImportCandidate::QualifierStart(qualifier_start.syntax().to_string()))
272 Some(ImportCandidate::UnqualifiedName(
273 segment.syntax().descendants().find_map(ast::NameRef::cast)?.syntax().to_string(),
282 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
285 fn applicable_when_found_an_import() {
292 pub struct PubStruct;
296 <|>use PubMod::PubStruct;
301 pub struct PubStruct;
308 fn applicable_when_found_an_import_in_macros() {
313 ($i:ident) => { fn foo(a: $i) {} }
318 pub struct PubStruct;
322 use PubMod::PubStruct;
325 ($i:ident) => { fn foo(a: $i) {} }
330 pub struct PubStruct;
337 fn auto_imports_are_merged() {
341 use PubMod::PubStruct1;
344 test: Pub<|>Struct2<u8>,
348 pub struct PubStruct1;
349 pub struct PubStruct2<T> {
355 use PubMod::{PubStruct2, PubStruct1};
358 test: Pub<|>Struct2<u8>,
362 pub struct PubStruct1;
363 pub struct PubStruct2<T> {
372 fn applicable_when_found_multiple_imports() {
379 pub struct PubStruct;
382 pub struct PubStruct;
385 pub struct PubStruct;
389 use PubMod3::PubStruct;
394 pub struct PubStruct;
397 pub struct PubStruct;
400 pub struct PubStruct;
407 fn not_applicable_for_already_imported_types() {
408 check_assist_not_applicable(
411 use PubMod::PubStruct;
416 pub struct PubStruct;
423 fn not_applicable_for_types_with_private_paths() {
424 check_assist_not_applicable(
430 struct PrivateStruct;
437 fn not_applicable_when_no_imports_found() {
438 check_assist_not_applicable(
446 fn not_applicable_in_import_statements() {
447 check_assist_not_applicable(
453 pub struct PubStruct;
459 fn function_import() {
466 pub fn test_function() {};
470 use PubMod::test_function;
475 pub fn test_function() {};
486 //- /lib.rs crate:crate_with_macro
492 //- /main.rs crate:main deps:crate_with_macro
496 r"use crate_with_macro::foo;
506 fn auto_import_target() {
511 group_label: Option<<|>GroupLabel>,
514 mod m { pub struct GroupLabel; }
521 fn not_applicable_when_path_start_is_imported() {
522 check_assist_not_applicable(
528 pub struct TestStruct;
535 mod2::mod3::TestStruct<|>
542 fn not_applicable_for_imported_function() {
543 check_assist_not_applicable(
547 pub fn test_function() {}
550 use test_mod::test_function;
559 fn associated_struct_function() {
564 pub struct TestStruct {}
566 pub fn test_function() {}
571 TestStruct::test_function<|>
575 use test_mod::TestStruct;
578 pub struct TestStruct {}
580 pub fn test_function() {}
585 TestStruct::test_function<|>
592 fn associated_struct_const() {
597 pub struct TestStruct {}
599 const TEST_CONST: u8 = 42;
604 TestStruct::TEST_CONST<|>
608 use test_mod::TestStruct;
611 pub struct TestStruct {}
613 const TEST_CONST: u8 = 42;
618 TestStruct::TEST_CONST<|>
625 fn associated_trait_function() {
630 pub trait TestTrait {
633 pub struct TestStruct {}
634 impl TestTrait for TestStruct {
635 fn test_function() {}
640 test_mod::TestStruct::test_function<|>
644 use test_mod::TestTrait;
647 pub trait TestTrait {
650 pub struct TestStruct {}
651 impl TestTrait for TestStruct {
652 fn test_function() {}
657 test_mod::TestStruct::test_function<|>
664 fn not_applicable_for_imported_trait_for_function() {
665 check_assist_not_applicable(
669 pub trait TestTrait {
672 pub trait TestTrait2 {
679 impl TestTrait2 for TestEnum {
680 fn test_function() {}
682 impl TestTrait for TestEnum {
683 fn test_function() {}
687 use test_mod::TestTrait2;
689 test_mod::TestEnum::test_function<|>;
696 fn associated_trait_const() {
701 pub trait TestTrait {
702 const TEST_CONST: u8;
704 pub struct TestStruct {}
705 impl TestTrait for TestStruct {
706 const TEST_CONST: u8 = 42;
711 test_mod::TestStruct::TEST_CONST<|>
715 use test_mod::TestTrait;
718 pub trait TestTrait {
719 const TEST_CONST: u8;
721 pub struct TestStruct {}
722 impl TestTrait for TestStruct {
723 const TEST_CONST: u8 = 42;
728 test_mod::TestStruct::TEST_CONST<|>
735 fn not_applicable_for_imported_trait_for_const() {
736 check_assist_not_applicable(
740 pub trait TestTrait {
741 const TEST_CONST: u8;
743 pub trait TestTrait2 {
744 const TEST_CONST: f64;
750 impl TestTrait2 for TestEnum {
751 const TEST_CONST: f64 = 42.0;
753 impl TestTrait for TestEnum {
754 const TEST_CONST: u8 = 42;
758 use test_mod::TestTrait2;
760 test_mod::TestEnum::TEST_CONST<|>;
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<|>od()
787 use test_mod::TestTrait;
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<|>od()
808 fn not_applicable_for_imported_trait_for_method() {
809 check_assist_not_applicable(
813 pub trait TestTrait {
814 fn test_method(&self);
816 pub trait TestTrait2 {
817 fn test_method(&self);
823 impl TestTrait2 for TestEnum {
824 fn test_method(&self) {}
826 impl TestTrait for TestEnum {
827 fn test_method(&self) {}
831 use test_mod::TestTrait2;
833 let one = test_mod::TestEnum::One;
834 one.test<|>_method();