2 import_assets::{ImportAssets, ImportCandidate},
3 insert_use::{insert_use, ImportScope},
6 use syntax::{ast, AstNode, SyntaxNode};
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() {
92 // we aren't interested in different namespaces
93 proposed_imports.dedup_by(|a, b| a.import_path == b.import_path);
95 let range = ctx.sema.original_range(&syntax_under_caret).range;
96 let group_label = group_label(import_assets.import_candidate());
97 let scope = ImportScope::find_insert_use_container_with_macros(&syntax_under_caret, &ctx.sema)?;
98 for import in proposed_imports {
101 AssistId("auto_import", AssistKind::QuickFix),
102 format!("Import `{}`", import.import_path),
105 let scope = match scope.clone() {
106 ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
107 ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
108 ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
110 insert_use(&scope, mod_path_to_ast(&import.import_path), &ctx.config.insert_use);
117 pub(super) fn find_importable_node(ctx: &AssistContext) -> Option<(ImportAssets, SyntaxNode)> {
118 if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() {
119 ImportAssets::for_exact_path(&path_under_caret, &ctx.sema)
120 .zip(Some(path_under_caret.syntax().clone()))
121 } else if let Some(method_under_caret) =
122 ctx.find_node_at_offset_with_descend::<ast::MethodCallExpr>()
124 ImportAssets::for_method_call(&method_under_caret, &ctx.sema)
125 .zip(Some(method_under_caret.syntax().clone()))
131 fn group_label(import_candidate: &ImportCandidate) -> GroupLabel {
132 let name = match import_candidate {
133 ImportCandidate::Path(candidate) => format!("Import {}", candidate.name.text()),
134 ImportCandidate::TraitAssocItem(candidate) => {
135 format!("Import a trait for item {}", candidate.assoc_item_name.text())
137 ImportCandidate::TraitMethod(candidate) => {
138 format!("Import a trait for method {}", candidate.assoc_item_name.text())
147 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
150 fn applicable_when_found_an_import_partial() {
156 pub struct Formatter;
167 pub struct Formatter;
171 use std::fmt::{self, Formatter};
179 fn applicable_when_found_an_import() {
186 pub struct PubStruct;
190 use PubMod::PubStruct;
195 pub struct PubStruct;
202 fn applicable_when_found_an_import_in_macros() {
207 ($i:ident) => { fn foo(a: $i) {} }
212 pub struct PubStruct;
216 use PubMod::PubStruct;
219 ($i:ident) => { fn foo(a: $i) {} }
224 pub struct PubStruct;
231 fn applicable_when_found_multiple_imports() {
238 pub struct PubStruct;
241 pub struct PubStruct;
244 pub struct PubStruct;
248 use PubMod3::PubStruct;
253 pub struct PubStruct;
256 pub struct PubStruct;
259 pub struct PubStruct;
266 fn not_applicable_for_already_imported_types() {
267 check_assist_not_applicable(
270 use PubMod::PubStruct;
275 pub struct PubStruct;
282 fn not_applicable_for_types_with_private_paths() {
283 check_assist_not_applicable(
289 struct PrivateStruct;
296 fn not_applicable_when_no_imports_found() {
297 check_assist_not_applicable(
305 fn not_applicable_in_import_statements() {
306 check_assist_not_applicable(
312 pub struct PubStruct;
318 fn function_import() {
325 pub fn test_function() {};
329 use PubMod::test_function;
334 pub fn test_function() {};
345 //- /lib.rs crate:crate_with_macro
351 //- /main.rs crate:main deps:crate_with_macro
356 r"use crate_with_macro::foo;
366 fn auto_import_target() {
371 group_label: Option<$0GroupLabel>,
374 mod m { pub struct GroupLabel; }
381 fn not_applicable_when_path_start_is_imported() {
382 check_assist_not_applicable(
388 pub struct TestStruct;
395 mod2::mod3::TestStruct$0
402 fn not_applicable_for_imported_function() {
403 check_assist_not_applicable(
407 pub fn test_function() {}
410 use test_mod::test_function;
419 fn associated_struct_function() {
424 pub struct TestStruct {}
426 pub fn test_function() {}
431 TestStruct::test_function$0
435 use test_mod::TestStruct;
438 pub struct TestStruct {}
440 pub fn test_function() {}
445 TestStruct::test_function
452 fn associated_struct_const() {
457 pub struct TestStruct {}
459 const TEST_CONST: u8 = 42;
464 TestStruct::TEST_CONST$0
468 use test_mod::TestStruct;
471 pub struct TestStruct {}
473 const TEST_CONST: u8 = 42;
478 TestStruct::TEST_CONST
485 fn associated_trait_function() {
490 pub trait TestTrait {
493 pub struct TestStruct {}
494 impl TestTrait for TestStruct {
495 fn test_function() {}
500 test_mod::TestStruct::test_function$0
504 use test_mod::TestTrait;
507 pub trait TestTrait {
510 pub struct TestStruct {}
511 impl TestTrait for TestStruct {
512 fn test_function() {}
517 test_mod::TestStruct::test_function
524 fn not_applicable_for_imported_trait_for_function() {
525 check_assist_not_applicable(
529 pub trait TestTrait {
532 pub trait TestTrait2 {
539 impl TestTrait2 for TestEnum {
540 fn test_function() {}
542 impl TestTrait for TestEnum {
543 fn test_function() {}
547 use test_mod::TestTrait2;
549 test_mod::TestEnum::test_function$0;
556 fn associated_trait_const() {
561 pub trait TestTrait {
562 const TEST_CONST: u8;
564 pub struct TestStruct {}
565 impl TestTrait for TestStruct {
566 const TEST_CONST: u8 = 42;
571 test_mod::TestStruct::TEST_CONST$0
575 use test_mod::TestTrait;
578 pub trait TestTrait {
579 const TEST_CONST: u8;
581 pub struct TestStruct {}
582 impl TestTrait for TestStruct {
583 const TEST_CONST: u8 = 42;
588 test_mod::TestStruct::TEST_CONST
595 fn not_applicable_for_imported_trait_for_const() {
596 check_assist_not_applicable(
600 pub trait TestTrait {
601 const TEST_CONST: u8;
603 pub trait TestTrait2 {
604 const TEST_CONST: f64;
610 impl TestTrait2 for TestEnum {
611 const TEST_CONST: f64 = 42.0;
613 impl TestTrait for TestEnum {
614 const TEST_CONST: u8 = 42;
618 use test_mod::TestTrait2;
620 test_mod::TestEnum::TEST_CONST$0;
632 pub trait TestTrait {
633 fn test_method(&self);
635 pub struct TestStruct {}
636 impl TestTrait for TestStruct {
637 fn test_method(&self) {}
642 let test_struct = test_mod::TestStruct {};
643 test_struct.test_meth$0od()
647 use test_mod::TestTrait;
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_method()
668 fn trait_method_cross_crate() {
672 //- /main.rs crate:main deps:dep
674 let test_struct = dep::test_mod::TestStruct {};
675 test_struct.test_meth$0od()
677 //- /dep.rs crate:dep
679 pub trait TestTrait {
680 fn test_method(&self);
682 pub struct TestStruct {}
683 impl TestTrait for TestStruct {
684 fn test_method(&self) {}
689 use dep::test_mod::TestTrait;
692 let test_struct = dep::test_mod::TestStruct {};
693 test_struct.test_method()
700 fn assoc_fn_cross_crate() {
704 //- /main.rs crate:main deps:dep
706 dep::test_mod::TestStruct::test_func$0tion
708 //- /dep.rs crate:dep
710 pub trait TestTrait {
713 pub struct TestStruct {}
714 impl TestTrait for TestStruct {
715 fn test_function() {}
720 use dep::test_mod::TestTrait;
723 dep::test_mod::TestStruct::test_function
730 fn assoc_const_cross_crate() {
734 //- /main.rs crate:main deps:dep
736 dep::test_mod::TestStruct::CONST$0
738 //- /dep.rs crate:dep
740 pub trait TestTrait {
743 pub struct TestStruct {}
744 impl TestTrait for TestStruct {
745 const CONST: bool = true;
750 use dep::test_mod::TestTrait;
753 dep::test_mod::TestStruct::CONST
760 fn assoc_fn_as_method_cross_crate() {
761 check_assist_not_applicable(
764 //- /main.rs crate:main deps:dep
766 let test_struct = dep::test_mod::TestStruct {};
767 test_struct.test_func$0tion()
769 //- /dep.rs crate:dep
771 pub trait TestTrait {
774 pub struct TestStruct {}
775 impl TestTrait for TestStruct {
776 fn test_function() {}
784 fn private_trait_cross_crate() {
785 check_assist_not_applicable(
788 //- /main.rs crate:main deps:dep
790 let test_struct = dep::test_mod::TestStruct {};
791 test_struct.test_meth$0od()
793 //- /dep.rs crate:dep
796 fn test_method(&self);
798 pub struct TestStruct {}
799 impl TestTrait for TestStruct {
800 fn test_method(&self) {}
808 fn not_applicable_for_imported_trait_for_method() {
809 check_assist_not_applicable(
813 pub trait TestTrait {
814 fn test_method(&self);
816 pub trait TestTrait2 {
817 fn test_method(&self);
823 impl TestTrait2 for TestEnum {
824 fn test_method(&self) {}
826 impl TestTrait for TestEnum {
827 fn test_method(&self) {}
831 use test_mod::TestTrait2;
833 let one = test_mod::TestEnum::One;
845 //- /lib.rs crate:dep
848 //- /main.rs crate:main deps:dep
864 // Tests that only imports whose last segment matches the identifier get suggested.
868 //- /lib.rs crate:dep
873 pub fn panic_fmt() {}
875 //- /main.rs crate:main deps:dep
878 impl f$0mt::Display for S {}
884 impl fmt::Display for S {}
890 fn macro_generated() {
891 // Tests that macro-generated items are suggested from external crates.
895 //- /lib.rs crate:dep
904 //- /main.rs crate:main deps:dep
920 // Tests that differently cased names don't interfere and we only suggest the matching one.
924 //- /lib.rs crate:dep
928 //- /main.rs crate:main deps:dep
976 fn uses_abs_path_with_extern_crate_clash() {
980 //- /main.rs crate:main deps:foo
986 //- /foo.rs crate:foo