2 import_assets::{ImportAssets, ImportCandidate},
3 insert_use::{insert_use, ImportScope},
6 use syntax::{ast, AstNode, NodeOrToken, SyntaxElement};
8 use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel};
10 // Feature: Auto Import
12 // Using the `auto-import` assist it is possible to insert missing imports for unresolved items.
13 // When inserting an import it will do so in a structured manner by keeping imports grouped,
14 // separated by a newline in the following order:
18 // - Current Crate, paths prefixed by `crate`
19 // - Current Module, paths prefixed by `self`
20 // - Super Module, paths prefixed by `super`
26 // use itertools::Itertools;
29 // use crate::utils::insert_use;
31 // use self::auto_import;
33 // use super::AssistContext;
36 // .Import Granularity
38 // It is possible to configure how use-trees are merged with the `importGranularity` setting.
39 // It has the following configurations:
41 // - `crate`: Merge imports from the same crate into a single use statement. This kind of
42 // nesting is only supported in Rust versions later than 1.24.
43 // - `module`: Merge imports from the same module into a single use statement.
44 // - `item`: Don't merge imports at all, creating one import per item.
45 // - `preserve`: Do not change the granularity of any imports. For auto-import this has the same
48 // In `VS Code` the configuration for this is `rust-analyzer.assist.importGranularity`.
52 // The style of imports in the same crate is configurable through the `importPrefix` setting.
53 // It has the following configurations:
55 // - `by_crate`: This setting will force paths to be always absolute, starting with the `crate`
56 // prefix, unless the item is defined outside of the current crate.
57 // - `by_self`: This setting will force paths that are relative to the current module to always
58 // start with `self`. This will result in paths that always start with either `crate`, `self`,
59 // `super` or an extern crate identifier.
60 // - `plain`: This setting does not impose any restrictions in imports.
62 // In `VS Code` the configuration for this is `rust-analyzer.assist.importPrefix`.
64 // image::https://user-images.githubusercontent.com/48062697/113020673-b85be580-917a-11eb-9022-59585f35d4f8.gif[]
66 // Assist: auto_import
68 // If the name is unresolved, provides all possible imports for it.
72 // let map = HashMap$0::new();
74 // # pub mod std { pub mod collections { pub struct HashMap { } } }
78 // use std::collections::HashMap;
81 // let map = HashMap::new();
83 // # pub mod std { pub mod collections { pub struct HashMap { } } }
85 pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
86 let (import_assets, syntax_under_caret) = find_importable_node(ctx)?;
87 let mut proposed_imports =
88 import_assets.search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind);
89 if proposed_imports.is_empty() {
93 let range = match &syntax_under_caret {
94 NodeOrToken::Node(node) => ctx.sema.original_range(node).range,
95 NodeOrToken::Token(token) => token.text_range(),
97 let group_label = group_label(import_assets.import_candidate());
98 let scope = ImportScope::find_insert_use_container(
99 &match syntax_under_caret {
100 NodeOrToken::Node(it) => it,
101 NodeOrToken::Token(it) => it.parent()?,
106 // we aren't interested in different namespaces
107 proposed_imports.dedup_by(|a, b| a.import_path == b.import_path);
108 for import in proposed_imports {
111 AssistId("auto_import", AssistKind::QuickFix),
112 format!("Import `{}`", import.import_path),
115 let scope = match scope.clone() {
116 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
117 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
118 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
120 insert_use(&scope, mod_path_to_ast(&import.import_path), &ctx.config.insert_use);
127 pub(super) fn find_importable_node(ctx: &AssistContext) -> Option<(ImportAssets, SyntaxElement)> {
128 if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() {
129 ImportAssets::for_exact_path(&path_under_caret, &ctx.sema)
130 .zip(Some(path_under_caret.syntax().clone().into()))
131 } else if let Some(method_under_caret) =
132 ctx.find_node_at_offset_with_descend::<ast::MethodCallExpr>()
134 ImportAssets::for_method_call(&method_under_caret, &ctx.sema)
135 .zip(Some(method_under_caret.syntax().clone().into()))
136 } else if let Some(pat) = ctx
137 .find_node_at_offset_with_descend::<ast::IdentPat>()
138 .filter(ast::IdentPat::is_simple_ident)
140 ImportAssets::for_ident_pat(&ctx.sema, &pat).zip(Some(pat.syntax().clone().into()))
146 fn group_label(import_candidate: &ImportCandidate) -> GroupLabel {
147 let name = match import_candidate {
148 ImportCandidate::Path(candidate) => format!("Import {}", candidate.name.text()),
149 ImportCandidate::TraitAssocItem(candidate) => {
150 format!("Import a trait for item {}", candidate.assoc_item_name.text())
152 ImportCandidate::TraitMethod(candidate) => {
153 format!("Import a trait for method {}", candidate.assoc_item_name.text())
163 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
166 fn not_applicable_if_scope_inside_macro() {
167 check_assist_not_applicable(
188 fn applicable_in_attributes() {
192 //- proc_macros: identity
193 #[proc_macros::identity]
204 #[proc_macros::identity]
220 fn applicable_when_found_an_import_partial() {
226 pub struct Formatter;
237 pub struct Formatter;
241 use std::fmt::{self, Formatter};
249 fn applicable_when_found_an_import() {
256 pub struct PubStruct;
260 use PubMod::PubStruct;
265 pub struct PubStruct;
272 fn applicable_when_found_an_import_in_macros() {
277 ($i:ident) => { fn foo(a: $i) {} }
282 pub struct PubStruct;
286 use PubMod::PubStruct;
289 ($i:ident) => { fn foo(a: $i) {} }
294 pub struct PubStruct;
301 fn applicable_when_found_multiple_imports() {
308 pub struct PubStruct;
311 pub struct PubStruct;
314 pub struct PubStruct;
318 use PubMod3::PubStruct;
323 pub struct PubStruct;
326 pub struct PubStruct;
329 pub struct PubStruct;
336 fn not_applicable_for_already_imported_types() {
337 check_assist_not_applicable(
340 use PubMod::PubStruct;
345 pub struct PubStruct;
352 fn not_applicable_for_types_with_private_paths() {
353 check_assist_not_applicable(
359 struct PrivateStruct;
366 fn not_applicable_when_no_imports_found() {
367 check_assist_not_applicable(
375 fn not_applicable_in_import_statements() {
376 check_assist_not_applicable(
382 pub struct PubStruct;
388 fn function_import() {
395 pub fn test_function() {};
399 use PubMod::test_function;
404 pub fn test_function() {};
415 //- /lib.rs crate:crate_with_macro
421 //- /main.rs crate:main deps:crate_with_macro
426 r"use crate_with_macro::foo;
436 fn auto_import_target() {
441 group_label: Option<$0GroupLabel>,
444 mod m { pub struct GroupLabel; }
451 fn not_applicable_when_path_start_is_imported() {
452 check_assist_not_applicable(
458 pub struct TestStruct;
465 mod2::mod3::TestStruct$0
472 fn not_applicable_for_imported_function() {
473 check_assist_not_applicable(
477 pub fn test_function() {}
480 use test_mod::test_function;
489 fn associated_struct_function() {
494 pub struct TestStruct {}
496 pub fn test_function() {}
501 TestStruct::test_function$0
505 use test_mod::TestStruct;
508 pub struct TestStruct {}
510 pub fn test_function() {}
515 TestStruct::test_function
522 fn associated_struct_const() {
527 pub struct TestStruct {}
529 const TEST_CONST: u8 = 42;
534 TestStruct::TEST_CONST$0
538 use test_mod::TestStruct;
541 pub struct TestStruct {}
543 const TEST_CONST: u8 = 42;
548 TestStruct::TEST_CONST
555 fn associated_trait_function() {
560 pub trait TestTrait {
563 pub struct TestStruct {}
564 impl TestTrait for TestStruct {
565 fn test_function() {}
570 test_mod::TestStruct::test_function$0
574 use test_mod::TestTrait;
577 pub trait TestTrait {
580 pub struct TestStruct {}
581 impl TestTrait for TestStruct {
582 fn test_function() {}
587 test_mod::TestStruct::test_function
594 fn not_applicable_for_imported_trait_for_function() {
595 check_assist_not_applicable(
599 pub trait TestTrait {
602 pub trait TestTrait2 {
609 impl TestTrait2 for TestEnum {
610 fn test_function() {}
612 impl TestTrait for TestEnum {
613 fn test_function() {}
617 use test_mod::TestTrait2;
619 test_mod::TestEnum::test_function$0;
626 fn associated_trait_const() {
631 pub trait TestTrait {
632 const TEST_CONST: u8;
634 pub struct TestStruct {}
635 impl TestTrait for TestStruct {
636 const TEST_CONST: u8 = 42;
641 test_mod::TestStruct::TEST_CONST$0
645 use test_mod::TestTrait;
648 pub trait TestTrait {
649 const TEST_CONST: u8;
651 pub struct TestStruct {}
652 impl TestTrait for TestStruct {
653 const TEST_CONST: u8 = 42;
658 test_mod::TestStruct::TEST_CONST
665 fn not_applicable_for_imported_trait_for_const() {
666 check_assist_not_applicable(
670 pub trait TestTrait {
671 const TEST_CONST: u8;
673 pub trait TestTrait2 {
674 const TEST_CONST: f64;
680 impl TestTrait2 for TestEnum {
681 const TEST_CONST: f64 = 42.0;
683 impl TestTrait for TestEnum {
684 const TEST_CONST: u8 = 42;
688 use test_mod::TestTrait2;
690 test_mod::TestEnum::TEST_CONST$0;
702 pub trait TestTrait {
703 fn test_method(&self);
705 pub struct TestStruct {}
706 impl TestTrait for TestStruct {
707 fn test_method(&self) {}
712 let test_struct = test_mod::TestStruct {};
713 test_struct.test_meth$0od()
717 use test_mod::TestTrait;
720 pub trait TestTrait {
721 fn test_method(&self);
723 pub struct TestStruct {}
724 impl TestTrait for TestStruct {
725 fn test_method(&self) {}
730 let test_struct = test_mod::TestStruct {};
731 test_struct.test_method()
738 fn trait_method_cross_crate() {
742 //- /main.rs crate:main deps:dep
744 let test_struct = dep::test_mod::TestStruct {};
745 test_struct.test_meth$0od()
747 //- /dep.rs crate:dep
749 pub trait TestTrait {
750 fn test_method(&self);
752 pub struct TestStruct {}
753 impl TestTrait for TestStruct {
754 fn test_method(&self) {}
759 use dep::test_mod::TestTrait;
762 let test_struct = dep::test_mod::TestStruct {};
763 test_struct.test_method()
770 fn assoc_fn_cross_crate() {
774 //- /main.rs crate:main deps:dep
776 dep::test_mod::TestStruct::test_func$0tion
778 //- /dep.rs crate:dep
780 pub trait TestTrait {
783 pub struct TestStruct {}
784 impl TestTrait for TestStruct {
785 fn test_function() {}
790 use dep::test_mod::TestTrait;
793 dep::test_mod::TestStruct::test_function
800 fn assoc_const_cross_crate() {
804 //- /main.rs crate:main deps:dep
806 dep::test_mod::TestStruct::CONST$0
808 //- /dep.rs crate:dep
810 pub trait TestTrait {
813 pub struct TestStruct {}
814 impl TestTrait for TestStruct {
815 const CONST: bool = true;
820 use dep::test_mod::TestTrait;
823 dep::test_mod::TestStruct::CONST
830 fn assoc_fn_as_method_cross_crate() {
831 check_assist_not_applicable(
834 //- /main.rs crate:main deps:dep
836 let test_struct = dep::test_mod::TestStruct {};
837 test_struct.test_func$0tion()
839 //- /dep.rs crate:dep
841 pub trait TestTrait {
844 pub struct TestStruct {}
845 impl TestTrait for TestStruct {
846 fn test_function() {}
854 fn private_trait_cross_crate() {
855 check_assist_not_applicable(
858 //- /main.rs crate:main deps:dep
860 let test_struct = dep::test_mod::TestStruct {};
861 test_struct.test_meth$0od()
863 //- /dep.rs crate:dep
866 fn test_method(&self);
868 pub struct TestStruct {}
869 impl TestTrait for TestStruct {
870 fn test_method(&self) {}
878 fn not_applicable_for_imported_trait_for_method() {
879 check_assist_not_applicable(
883 pub trait TestTrait {
884 fn test_method(&self);
886 pub trait TestTrait2 {
887 fn test_method(&self);
893 impl TestTrait2 for TestEnum {
894 fn test_method(&self) {}
896 impl TestTrait for TestEnum {
897 fn test_method(&self) {}
901 use test_mod::TestTrait2;
903 let one = test_mod::TestEnum::One;
915 //- /lib.rs crate:dep
918 //- /main.rs crate:main deps:dep
934 // Tests that only imports whose last segment matches the identifier get suggested.
938 //- /lib.rs crate:dep
943 pub fn panic_fmt() {}
945 //- /main.rs crate:main deps:dep
948 impl f$0mt::Display for S {}
954 impl fmt::Display for S {}
960 fn macro_generated() {
961 // Tests that macro-generated items are suggested from external crates.
965 //- /lib.rs crate:dep
974 //- /main.rs crate:main deps:dep
990 // Tests that differently cased names don't interfere and we only suggest the matching one.
994 //- /lib.rs crate:dep
998 //- /main.rs crate:main deps:dep
1034 use crate::baz::Foo;
1046 fn uses_abs_path_with_extern_crate_clash() {
1047 cov_mark::check!(ambiguous_crate_start);
1051 //- /main.rs crate:main deps:foo
1057 //- /foo.rs crate:foo
1073 fn works_on_ident_patterns() {
1098 fn works_in_derives() {
1104 #[rustc_builtin_macro]
1114 #[rustc_builtin_macro]