3 use hir::{db::HirDatabase, Module};
5 helpers::mod_path_to_ast,
7 import_assets::{ImportAssets, ImportCandidate, LocatedImport},
8 insert_use::{insert_use, ImportScope},
11 use syntax::{ast, AstNode, NodeOrToken, SyntaxElement};
13 use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel};
15 // Feature: Auto Import
17 // Using the `auto-import` assist it is possible to insert missing imports for unresolved items.
18 // When inserting an import it will do so in a structured manner by keeping imports grouped,
19 // separated by a newline in the following order:
23 // - Current Crate, paths prefixed by `crate`
24 // - Current Module, paths prefixed by `self`
25 // - Super Module, paths prefixed by `super`
31 // use itertools::Itertools;
34 // use crate::utils::insert_use;
36 // use self::auto_import;
38 // use super::AssistContext;
41 // .Import Granularity
43 // It is possible to configure how use-trees are merged with the `imports.granularity.group` setting.
44 // It has the following configurations:
46 // - `crate`: Merge imports from the same crate into a single use statement. This kind of
47 // nesting is only supported in Rust versions later than 1.24.
48 // - `module`: Merge imports from the same module into a single use statement.
49 // - `item`: Don't merge imports at all, creating one import per item.
50 // - `preserve`: Do not change the granularity of any imports. For auto-import this has the same
53 // In `VS Code` the configuration for this is `rust-analyzer.imports.granularity.group`.
57 // The style of imports in the same crate is configurable through the `imports.prefix` setting.
58 // It has the following configurations:
60 // - `crate`: This setting will force paths to be always absolute, starting with the `crate`
61 // prefix, unless the item is defined outside of the current crate.
62 // - `self`: This setting will force paths that are relative to the current module to always
63 // start with `self`. This will result in paths that always start with either `crate`, `self`,
64 // `super` or an extern crate identifier.
65 // - `plain`: This setting does not impose any restrictions in imports.
67 // In `VS Code` the configuration for this is `rust-analyzer.imports.prefix`.
69 // image::https://user-images.githubusercontent.com/48062697/113020673-b85be580-917a-11eb-9022-59585f35d4f8.gif[]
71 // Assist: auto_import
73 // If the name is unresolved, provides all possible imports for it.
77 // let map = HashMap$0::new();
79 // # pub mod std { pub mod collections { pub struct HashMap { } } }
83 // use std::collections::HashMap;
86 // let map = HashMap::new();
88 // # pub mod std { pub mod collections { pub struct HashMap { } } }
90 pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
91 let (import_assets, syntax_under_caret) = find_importable_node(ctx)?;
92 let mut proposed_imports = import_assets.search_for_imports(
94 ctx.config.insert_use.prefix_kind,
95 ctx.config.prefer_no_std,
97 if proposed_imports.is_empty() {
101 let range = match &syntax_under_caret {
102 NodeOrToken::Node(node) => ctx.sema.original_range(node).range,
103 NodeOrToken::Token(token) => token.text_range(),
105 let group_label = group_label(import_assets.import_candidate());
106 let scope = ImportScope::find_insert_use_container(
107 &match syntax_under_caret {
108 NodeOrToken::Node(it) => it,
109 NodeOrToken::Token(it) => it.parent()?,
114 // we aren't interested in different namespaces
115 proposed_imports.dedup_by(|a, b| a.import_path == b.import_path);
117 let current_node = match ctx.covering_element() {
118 NodeOrToken::Node(node) => Some(node),
119 NodeOrToken::Token(token) => token.parent(),
123 current_node.as_ref().and_then(|node| ctx.sema.scope(node)).map(|scope| scope.module());
125 // prioritize more relevant imports
127 .sort_by_key(|import| Reverse(relevance_score(ctx, import, current_module.as_ref())));
129 for import in proposed_imports {
132 AssistId("auto_import", AssistKind::QuickFix),
133 format!("Import `{}`", import.import_path),
136 let scope = match scope.clone() {
137 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
138 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
139 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
141 insert_use(&scope, mod_path_to_ast(&import.import_path), &ctx.config.insert_use);
148 pub(super) fn find_importable_node(
149 ctx: &AssistContext<'_>,
150 ) -> Option<(ImportAssets, SyntaxElement)> {
151 if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() {
152 ImportAssets::for_exact_path(&path_under_caret, &ctx.sema)
153 .zip(Some(path_under_caret.syntax().clone().into()))
154 } else if let Some(method_under_caret) =
155 ctx.find_node_at_offset_with_descend::<ast::MethodCallExpr>()
157 ImportAssets::for_method_call(&method_under_caret, &ctx.sema)
158 .zip(Some(method_under_caret.syntax().clone().into()))
159 } else if let Some(_) = ctx.find_node_at_offset_with_descend::<ast::Param>() {
161 } else if let Some(pat) = ctx
162 .find_node_at_offset_with_descend::<ast::IdentPat>()
163 .filter(ast::IdentPat::is_simple_ident)
165 ImportAssets::for_ident_pat(&ctx.sema, &pat).zip(Some(pat.syntax().clone().into()))
171 fn group_label(import_candidate: &ImportCandidate) -> GroupLabel {
172 let name = match import_candidate {
173 ImportCandidate::Path(candidate) => format!("Import {}", candidate.name.text()),
174 ImportCandidate::TraitAssocItem(candidate) => {
175 format!("Import a trait for item {}", candidate.assoc_item_name.text())
177 ImportCandidate::TraitMethod(candidate) => {
178 format!("Import a trait for method {}", candidate.assoc_item_name.text())
184 /// Determine how relevant a given import is in the current context. Higher scores are more
187 ctx: &AssistContext<'_>,
188 import: &LocatedImport,
189 current_module: Option<&Module>,
195 let item_module = match import.item_to_import {
196 hir::ItemInNs::Types(item) | hir::ItemInNs::Values(item) => item.module(db),
197 hir::ItemInNs::Macros(makro) => Some(makro.module(db)),
200 match item_module.zip(current_module) {
201 // get the distance between the imported path and the current module
202 // (prefer items that are more local)
203 Some((item_module, current_module)) => {
204 score -= module_distance_hueristic(db, ¤t_module, &item_module) as i32;
207 // could not find relevant modules, so just use the length of the path as an estimate
208 None => return -(2 * import.import_path.len() as i32),
214 /// A heuristic that gives a higher score to modules that are more separated.
215 fn module_distance_hueristic(db: &dyn HirDatabase, current: &Module, item: &Module) -> usize {
216 // get the path starting from the item to the respective crate roots
217 let mut current_path = current.path_to_root(db);
218 let mut item_path = item.path_to_root(db);
220 // we want paths going from the root to the item
221 current_path.reverse();
224 // length of the common prefix of the two paths
225 let prefix_length = current_path.iter().zip(&item_path).take_while(|(a, b)| a == b).count();
227 // how many modules differ between the two paths (all modules, removing any duplicates)
228 let distinct_length = current_path.len() + item_path.len() - 2 * prefix_length;
230 // cost of importing from another crate
231 let crate_boundary_cost = if current.krate() == item.krate() {
233 } else if item.krate().is_builtin(db) {
239 distinct_length + crate_boundary_cost
248 assists::AssistResolveStrategy,
249 base_db::{fixture::WithFixture, FileRange},
254 check_assist, check_assist_not_applicable, check_assist_target, TEST_CONFIG,
257 fn check_auto_import_order(before: &str, order: &[&str]) {
258 let (db, file_id, range_or_offset) = RootDatabase::with_range_or_offset(before);
259 let frange = FileRange { file_id, range: range_or_offset.into() };
261 let sema = Semantics::new(&db);
262 let config = TEST_CONFIG;
263 let ctx = AssistContext::new(sema, &config, frange);
264 let mut acc = Assists::new(&ctx, AssistResolveStrategy::All);
265 auto_import(&mut acc, &ctx);
266 let assists = acc.finish();
268 let labels = assists.iter().map(|assist| assist.label.to_string()).collect::<Vec<_>>();
270 assert_eq!(labels, order);
274 fn ignore_parameter_name() {
275 check_assist_not_applicable(
282 fn foo(bar$0: &str) {}
288 fn prefer_shorter_paths() {
290 //- /main.rs crate:main deps:foo,bar
293 //- /lib.rs crate:foo
294 pub mod collections { pub struct HashMap; }
296 //- /lib.rs crate:bar
297 pub mod collections { pub mod hash_map { pub struct HashMap; } }
300 check_auto_import_order(
302 &["Import `foo::collections::HashMap`", "Import `bar::collections::hash_map::HashMap`"],
307 fn prefer_same_crate() {
309 //- /main.rs crate:main deps:foo
318 //- /lib.rs crate:foo
322 check_auto_import_order(
324 &["Import `collections::hash_map::HashMap`", "Import `foo::HashMap`"],
329 fn not_applicable_if_scope_inside_macro() {
330 check_assist_not_applicable(
351 fn applicable_in_attributes() {
355 //- proc_macros: identity
356 #[proc_macros::identity]
367 #[proc_macros::identity]
383 fn applicable_when_found_an_import_partial() {
389 pub struct Formatter;
400 pub struct Formatter;
404 use std::fmt::{self, Formatter};
412 fn applicable_when_found_an_import() {
419 pub struct PubStruct;
423 use PubMod::PubStruct;
428 pub struct PubStruct;
435 fn applicable_when_found_an_import_in_macros() {
440 ($i:ident) => { fn foo(a: $i) {} }
445 pub struct PubStruct;
449 use PubMod::PubStruct;
452 ($i:ident) => { fn foo(a: $i) {} }
457 pub struct PubStruct;
464 fn applicable_when_found_multiple_imports() {
471 pub struct PubStruct;
474 pub struct PubStruct;
477 pub struct PubStruct;
481 use PubMod3::PubStruct;
486 pub struct PubStruct;
489 pub struct PubStruct;
492 pub struct PubStruct;
499 fn not_applicable_for_already_imported_types() {
500 check_assist_not_applicable(
503 use PubMod::PubStruct;
508 pub struct PubStruct;
515 fn not_applicable_for_types_with_private_paths() {
516 check_assist_not_applicable(
522 struct PrivateStruct;
529 fn not_applicable_when_no_imports_found() {
530 check_assist_not_applicable(
538 fn function_import() {
545 pub fn test_function() {};
549 use PubMod::test_function;
554 pub fn test_function() {};
565 //- /lib.rs crate:crate_with_macro
571 //- /main.rs crate:main deps:crate_with_macro
576 r"use crate_with_macro::foo;
586 fn auto_import_target() {
591 group_label: Option<$0GroupLabel>,
594 mod m { pub struct GroupLabel; }
601 fn not_applicable_when_path_start_is_imported() {
602 check_assist_not_applicable(
608 pub struct TestStruct;
615 mod2::mod3::TestStruct$0
622 fn not_applicable_for_imported_function() {
623 check_assist_not_applicable(
627 pub fn test_function() {}
630 use test_mod::test_function;
639 fn associated_struct_function() {
644 pub struct TestStruct {}
646 pub fn test_function() {}
651 TestStruct::test_function$0
655 use test_mod::TestStruct;
658 pub struct TestStruct {}
660 pub fn test_function() {}
665 TestStruct::test_function
672 fn associated_struct_const() {
677 pub struct TestStruct {}
679 const TEST_CONST: u8 = 42;
684 TestStruct::TEST_CONST$0
688 use test_mod::TestStruct;
691 pub struct TestStruct {}
693 const TEST_CONST: u8 = 42;
698 TestStruct::TEST_CONST
705 fn associated_trait_function() {
710 pub trait TestTrait {
713 pub struct TestStruct {}
714 impl TestTrait for TestStruct {
715 fn test_function() {}
720 test_mod::TestStruct::test_function$0
724 use test_mod::TestTrait;
727 pub trait TestTrait {
730 pub struct TestStruct {}
731 impl TestTrait for TestStruct {
732 fn test_function() {}
737 test_mod::TestStruct::test_function
744 fn not_applicable_for_imported_trait_for_function() {
745 check_assist_not_applicable(
749 pub trait TestTrait {
752 pub trait TestTrait2 {
759 impl TestTrait2 for TestEnum {
760 fn test_function() {}
762 impl TestTrait for TestEnum {
763 fn test_function() {}
767 use test_mod::TestTrait2;
769 test_mod::TestEnum::test_function$0;
776 fn associated_trait_const() {
781 pub trait TestTrait {
782 const TEST_CONST: u8;
784 pub struct TestStruct {}
785 impl TestTrait for TestStruct {
786 const TEST_CONST: u8 = 42;
791 test_mod::TestStruct::TEST_CONST$0
795 use test_mod::TestTrait;
798 pub trait TestTrait {
799 const TEST_CONST: u8;
801 pub struct TestStruct {}
802 impl TestTrait for TestStruct {
803 const TEST_CONST: u8 = 42;
808 test_mod::TestStruct::TEST_CONST
815 fn not_applicable_for_imported_trait_for_const() {
816 check_assist_not_applicable(
820 pub trait TestTrait {
821 const TEST_CONST: u8;
823 pub trait TestTrait2 {
824 const TEST_CONST: f64;
830 impl TestTrait2 for TestEnum {
831 const TEST_CONST: f64 = 42.0;
833 impl TestTrait for TestEnum {
834 const TEST_CONST: u8 = 42;
838 use test_mod::TestTrait2;
840 test_mod::TestEnum::TEST_CONST$0;
852 pub trait TestTrait {
853 fn test_method(&self);
855 pub struct TestStruct {}
856 impl TestTrait for TestStruct {
857 fn test_method(&self) {}
862 let test_struct = test_mod::TestStruct {};
863 test_struct.test_meth$0od()
867 use test_mod::TestTrait;
870 pub trait TestTrait {
871 fn test_method(&self);
873 pub struct TestStruct {}
874 impl TestTrait for TestStruct {
875 fn test_method(&self) {}
880 let test_struct = test_mod::TestStruct {};
881 test_struct.test_method()
888 fn trait_method_cross_crate() {
892 //- /main.rs crate:main deps:dep
894 let test_struct = dep::test_mod::TestStruct {};
895 test_struct.test_meth$0od()
897 //- /dep.rs crate:dep
899 pub trait TestTrait {
900 fn test_method(&self);
902 pub struct TestStruct {}
903 impl TestTrait for TestStruct {
904 fn test_method(&self) {}
909 use dep::test_mod::TestTrait;
912 let test_struct = dep::test_mod::TestStruct {};
913 test_struct.test_method()
920 fn assoc_fn_cross_crate() {
924 //- /main.rs crate:main deps:dep
926 dep::test_mod::TestStruct::test_func$0tion
928 //- /dep.rs crate:dep
930 pub trait TestTrait {
933 pub struct TestStruct {}
934 impl TestTrait for TestStruct {
935 fn test_function() {}
940 use dep::test_mod::TestTrait;
943 dep::test_mod::TestStruct::test_function
950 fn assoc_const_cross_crate() {
954 //- /main.rs crate:main deps:dep
956 dep::test_mod::TestStruct::CONST$0
958 //- /dep.rs crate:dep
960 pub trait TestTrait {
963 pub struct TestStruct {}
964 impl TestTrait for TestStruct {
965 const CONST: bool = true;
970 use dep::test_mod::TestTrait;
973 dep::test_mod::TestStruct::CONST
980 fn assoc_fn_as_method_cross_crate() {
981 check_assist_not_applicable(
984 //- /main.rs crate:main deps:dep
986 let test_struct = dep::test_mod::TestStruct {};
987 test_struct.test_func$0tion()
989 //- /dep.rs crate:dep
991 pub trait TestTrait {
994 pub struct TestStruct {}
995 impl TestTrait for TestStruct {
996 fn test_function() {}
1004 fn private_trait_cross_crate() {
1005 check_assist_not_applicable(
1008 //- /main.rs crate:main deps:dep
1010 let test_struct = dep::test_mod::TestStruct {};
1011 test_struct.test_meth$0od()
1013 //- /dep.rs crate:dep
1016 fn test_method(&self);
1018 pub struct TestStruct {}
1019 impl TestTrait for TestStruct {
1020 fn test_method(&self) {}
1028 fn not_applicable_for_imported_trait_for_method() {
1029 check_assist_not_applicable(
1033 pub trait TestTrait {
1034 fn test_method(&self);
1036 pub trait TestTrait2 {
1037 fn test_method(&self);
1043 impl TestTrait2 for TestEnum {
1044 fn test_method(&self) {}
1046 impl TestTrait for TestEnum {
1047 fn test_method(&self) {}
1051 use test_mod::TestTrait2;
1053 let one = test_mod::TestEnum::One;
1054 one.test$0_method();
1065 //- /lib.rs crate:dep
1068 //- /main.rs crate:main deps:dep
1083 fn whole_segment() {
1084 // Tests that only imports whose last segment matches the identifier get suggested.
1088 //- /lib.rs crate:dep
1090 pub trait Display {}
1093 pub fn panic_fmt() {}
1095 //- /main.rs crate:main deps:dep
1098 impl f$0mt::Display for S {}
1104 impl fmt::Display for S {}
1110 fn macro_generated() {
1111 // Tests that macro-generated items are suggested from external crates.
1115 //- /lib.rs crate:dep
1124 //- /main.rs crate:main deps:dep
1140 // Tests that differently cased names don't interfere and we only suggest the matching one.
1144 //- /lib.rs crate:dep
1148 //- /main.rs crate:main deps:dep
1184 use crate::baz::Foo;
1196 fn uses_abs_path_with_extern_crate_clash() {
1197 cov_mark::check!(ambiguous_crate_start);
1201 //- /main.rs crate:main deps:foo
1207 //- /foo.rs crate:foo
1223 fn works_on_ident_patterns() {
1248 fn works_in_derives() {
1254 #[rustc_builtin_macro]
1264 #[rustc_builtin_macro]
1274 fn works_in_use_start() {
1298 fn not_applicable_in_non_start_use() {
1299 check_assist_not_applicable(