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 =
93 import_assets.search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind);
94 if proposed_imports.is_empty() {
98 let range = match &syntax_under_caret {
99 NodeOrToken::Node(node) => ctx.sema.original_range(node).range,
100 NodeOrToken::Token(token) => token.text_range(),
102 let group_label = group_label(import_assets.import_candidate());
103 let scope = ImportScope::find_insert_use_container(
104 &match syntax_under_caret {
105 NodeOrToken::Node(it) => it,
106 NodeOrToken::Token(it) => it.parent()?,
111 // we aren't interested in different namespaces
112 proposed_imports.dedup_by(|a, b| a.import_path == b.import_path);
114 let current_node = match ctx.covering_element() {
115 NodeOrToken::Node(node) => Some(node),
116 NodeOrToken::Token(token) => token.parent(),
120 current_node.as_ref().and_then(|node| ctx.sema.scope(node)).map(|scope| scope.module());
122 // prioritize more relevant imports
124 .sort_by_key(|import| Reverse(relevance_score(ctx, import, current_module.as_ref())));
126 for import in proposed_imports {
129 AssistId("auto_import", AssistKind::QuickFix),
130 format!("Import `{}`", import.import_path),
133 let scope = match scope.clone() {
134 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
135 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
136 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
138 insert_use(&scope, mod_path_to_ast(&import.import_path), &ctx.config.insert_use);
145 pub(super) fn find_importable_node(
146 ctx: &AssistContext<'_>,
147 ) -> Option<(ImportAssets, SyntaxElement)> {
148 if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() {
149 ImportAssets::for_exact_path(&path_under_caret, &ctx.sema)
150 .zip(Some(path_under_caret.syntax().clone().into()))
151 } else if let Some(method_under_caret) =
152 ctx.find_node_at_offset_with_descend::<ast::MethodCallExpr>()
154 ImportAssets::for_method_call(&method_under_caret, &ctx.sema)
155 .zip(Some(method_under_caret.syntax().clone().into()))
156 } else if let Some(pat) = ctx
157 .find_node_at_offset_with_descend::<ast::IdentPat>()
158 .filter(ast::IdentPat::is_simple_ident)
160 ImportAssets::for_ident_pat(&ctx.sema, &pat).zip(Some(pat.syntax().clone().into()))
166 fn group_label(import_candidate: &ImportCandidate) -> GroupLabel {
167 let name = match import_candidate {
168 ImportCandidate::Path(candidate) => format!("Import {}", candidate.name.text()),
169 ImportCandidate::TraitAssocItem(candidate) => {
170 format!("Import a trait for item {}", candidate.assoc_item_name.text())
172 ImportCandidate::TraitMethod(candidate) => {
173 format!("Import a trait for method {}", candidate.assoc_item_name.text())
179 /// Determine how relevant a given import is in the current context. Higher scores are more
182 ctx: &AssistContext<'_>,
183 import: &LocatedImport,
184 current_module: Option<&Module>,
190 let item_module = match import.item_to_import {
191 hir::ItemInNs::Types(item) | hir::ItemInNs::Values(item) => item.module(db),
192 hir::ItemInNs::Macros(makro) => Some(makro.module(db)),
195 match item_module.zip(current_module) {
196 // get the distance between the imported path and the current module
197 // (prefer items that are more local)
198 Some((item_module, current_module)) => {
199 score -= module_distance_hueristic(db, ¤t_module, &item_module) as i32;
202 // could not find relevant modules, so just use the length of the path as an estimate
203 None => return -(2 * import.import_path.len() as i32),
209 /// A heuristic that gives a higher score to modules that are more separated.
210 fn module_distance_hueristic(db: &dyn HirDatabase, current: &Module, item: &Module) -> usize {
211 // get the path starting from the item to the respective crate roots
212 let mut current_path = current.path_to_root(db);
213 let mut item_path = item.path_to_root(db);
215 // we want paths going from the root to the item
216 current_path.reverse();
219 // length of the common prefix of the two paths
220 let prefix_length = current_path.iter().zip(&item_path).take_while(|(a, b)| a == b).count();
222 // how many modules differ between the two paths (all modules, removing any duplicates)
223 let distinct_length = current_path.len() + item_path.len() - 2 * prefix_length;
225 // cost of importing from another crate
226 let crate_boundary_cost = if current.krate() == item.krate() {
228 } else if item.krate().is_builtin(db) {
234 distinct_length + crate_boundary_cost
243 assists::AssistResolveStrategy,
244 base_db::{fixture::WithFixture, FileRange},
249 check_assist, check_assist_not_applicable, check_assist_target, TEST_CONFIG,
252 fn check_auto_import_order(before: &str, order: &[&str]) {
253 let (db, file_id, range_or_offset) = RootDatabase::with_range_or_offset(before);
254 let frange = FileRange { file_id, range: range_or_offset.into() };
256 let sema = Semantics::new(&db);
257 let config = TEST_CONFIG;
258 let ctx = AssistContext::new(sema, &config, frange);
259 let mut acc = Assists::new(&ctx, AssistResolveStrategy::All);
260 auto_import(&mut acc, &ctx);
261 let assists = acc.finish();
263 let labels = assists.iter().map(|assist| assist.label.to_string()).collect::<Vec<_>>();
265 assert_eq!(labels, order);
269 fn prefer_shorter_paths() {
271 //- /main.rs crate:main deps:foo,bar
274 //- /lib.rs crate:foo
275 pub mod collections { pub struct HashMap; }
277 //- /lib.rs crate:bar
278 pub mod collections { pub mod hash_map { pub struct HashMap; } }
281 check_auto_import_order(
283 &["Import `foo::collections::HashMap`", "Import `bar::collections::hash_map::HashMap`"],
288 fn prefer_same_crate() {
290 //- /main.rs crate:main deps:foo
299 //- /lib.rs crate:foo
303 check_auto_import_order(
305 &["Import `collections::hash_map::HashMap`", "Import `foo::HashMap`"],
310 fn not_applicable_if_scope_inside_macro() {
311 check_assist_not_applicable(
332 fn applicable_in_attributes() {
336 //- proc_macros: identity
337 #[proc_macros::identity]
348 #[proc_macros::identity]
364 fn applicable_when_found_an_import_partial() {
370 pub struct Formatter;
381 pub struct Formatter;
385 use std::fmt::{self, Formatter};
393 fn applicable_when_found_an_import() {
400 pub struct PubStruct;
404 use PubMod::PubStruct;
409 pub struct PubStruct;
416 fn applicable_when_found_an_import_in_macros() {
421 ($i:ident) => { fn foo(a: $i) {} }
426 pub struct PubStruct;
430 use PubMod::PubStruct;
433 ($i:ident) => { fn foo(a: $i) {} }
438 pub struct PubStruct;
445 fn applicable_when_found_multiple_imports() {
452 pub struct PubStruct;
455 pub struct PubStruct;
458 pub struct PubStruct;
462 use PubMod3::PubStruct;
467 pub struct PubStruct;
470 pub struct PubStruct;
473 pub struct PubStruct;
480 fn not_applicable_for_already_imported_types() {
481 check_assist_not_applicable(
484 use PubMod::PubStruct;
489 pub struct PubStruct;
496 fn not_applicable_for_types_with_private_paths() {
497 check_assist_not_applicable(
503 struct PrivateStruct;
510 fn not_applicable_when_no_imports_found() {
511 check_assist_not_applicable(
519 fn function_import() {
526 pub fn test_function() {};
530 use PubMod::test_function;
535 pub fn test_function() {};
546 //- /lib.rs crate:crate_with_macro
552 //- /main.rs crate:main deps:crate_with_macro
557 r"use crate_with_macro::foo;
567 fn auto_import_target() {
572 group_label: Option<$0GroupLabel>,
575 mod m { pub struct GroupLabel; }
582 fn not_applicable_when_path_start_is_imported() {
583 check_assist_not_applicable(
589 pub struct TestStruct;
596 mod2::mod3::TestStruct$0
603 fn not_applicable_for_imported_function() {
604 check_assist_not_applicable(
608 pub fn test_function() {}
611 use test_mod::test_function;
620 fn associated_struct_function() {
625 pub struct TestStruct {}
627 pub fn test_function() {}
632 TestStruct::test_function$0
636 use test_mod::TestStruct;
639 pub struct TestStruct {}
641 pub fn test_function() {}
646 TestStruct::test_function
653 fn associated_struct_const() {
658 pub struct TestStruct {}
660 const TEST_CONST: u8 = 42;
665 TestStruct::TEST_CONST$0
669 use test_mod::TestStruct;
672 pub struct TestStruct {}
674 const TEST_CONST: u8 = 42;
679 TestStruct::TEST_CONST
686 fn associated_trait_function() {
691 pub trait TestTrait {
694 pub struct TestStruct {}
695 impl TestTrait for TestStruct {
696 fn test_function() {}
701 test_mod::TestStruct::test_function$0
705 use test_mod::TestTrait;
708 pub trait TestTrait {
711 pub struct TestStruct {}
712 impl TestTrait for TestStruct {
713 fn test_function() {}
718 test_mod::TestStruct::test_function
725 fn not_applicable_for_imported_trait_for_function() {
726 check_assist_not_applicable(
730 pub trait TestTrait {
733 pub trait TestTrait2 {
740 impl TestTrait2 for TestEnum {
741 fn test_function() {}
743 impl TestTrait for TestEnum {
744 fn test_function() {}
748 use test_mod::TestTrait2;
750 test_mod::TestEnum::test_function$0;
757 fn associated_trait_const() {
762 pub trait TestTrait {
763 const TEST_CONST: u8;
765 pub struct TestStruct {}
766 impl TestTrait for TestStruct {
767 const TEST_CONST: u8 = 42;
772 test_mod::TestStruct::TEST_CONST$0
776 use test_mod::TestTrait;
779 pub trait TestTrait {
780 const TEST_CONST: u8;
782 pub struct TestStruct {}
783 impl TestTrait for TestStruct {
784 const TEST_CONST: u8 = 42;
789 test_mod::TestStruct::TEST_CONST
796 fn not_applicable_for_imported_trait_for_const() {
797 check_assist_not_applicable(
801 pub trait TestTrait {
802 const TEST_CONST: u8;
804 pub trait TestTrait2 {
805 const TEST_CONST: f64;
811 impl TestTrait2 for TestEnum {
812 const TEST_CONST: f64 = 42.0;
814 impl TestTrait for TestEnum {
815 const TEST_CONST: u8 = 42;
819 use test_mod::TestTrait2;
821 test_mod::TestEnum::TEST_CONST$0;
833 pub trait TestTrait {
834 fn test_method(&self);
836 pub struct TestStruct {}
837 impl TestTrait for TestStruct {
838 fn test_method(&self) {}
843 let test_struct = test_mod::TestStruct {};
844 test_struct.test_meth$0od()
848 use test_mod::TestTrait;
851 pub trait TestTrait {
852 fn test_method(&self);
854 pub struct TestStruct {}
855 impl TestTrait for TestStruct {
856 fn test_method(&self) {}
861 let test_struct = test_mod::TestStruct {};
862 test_struct.test_method()
869 fn trait_method_cross_crate() {
873 //- /main.rs crate:main deps:dep
875 let test_struct = dep::test_mod::TestStruct {};
876 test_struct.test_meth$0od()
878 //- /dep.rs crate:dep
880 pub trait TestTrait {
881 fn test_method(&self);
883 pub struct TestStruct {}
884 impl TestTrait for TestStruct {
885 fn test_method(&self) {}
890 use dep::test_mod::TestTrait;
893 let test_struct = dep::test_mod::TestStruct {};
894 test_struct.test_method()
901 fn assoc_fn_cross_crate() {
905 //- /main.rs crate:main deps:dep
907 dep::test_mod::TestStruct::test_func$0tion
909 //- /dep.rs crate:dep
911 pub trait TestTrait {
914 pub struct TestStruct {}
915 impl TestTrait for TestStruct {
916 fn test_function() {}
921 use dep::test_mod::TestTrait;
924 dep::test_mod::TestStruct::test_function
931 fn assoc_const_cross_crate() {
935 //- /main.rs crate:main deps:dep
937 dep::test_mod::TestStruct::CONST$0
939 //- /dep.rs crate:dep
941 pub trait TestTrait {
944 pub struct TestStruct {}
945 impl TestTrait for TestStruct {
946 const CONST: bool = true;
951 use dep::test_mod::TestTrait;
954 dep::test_mod::TestStruct::CONST
961 fn assoc_fn_as_method_cross_crate() {
962 check_assist_not_applicable(
965 //- /main.rs crate:main deps:dep
967 let test_struct = dep::test_mod::TestStruct {};
968 test_struct.test_func$0tion()
970 //- /dep.rs crate:dep
972 pub trait TestTrait {
975 pub struct TestStruct {}
976 impl TestTrait for TestStruct {
977 fn test_function() {}
985 fn private_trait_cross_crate() {
986 check_assist_not_applicable(
989 //- /main.rs crate:main deps:dep
991 let test_struct = dep::test_mod::TestStruct {};
992 test_struct.test_meth$0od()
994 //- /dep.rs crate:dep
997 fn test_method(&self);
999 pub struct TestStruct {}
1000 impl TestTrait for TestStruct {
1001 fn test_method(&self) {}
1009 fn not_applicable_for_imported_trait_for_method() {
1010 check_assist_not_applicable(
1014 pub trait TestTrait {
1015 fn test_method(&self);
1017 pub trait TestTrait2 {
1018 fn test_method(&self);
1024 impl TestTrait2 for TestEnum {
1025 fn test_method(&self) {}
1027 impl TestTrait for TestEnum {
1028 fn test_method(&self) {}
1032 use test_mod::TestTrait2;
1034 let one = test_mod::TestEnum::One;
1035 one.test$0_method();
1046 //- /lib.rs crate:dep
1049 //- /main.rs crate:main deps:dep
1064 fn whole_segment() {
1065 // Tests that only imports whose last segment matches the identifier get suggested.
1069 //- /lib.rs crate:dep
1071 pub trait Display {}
1074 pub fn panic_fmt() {}
1076 //- /main.rs crate:main deps:dep
1079 impl f$0mt::Display for S {}
1085 impl fmt::Display for S {}
1091 fn macro_generated() {
1092 // Tests that macro-generated items are suggested from external crates.
1096 //- /lib.rs crate:dep
1105 //- /main.rs crate:main deps:dep
1121 // Tests that differently cased names don't interfere and we only suggest the matching one.
1125 //- /lib.rs crate:dep
1129 //- /main.rs crate:main deps:dep
1165 use crate::baz::Foo;
1177 fn uses_abs_path_with_extern_crate_clash() {
1178 cov_mark::check!(ambiguous_crate_start);
1182 //- /main.rs crate:main deps:foo
1188 //- /foo.rs crate:foo
1204 fn works_on_ident_patterns() {
1229 fn works_in_derives() {
1235 #[rustc_builtin_macro]
1245 #[rustc_builtin_macro]
1255 fn works_in_use_start() {
1279 fn not_applicable_in_non_start_use() {
1280 check_assist_not_applicable(