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(pat) = ctx
160 .find_node_at_offset_with_descend::<ast::IdentPat>()
161 .filter(ast::IdentPat::is_simple_ident)
163 ImportAssets::for_ident_pat(&ctx.sema, &pat).zip(Some(pat.syntax().clone().into()))
169 fn group_label(import_candidate: &ImportCandidate) -> GroupLabel {
170 let name = match import_candidate {
171 ImportCandidate::Path(candidate) => format!("Import {}", candidate.name.text()),
172 ImportCandidate::TraitAssocItem(candidate) => {
173 format!("Import a trait for item {}", candidate.assoc_item_name.text())
175 ImportCandidate::TraitMethod(candidate) => {
176 format!("Import a trait for method {}", candidate.assoc_item_name.text())
182 /// Determine how relevant a given import is in the current context. Higher scores are more
185 ctx: &AssistContext<'_>,
186 import: &LocatedImport,
187 current_module: Option<&Module>,
193 let item_module = match import.item_to_import {
194 hir::ItemInNs::Types(item) | hir::ItemInNs::Values(item) => item.module(db),
195 hir::ItemInNs::Macros(makro) => Some(makro.module(db)),
198 match item_module.zip(current_module) {
199 // get the distance between the imported path and the current module
200 // (prefer items that are more local)
201 Some((item_module, current_module)) => {
202 score -= module_distance_hueristic(db, ¤t_module, &item_module) as i32;
205 // could not find relevant modules, so just use the length of the path as an estimate
206 None => return -(2 * import.import_path.len() as i32),
212 /// A heuristic that gives a higher score to modules that are more separated.
213 fn module_distance_hueristic(db: &dyn HirDatabase, current: &Module, item: &Module) -> usize {
214 // get the path starting from the item to the respective crate roots
215 let mut current_path = current.path_to_root(db);
216 let mut item_path = item.path_to_root(db);
218 // we want paths going from the root to the item
219 current_path.reverse();
222 // length of the common prefix of the two paths
223 let prefix_length = current_path.iter().zip(&item_path).take_while(|(a, b)| a == b).count();
225 // how many modules differ between the two paths (all modules, removing any duplicates)
226 let distinct_length = current_path.len() + item_path.len() - 2 * prefix_length;
228 // cost of importing from another crate
229 let crate_boundary_cost = if current.krate() == item.krate() {
231 } else if item.krate().is_builtin(db) {
237 distinct_length + crate_boundary_cost
246 assists::AssistResolveStrategy,
247 base_db::{fixture::WithFixture, FileRange},
252 check_assist, check_assist_not_applicable, check_assist_target, TEST_CONFIG,
255 fn check_auto_import_order(before: &str, order: &[&str]) {
256 let (db, file_id, range_or_offset) = RootDatabase::with_range_or_offset(before);
257 let frange = FileRange { file_id, range: range_or_offset.into() };
259 let sema = Semantics::new(&db);
260 let config = TEST_CONFIG;
261 let ctx = AssistContext::new(sema, &config, frange);
262 let mut acc = Assists::new(&ctx, AssistResolveStrategy::All);
263 auto_import(&mut acc, &ctx);
264 let assists = acc.finish();
266 let labels = assists.iter().map(|assist| assist.label.to_string()).collect::<Vec<_>>();
268 assert_eq!(labels, order);
272 fn prefer_shorter_paths() {
274 //- /main.rs crate:main deps:foo,bar
277 //- /lib.rs crate:foo
278 pub mod collections { pub struct HashMap; }
280 //- /lib.rs crate:bar
281 pub mod collections { pub mod hash_map { pub struct HashMap; } }
284 check_auto_import_order(
286 &["Import `foo::collections::HashMap`", "Import `bar::collections::hash_map::HashMap`"],
291 fn prefer_same_crate() {
293 //- /main.rs crate:main deps:foo
302 //- /lib.rs crate:foo
306 check_auto_import_order(
308 &["Import `collections::hash_map::HashMap`", "Import `foo::HashMap`"],
313 fn not_applicable_if_scope_inside_macro() {
314 check_assist_not_applicable(
335 fn applicable_in_attributes() {
339 //- proc_macros: identity
340 #[proc_macros::identity]
351 #[proc_macros::identity]
367 fn applicable_when_found_an_import_partial() {
373 pub struct Formatter;
384 pub struct Formatter;
388 use std::fmt::{self, Formatter};
396 fn applicable_when_found_an_import() {
403 pub struct PubStruct;
407 use PubMod::PubStruct;
412 pub struct PubStruct;
419 fn applicable_when_found_an_import_in_macros() {
424 ($i:ident) => { fn foo(a: $i) {} }
429 pub struct PubStruct;
433 use PubMod::PubStruct;
436 ($i:ident) => { fn foo(a: $i) {} }
441 pub struct PubStruct;
448 fn applicable_when_found_multiple_imports() {
455 pub struct PubStruct;
458 pub struct PubStruct;
461 pub struct PubStruct;
465 use PubMod3::PubStruct;
470 pub struct PubStruct;
473 pub struct PubStruct;
476 pub struct PubStruct;
483 fn not_applicable_for_already_imported_types() {
484 check_assist_not_applicable(
487 use PubMod::PubStruct;
492 pub struct PubStruct;
499 fn not_applicable_for_types_with_private_paths() {
500 check_assist_not_applicable(
506 struct PrivateStruct;
513 fn not_applicable_when_no_imports_found() {
514 check_assist_not_applicable(
522 fn function_import() {
529 pub fn test_function() {};
533 use PubMod::test_function;
538 pub fn test_function() {};
549 //- /lib.rs crate:crate_with_macro
555 //- /main.rs crate:main deps:crate_with_macro
560 r"use crate_with_macro::foo;
570 fn auto_import_target() {
575 group_label: Option<$0GroupLabel>,
578 mod m { pub struct GroupLabel; }
585 fn not_applicable_when_path_start_is_imported() {
586 check_assist_not_applicable(
592 pub struct TestStruct;
599 mod2::mod3::TestStruct$0
606 fn not_applicable_for_imported_function() {
607 check_assist_not_applicable(
611 pub fn test_function() {}
614 use test_mod::test_function;
623 fn associated_struct_function() {
628 pub struct TestStruct {}
630 pub fn test_function() {}
635 TestStruct::test_function$0
639 use test_mod::TestStruct;
642 pub struct TestStruct {}
644 pub fn test_function() {}
649 TestStruct::test_function
656 fn associated_struct_const() {
661 pub struct TestStruct {}
663 const TEST_CONST: u8 = 42;
668 TestStruct::TEST_CONST$0
672 use test_mod::TestStruct;
675 pub struct TestStruct {}
677 const TEST_CONST: u8 = 42;
682 TestStruct::TEST_CONST
689 fn associated_trait_function() {
694 pub trait TestTrait {
697 pub struct TestStruct {}
698 impl TestTrait for TestStruct {
699 fn test_function() {}
704 test_mod::TestStruct::test_function$0
708 use test_mod::TestTrait;
711 pub trait TestTrait {
714 pub struct TestStruct {}
715 impl TestTrait for TestStruct {
716 fn test_function() {}
721 test_mod::TestStruct::test_function
728 fn not_applicable_for_imported_trait_for_function() {
729 check_assist_not_applicable(
733 pub trait TestTrait {
736 pub trait TestTrait2 {
743 impl TestTrait2 for TestEnum {
744 fn test_function() {}
746 impl TestTrait for TestEnum {
747 fn test_function() {}
751 use test_mod::TestTrait2;
753 test_mod::TestEnum::test_function$0;
760 fn associated_trait_const() {
765 pub trait TestTrait {
766 const TEST_CONST: u8;
768 pub struct TestStruct {}
769 impl TestTrait for TestStruct {
770 const TEST_CONST: u8 = 42;
775 test_mod::TestStruct::TEST_CONST$0
779 use test_mod::TestTrait;
782 pub trait TestTrait {
783 const TEST_CONST: u8;
785 pub struct TestStruct {}
786 impl TestTrait for TestStruct {
787 const TEST_CONST: u8 = 42;
792 test_mod::TestStruct::TEST_CONST
799 fn not_applicable_for_imported_trait_for_const() {
800 check_assist_not_applicable(
804 pub trait TestTrait {
805 const TEST_CONST: u8;
807 pub trait TestTrait2 {
808 const TEST_CONST: f64;
814 impl TestTrait2 for TestEnum {
815 const TEST_CONST: f64 = 42.0;
817 impl TestTrait for TestEnum {
818 const TEST_CONST: u8 = 42;
822 use test_mod::TestTrait2;
824 test_mod::TestEnum::TEST_CONST$0;
836 pub trait TestTrait {
837 fn test_method(&self);
839 pub struct TestStruct {}
840 impl TestTrait for TestStruct {
841 fn test_method(&self) {}
846 let test_struct = test_mod::TestStruct {};
847 test_struct.test_meth$0od()
851 use test_mod::TestTrait;
854 pub trait TestTrait {
855 fn test_method(&self);
857 pub struct TestStruct {}
858 impl TestTrait for TestStruct {
859 fn test_method(&self) {}
864 let test_struct = test_mod::TestStruct {};
865 test_struct.test_method()
872 fn trait_method_cross_crate() {
876 //- /main.rs crate:main deps:dep
878 let test_struct = dep::test_mod::TestStruct {};
879 test_struct.test_meth$0od()
881 //- /dep.rs crate:dep
883 pub trait TestTrait {
884 fn test_method(&self);
886 pub struct TestStruct {}
887 impl TestTrait for TestStruct {
888 fn test_method(&self) {}
893 use dep::test_mod::TestTrait;
896 let test_struct = dep::test_mod::TestStruct {};
897 test_struct.test_method()
904 fn assoc_fn_cross_crate() {
908 //- /main.rs crate:main deps:dep
910 dep::test_mod::TestStruct::test_func$0tion
912 //- /dep.rs crate:dep
914 pub trait TestTrait {
917 pub struct TestStruct {}
918 impl TestTrait for TestStruct {
919 fn test_function() {}
924 use dep::test_mod::TestTrait;
927 dep::test_mod::TestStruct::test_function
934 fn assoc_const_cross_crate() {
938 //- /main.rs crate:main deps:dep
940 dep::test_mod::TestStruct::CONST$0
942 //- /dep.rs crate:dep
944 pub trait TestTrait {
947 pub struct TestStruct {}
948 impl TestTrait for TestStruct {
949 const CONST: bool = true;
954 use dep::test_mod::TestTrait;
957 dep::test_mod::TestStruct::CONST
964 fn assoc_fn_as_method_cross_crate() {
965 check_assist_not_applicable(
968 //- /main.rs crate:main deps:dep
970 let test_struct = dep::test_mod::TestStruct {};
971 test_struct.test_func$0tion()
973 //- /dep.rs crate:dep
975 pub trait TestTrait {
978 pub struct TestStruct {}
979 impl TestTrait for TestStruct {
980 fn test_function() {}
988 fn private_trait_cross_crate() {
989 check_assist_not_applicable(
992 //- /main.rs crate:main deps:dep
994 let test_struct = dep::test_mod::TestStruct {};
995 test_struct.test_meth$0od()
997 //- /dep.rs crate:dep
1000 fn test_method(&self);
1002 pub struct TestStruct {}
1003 impl TestTrait for TestStruct {
1004 fn test_method(&self) {}
1012 fn not_applicable_for_imported_trait_for_method() {
1013 check_assist_not_applicable(
1017 pub trait TestTrait {
1018 fn test_method(&self);
1020 pub trait TestTrait2 {
1021 fn test_method(&self);
1027 impl TestTrait2 for TestEnum {
1028 fn test_method(&self) {}
1030 impl TestTrait for TestEnum {
1031 fn test_method(&self) {}
1035 use test_mod::TestTrait2;
1037 let one = test_mod::TestEnum::One;
1038 one.test$0_method();
1049 //- /lib.rs crate:dep
1052 //- /main.rs crate:main deps:dep
1067 fn whole_segment() {
1068 // Tests that only imports whose last segment matches the identifier get suggested.
1072 //- /lib.rs crate:dep
1074 pub trait Display {}
1077 pub fn panic_fmt() {}
1079 //- /main.rs crate:main deps:dep
1082 impl f$0mt::Display for S {}
1088 impl fmt::Display for S {}
1094 fn macro_generated() {
1095 // Tests that macro-generated items are suggested from external crates.
1099 //- /lib.rs crate:dep
1108 //- /main.rs crate:main deps:dep
1124 // Tests that differently cased names don't interfere and we only suggest the matching one.
1128 //- /lib.rs crate:dep
1132 //- /main.rs crate:main deps:dep
1168 use crate::baz::Foo;
1180 fn uses_abs_path_with_extern_crate_clash() {
1181 cov_mark::check!(ambiguous_crate_start);
1185 //- /main.rs crate:main deps:foo
1191 //- /foo.rs crate:foo
1207 fn works_on_ident_patterns() {
1232 fn works_in_derives() {
1238 #[rustc_builtin_macro]
1248 #[rustc_builtin_macro]
1258 fn works_in_use_start() {
1282 fn not_applicable_in_non_start_use() {
1283 check_assist_not_applicable(