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 {
130 let import_path = import.import_path;
134 AssistId("auto_import", AssistKind::QuickFix),
135 format!("Import `{import_path}`"),
138 let scope = match scope.clone() {
139 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
140 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
141 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
143 insert_use(&scope, mod_path_to_ast(&import_path), &ctx.config.insert_use);
150 pub(super) fn find_importable_node(
151 ctx: &AssistContext<'_>,
152 ) -> Option<(ImportAssets, SyntaxElement)> {
153 if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() {
154 ImportAssets::for_exact_path(&path_under_caret, &ctx.sema)
155 .zip(Some(path_under_caret.syntax().clone().into()))
156 } else if let Some(method_under_caret) =
157 ctx.find_node_at_offset_with_descend::<ast::MethodCallExpr>()
159 ImportAssets::for_method_call(&method_under_caret, &ctx.sema)
160 .zip(Some(method_under_caret.syntax().clone().into()))
161 } else if let Some(_) = ctx.find_node_at_offset_with_descend::<ast::Param>() {
163 } else if let Some(pat) = ctx
164 .find_node_at_offset_with_descend::<ast::IdentPat>()
165 .filter(ast::IdentPat::is_simple_ident)
167 ImportAssets::for_ident_pat(&ctx.sema, &pat).zip(Some(pat.syntax().clone().into()))
173 fn group_label(import_candidate: &ImportCandidate) -> GroupLabel {
174 let name = match import_candidate {
175 ImportCandidate::Path(candidate) => format!("Import {}", candidate.name.text()),
176 ImportCandidate::TraitAssocItem(candidate) => {
177 format!("Import a trait for item {}", candidate.assoc_item_name.text())
179 ImportCandidate::TraitMethod(candidate) => {
180 format!("Import a trait for method {}", candidate.assoc_item_name.text())
186 /// Determine how relevant a given import is in the current context. Higher scores are more
189 ctx: &AssistContext<'_>,
190 import: &LocatedImport,
191 current_module: Option<&Module>,
197 let item_module = match import.item_to_import {
198 hir::ItemInNs::Types(item) | hir::ItemInNs::Values(item) => item.module(db),
199 hir::ItemInNs::Macros(makro) => Some(makro.module(db)),
202 match item_module.zip(current_module) {
203 // get the distance between the imported path and the current module
204 // (prefer items that are more local)
205 Some((item_module, current_module)) => {
206 score -= module_distance_hueristic(db, ¤t_module, &item_module) as i32;
209 // could not find relevant modules, so just use the length of the path as an estimate
210 None => return -(2 * import.import_path.len() as i32),
216 /// A heuristic that gives a higher score to modules that are more separated.
217 fn module_distance_hueristic(db: &dyn HirDatabase, current: &Module, item: &Module) -> usize {
218 // get the path starting from the item to the respective crate roots
219 let mut current_path = current.path_to_root(db);
220 let mut item_path = item.path_to_root(db);
222 // we want paths going from the root to the item
223 current_path.reverse();
226 // length of the common prefix of the two paths
227 let prefix_length = current_path.iter().zip(&item_path).take_while(|(a, b)| a == b).count();
229 // how many modules differ between the two paths (all modules, removing any duplicates)
230 let distinct_length = current_path.len() + item_path.len() - 2 * prefix_length;
232 // cost of importing from another crate
233 let crate_boundary_cost = if current.krate() == item.krate() {
235 } else if item.krate().is_builtin(db) {
241 distinct_length + crate_boundary_cost
250 assists::AssistResolveStrategy,
251 base_db::{fixture::WithFixture, FileRange},
256 check_assist, check_assist_not_applicable, check_assist_target, TEST_CONFIG,
259 fn check_auto_import_order(before: &str, order: &[&str]) {
260 let (db, file_id, range_or_offset) = RootDatabase::with_range_or_offset(before);
261 let frange = FileRange { file_id, range: range_or_offset.into() };
263 let sema = Semantics::new(&db);
264 let config = TEST_CONFIG;
265 let ctx = AssistContext::new(sema, &config, frange);
266 let mut acc = Assists::new(&ctx, AssistResolveStrategy::All);
267 auto_import(&mut acc, &ctx);
268 let assists = acc.finish();
270 let labels = assists.iter().map(|assist| assist.label.to_string()).collect::<Vec<_>>();
272 assert_eq!(labels, order);
276 fn ignore_parameter_name() {
277 check_assist_not_applicable(
284 fn foo(bar$0: &str) {}
290 fn prefer_shorter_paths() {
292 //- /main.rs crate:main deps:foo,bar
295 //- /lib.rs crate:foo
296 pub mod collections { pub struct HashMap; }
298 //- /lib.rs crate:bar
299 pub mod collections { pub mod hash_map { pub struct HashMap; } }
302 check_auto_import_order(
304 &["Import `foo::collections::HashMap`", "Import `bar::collections::hash_map::HashMap`"],
309 fn prefer_same_crate() {
311 //- /main.rs crate:main deps:foo
320 //- /lib.rs crate:foo
324 check_auto_import_order(
326 &["Import `collections::hash_map::HashMap`", "Import `foo::HashMap`"],
331 fn not_applicable_if_scope_inside_macro() {
332 check_assist_not_applicable(
353 fn applicable_in_attributes() {
357 //- proc_macros: identity
358 #[proc_macros::identity]
369 #[proc_macros::identity]
385 fn applicable_when_found_an_import_partial() {
391 pub struct Formatter;
402 pub struct Formatter;
406 use std::fmt::{self, Formatter};
414 fn applicable_when_found_an_import() {
421 pub struct PubStruct;
425 use PubMod::PubStruct;
430 pub struct PubStruct;
437 fn applicable_when_found_an_import_in_macros() {
442 ($i:ident) => { fn foo(a: $i) {} }
447 pub struct PubStruct;
451 use PubMod::PubStruct;
454 ($i:ident) => { fn foo(a: $i) {} }
459 pub struct PubStruct;
466 fn applicable_when_found_multiple_imports() {
473 pub struct PubStruct;
476 pub struct PubStruct;
479 pub struct PubStruct;
483 use PubMod3::PubStruct;
488 pub struct PubStruct;
491 pub struct PubStruct;
494 pub struct PubStruct;
501 fn not_applicable_for_already_imported_types() {
502 check_assist_not_applicable(
505 use PubMod::PubStruct;
510 pub struct PubStruct;
517 fn not_applicable_for_types_with_private_paths() {
518 check_assist_not_applicable(
524 struct PrivateStruct;
531 fn not_applicable_when_no_imports_found() {
532 check_assist_not_applicable(
540 fn function_import() {
547 pub fn test_function() {};
551 use PubMod::test_function;
556 pub fn test_function() {};
567 //- /lib.rs crate:crate_with_macro
573 //- /main.rs crate:main deps:crate_with_macro
578 r"use crate_with_macro::foo;
588 fn auto_import_target() {
593 group_label: Option<$0GroupLabel>,
596 mod m { pub struct GroupLabel; }
603 fn not_applicable_when_path_start_is_imported() {
604 check_assist_not_applicable(
610 pub struct TestStruct;
617 mod2::mod3::TestStruct$0
624 fn not_applicable_for_imported_function() {
625 check_assist_not_applicable(
629 pub fn test_function() {}
632 use test_mod::test_function;
641 fn associated_struct_function() {
646 pub struct TestStruct {}
648 pub fn test_function() {}
653 TestStruct::test_function$0
657 use test_mod::TestStruct;
660 pub struct TestStruct {}
662 pub fn test_function() {}
667 TestStruct::test_function
674 fn associated_struct_const() {
679 pub struct TestStruct {}
681 const TEST_CONST: u8 = 42;
686 TestStruct::TEST_CONST$0
690 use test_mod::TestStruct;
693 pub struct TestStruct {}
695 const TEST_CONST: u8 = 42;
700 TestStruct::TEST_CONST
707 fn associated_trait_function() {
712 pub trait TestTrait {
715 pub struct TestStruct {}
716 impl TestTrait for TestStruct {
717 fn test_function() {}
722 test_mod::TestStruct::test_function$0
726 use test_mod::TestTrait;
729 pub trait TestTrait {
732 pub struct TestStruct {}
733 impl TestTrait for TestStruct {
734 fn test_function() {}
739 test_mod::TestStruct::test_function
746 fn not_applicable_for_imported_trait_for_function() {
747 check_assist_not_applicable(
751 pub trait TestTrait {
754 pub trait TestTrait2 {
761 impl TestTrait2 for TestEnum {
762 fn test_function() {}
764 impl TestTrait for TestEnum {
765 fn test_function() {}
769 use test_mod::TestTrait2;
771 test_mod::TestEnum::test_function$0;
778 fn associated_trait_const() {
783 pub trait TestTrait {
784 const TEST_CONST: u8;
786 pub struct TestStruct {}
787 impl TestTrait for TestStruct {
788 const TEST_CONST: u8 = 42;
793 test_mod::TestStruct::TEST_CONST$0
797 use test_mod::TestTrait;
800 pub trait TestTrait {
801 const TEST_CONST: u8;
803 pub struct TestStruct {}
804 impl TestTrait for TestStruct {
805 const TEST_CONST: u8 = 42;
810 test_mod::TestStruct::TEST_CONST
817 fn not_applicable_for_imported_trait_for_const() {
818 check_assist_not_applicable(
822 pub trait TestTrait {
823 const TEST_CONST: u8;
825 pub trait TestTrait2 {
826 const TEST_CONST: f64;
832 impl TestTrait2 for TestEnum {
833 const TEST_CONST: f64 = 42.0;
835 impl TestTrait for TestEnum {
836 const TEST_CONST: u8 = 42;
840 use test_mod::TestTrait2;
842 test_mod::TestEnum::TEST_CONST$0;
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_meth$0od()
869 use test_mod::TestTrait;
872 pub trait TestTrait {
873 fn test_method(&self);
875 pub struct TestStruct {}
876 impl TestTrait for TestStruct {
877 fn test_method(&self) {}
882 let test_struct = test_mod::TestStruct {};
883 test_struct.test_method()
890 fn trait_method_cross_crate() {
894 //- /main.rs crate:main deps:dep
896 let test_struct = dep::test_mod::TestStruct {};
897 test_struct.test_meth$0od()
899 //- /dep.rs crate:dep
901 pub trait TestTrait {
902 fn test_method(&self);
904 pub struct TestStruct {}
905 impl TestTrait for TestStruct {
906 fn test_method(&self) {}
911 use dep::test_mod::TestTrait;
914 let test_struct = dep::test_mod::TestStruct {};
915 test_struct.test_method()
922 fn assoc_fn_cross_crate() {
926 //- /main.rs crate:main deps:dep
928 dep::test_mod::TestStruct::test_func$0tion
930 //- /dep.rs crate:dep
932 pub trait TestTrait {
935 pub struct TestStruct {}
936 impl TestTrait for TestStruct {
937 fn test_function() {}
942 use dep::test_mod::TestTrait;
945 dep::test_mod::TestStruct::test_function
952 fn assoc_const_cross_crate() {
956 //- /main.rs crate:main deps:dep
958 dep::test_mod::TestStruct::CONST$0
960 //- /dep.rs crate:dep
962 pub trait TestTrait {
965 pub struct TestStruct {}
966 impl TestTrait for TestStruct {
967 const CONST: bool = true;
972 use dep::test_mod::TestTrait;
975 dep::test_mod::TestStruct::CONST
982 fn assoc_fn_as_method_cross_crate() {
983 check_assist_not_applicable(
986 //- /main.rs crate:main deps:dep
988 let test_struct = dep::test_mod::TestStruct {};
989 test_struct.test_func$0tion()
991 //- /dep.rs crate:dep
993 pub trait TestTrait {
996 pub struct TestStruct {}
997 impl TestTrait for TestStruct {
998 fn test_function() {}
1006 fn private_trait_cross_crate() {
1007 check_assist_not_applicable(
1010 //- /main.rs crate:main deps:dep
1012 let test_struct = dep::test_mod::TestStruct {};
1013 test_struct.test_meth$0od()
1015 //- /dep.rs crate:dep
1018 fn test_method(&self);
1020 pub struct TestStruct {}
1021 impl TestTrait for TestStruct {
1022 fn test_method(&self) {}
1030 fn not_applicable_for_imported_trait_for_method() {
1031 check_assist_not_applicable(
1035 pub trait TestTrait {
1036 fn test_method(&self);
1038 pub trait TestTrait2 {
1039 fn test_method(&self);
1045 impl TestTrait2 for TestEnum {
1046 fn test_method(&self) {}
1048 impl TestTrait for TestEnum {
1049 fn test_method(&self) {}
1053 use test_mod::TestTrait2;
1055 let one = test_mod::TestEnum::One;
1056 one.test$0_method();
1067 //- /lib.rs crate:dep
1070 //- /main.rs crate:main deps:dep
1085 fn whole_segment() {
1086 // Tests that only imports whose last segment matches the identifier get suggested.
1090 //- /lib.rs crate:dep
1092 pub trait Display {}
1095 pub fn panic_fmt() {}
1097 //- /main.rs crate:main deps:dep
1100 impl f$0mt::Display for S {}
1106 impl fmt::Display for S {}
1112 fn macro_generated() {
1113 // Tests that macro-generated items are suggested from external crates.
1117 //- /lib.rs crate:dep
1126 //- /main.rs crate:main deps:dep
1142 // Tests that differently cased names don't interfere and we only suggest the matching one.
1146 //- /lib.rs crate:dep
1150 //- /main.rs crate:main deps:dep
1186 use crate::baz::Foo;
1198 fn uses_abs_path_with_extern_crate_clash() {
1199 cov_mark::check!(ambiguous_crate_start);
1203 //- /main.rs crate:main deps:foo
1209 //- /foo.rs crate:foo
1225 fn works_on_ident_patterns() {
1250 fn works_in_derives() {
1256 #[rustc_builtin_macro]
1266 #[rustc_builtin_macro]
1276 fn works_in_use_start() {
1300 fn not_applicable_in_non_start_use() {
1301 check_assist_not_applicable(