2 import_assets::{ImportAssets, ImportCandidate},
3 insert_use::{insert_use, ImportScope},
6 use syntax::{ast, AstNode, AstToken, 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_with_macros(
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()))
143 let ident = ctx.find_token_at_offset()?;
144 ImportAssets::for_derive_ident(&ctx.sema, &ident).zip(Some(ident.syntax().clone().into()))
148 fn group_label(import_candidate: &ImportCandidate) -> GroupLabel {
149 let name = match import_candidate {
150 ImportCandidate::Path(candidate) => format!("Import {}", candidate.name.text()),
151 ImportCandidate::TraitAssocItem(candidate) => {
152 format!("Import a trait for item {}", candidate.assoc_item_name.text())
154 ImportCandidate::TraitMethod(candidate) => {
155 format!("Import a trait for method {}", candidate.assoc_item_name.text())
165 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
168 fn applicable_when_found_an_import_partial() {
174 pub struct Formatter;
185 pub struct Formatter;
189 use std::fmt::{self, Formatter};
197 fn applicable_when_found_an_import() {
204 pub struct PubStruct;
208 use PubMod::PubStruct;
213 pub struct PubStruct;
220 fn applicable_when_found_an_import_in_macros() {
225 ($i:ident) => { fn foo(a: $i) {} }
230 pub struct PubStruct;
234 use PubMod::PubStruct;
237 ($i:ident) => { fn foo(a: $i) {} }
242 pub struct PubStruct;
249 fn applicable_when_found_multiple_imports() {
256 pub struct PubStruct;
259 pub struct PubStruct;
262 pub struct PubStruct;
266 use PubMod3::PubStruct;
271 pub struct PubStruct;
274 pub struct PubStruct;
277 pub struct PubStruct;
284 fn not_applicable_for_already_imported_types() {
285 check_assist_not_applicable(
288 use PubMod::PubStruct;
293 pub struct PubStruct;
300 fn not_applicable_for_types_with_private_paths() {
301 check_assist_not_applicable(
307 struct PrivateStruct;
314 fn not_applicable_when_no_imports_found() {
315 check_assist_not_applicable(
323 fn not_applicable_in_import_statements() {
324 check_assist_not_applicable(
330 pub struct PubStruct;
336 fn function_import() {
343 pub fn test_function() {};
347 use PubMod::test_function;
352 pub fn test_function() {};
363 //- /lib.rs crate:crate_with_macro
369 //- /main.rs crate:main deps:crate_with_macro
374 r"use crate_with_macro::foo;
384 fn auto_import_target() {
389 group_label: Option<$0GroupLabel>,
392 mod m { pub struct GroupLabel; }
399 fn not_applicable_when_path_start_is_imported() {
400 check_assist_not_applicable(
406 pub struct TestStruct;
413 mod2::mod3::TestStruct$0
420 fn not_applicable_for_imported_function() {
421 check_assist_not_applicable(
425 pub fn test_function() {}
428 use test_mod::test_function;
437 fn associated_struct_function() {
442 pub struct TestStruct {}
444 pub fn test_function() {}
449 TestStruct::test_function$0
453 use test_mod::TestStruct;
456 pub struct TestStruct {}
458 pub fn test_function() {}
463 TestStruct::test_function
470 fn associated_struct_const() {
475 pub struct TestStruct {}
477 const TEST_CONST: u8 = 42;
482 TestStruct::TEST_CONST$0
486 use test_mod::TestStruct;
489 pub struct TestStruct {}
491 const TEST_CONST: u8 = 42;
496 TestStruct::TEST_CONST
503 fn associated_trait_function() {
508 pub trait TestTrait {
511 pub struct TestStruct {}
512 impl TestTrait for TestStruct {
513 fn test_function() {}
518 test_mod::TestStruct::test_function$0
522 use test_mod::TestTrait;
525 pub trait TestTrait {
528 pub struct TestStruct {}
529 impl TestTrait for TestStruct {
530 fn test_function() {}
535 test_mod::TestStruct::test_function
542 fn not_applicable_for_imported_trait_for_function() {
543 check_assist_not_applicable(
547 pub trait TestTrait {
550 pub trait TestTrait2 {
557 impl TestTrait2 for TestEnum {
558 fn test_function() {}
560 impl TestTrait for TestEnum {
561 fn test_function() {}
565 use test_mod::TestTrait2;
567 test_mod::TestEnum::test_function$0;
574 fn associated_trait_const() {
579 pub trait TestTrait {
580 const TEST_CONST: u8;
582 pub struct TestStruct {}
583 impl TestTrait for TestStruct {
584 const TEST_CONST: u8 = 42;
589 test_mod::TestStruct::TEST_CONST$0
593 use test_mod::TestTrait;
596 pub trait TestTrait {
597 const TEST_CONST: u8;
599 pub struct TestStruct {}
600 impl TestTrait for TestStruct {
601 const TEST_CONST: u8 = 42;
606 test_mod::TestStruct::TEST_CONST
613 fn not_applicable_for_imported_trait_for_const() {
614 check_assist_not_applicable(
618 pub trait TestTrait {
619 const TEST_CONST: u8;
621 pub trait TestTrait2 {
622 const TEST_CONST: f64;
628 impl TestTrait2 for TestEnum {
629 const TEST_CONST: f64 = 42.0;
631 impl TestTrait for TestEnum {
632 const TEST_CONST: u8 = 42;
636 use test_mod::TestTrait2;
638 test_mod::TestEnum::TEST_CONST$0;
650 pub trait TestTrait {
651 fn test_method(&self);
653 pub struct TestStruct {}
654 impl TestTrait for TestStruct {
655 fn test_method(&self) {}
660 let test_struct = test_mod::TestStruct {};
661 test_struct.test_meth$0od()
665 use test_mod::TestTrait;
668 pub trait TestTrait {
669 fn test_method(&self);
671 pub struct TestStruct {}
672 impl TestTrait for TestStruct {
673 fn test_method(&self) {}
678 let test_struct = test_mod::TestStruct {};
679 test_struct.test_method()
686 fn trait_method_cross_crate() {
690 //- /main.rs crate:main deps:dep
692 let test_struct = dep::test_mod::TestStruct {};
693 test_struct.test_meth$0od()
695 //- /dep.rs crate:dep
697 pub trait TestTrait {
698 fn test_method(&self);
700 pub struct TestStruct {}
701 impl TestTrait for TestStruct {
702 fn test_method(&self) {}
707 use dep::test_mod::TestTrait;
710 let test_struct = dep::test_mod::TestStruct {};
711 test_struct.test_method()
718 fn assoc_fn_cross_crate() {
722 //- /main.rs crate:main deps:dep
724 dep::test_mod::TestStruct::test_func$0tion
726 //- /dep.rs crate:dep
728 pub trait TestTrait {
731 pub struct TestStruct {}
732 impl TestTrait for TestStruct {
733 fn test_function() {}
738 use dep::test_mod::TestTrait;
741 dep::test_mod::TestStruct::test_function
748 fn assoc_const_cross_crate() {
752 //- /main.rs crate:main deps:dep
754 dep::test_mod::TestStruct::CONST$0
756 //- /dep.rs crate:dep
758 pub trait TestTrait {
761 pub struct TestStruct {}
762 impl TestTrait for TestStruct {
763 const CONST: bool = true;
768 use dep::test_mod::TestTrait;
771 dep::test_mod::TestStruct::CONST
778 fn assoc_fn_as_method_cross_crate() {
779 check_assist_not_applicable(
782 //- /main.rs crate:main deps:dep
784 let test_struct = dep::test_mod::TestStruct {};
785 test_struct.test_func$0tion()
787 //- /dep.rs crate:dep
789 pub trait TestTrait {
792 pub struct TestStruct {}
793 impl TestTrait for TestStruct {
794 fn test_function() {}
802 fn private_trait_cross_crate() {
803 check_assist_not_applicable(
806 //- /main.rs crate:main deps:dep
808 let test_struct = dep::test_mod::TestStruct {};
809 test_struct.test_meth$0od()
811 //- /dep.rs crate:dep
814 fn test_method(&self);
816 pub struct TestStruct {}
817 impl TestTrait for TestStruct {
818 fn test_method(&self) {}
826 fn not_applicable_for_imported_trait_for_method() {
827 check_assist_not_applicable(
831 pub trait TestTrait {
832 fn test_method(&self);
834 pub trait TestTrait2 {
835 fn test_method(&self);
841 impl TestTrait2 for TestEnum {
842 fn test_method(&self) {}
844 impl TestTrait for TestEnum {
845 fn test_method(&self) {}
849 use test_mod::TestTrait2;
851 let one = test_mod::TestEnum::One;
863 //- /lib.rs crate:dep
866 //- /main.rs crate:main deps:dep
882 // Tests that only imports whose last segment matches the identifier get suggested.
886 //- /lib.rs crate:dep
891 pub fn panic_fmt() {}
893 //- /main.rs crate:main deps:dep
896 impl f$0mt::Display for S {}
902 impl fmt::Display for S {}
908 fn macro_generated() {
909 // Tests that macro-generated items are suggested from external crates.
913 //- /lib.rs crate:dep
922 //- /main.rs crate:main deps:dep
938 // Tests that differently cased names don't interfere and we only suggest the matching one.
942 //- /lib.rs crate:dep
946 //- /main.rs crate:main deps:dep
994 fn uses_abs_path_with_extern_crate_clash() {
995 cov_mark::check!(ambiguous_crate_start);
999 //- /main.rs crate:main deps:foo
1005 //- /foo.rs crate:foo
1021 fn works_on_ident_patterns() {
1046 fn works_in_derives() {
1052 #[rustc_builtin_macro]
1062 #[rustc_builtin_macro]