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())
148 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
151 fn applicable_when_found_an_import_partial() {
157 pub struct Formatter;
168 pub struct Formatter;
172 use std::fmt::{self, Formatter};
180 fn applicable_when_found_an_import() {
187 pub struct PubStruct;
191 use PubMod::PubStruct;
196 pub struct PubStruct;
203 fn applicable_when_found_an_import_in_macros() {
208 ($i:ident) => { fn foo(a: $i) {} }
213 pub struct PubStruct;
217 use PubMod::PubStruct;
220 ($i:ident) => { fn foo(a: $i) {} }
225 pub struct PubStruct;
232 fn applicable_when_found_multiple_imports() {
239 pub struct PubStruct;
242 pub struct PubStruct;
245 pub struct PubStruct;
249 use PubMod3::PubStruct;
254 pub struct PubStruct;
257 pub struct PubStruct;
260 pub struct PubStruct;
267 fn not_applicable_for_already_imported_types() {
268 check_assist_not_applicable(
271 use PubMod::PubStruct;
276 pub struct PubStruct;
283 fn not_applicable_for_types_with_private_paths() {
284 check_assist_not_applicable(
290 struct PrivateStruct;
297 fn not_applicable_when_no_imports_found() {
298 check_assist_not_applicable(
306 fn not_applicable_in_import_statements() {
307 check_assist_not_applicable(
313 pub struct PubStruct;
319 fn function_import() {
326 pub fn test_function() {};
330 use PubMod::test_function;
335 pub fn test_function() {};
346 //- /lib.rs crate:crate_with_macro
352 //- /main.rs crate:main deps:crate_with_macro
357 r"use crate_with_macro::foo;
367 fn auto_import_target() {
372 group_label: Option<$0GroupLabel>,
375 mod m { pub struct GroupLabel; }
382 fn not_applicable_when_path_start_is_imported() {
383 check_assist_not_applicable(
389 pub struct TestStruct;
396 mod2::mod3::TestStruct$0
403 fn not_applicable_for_imported_function() {
404 check_assist_not_applicable(
408 pub fn test_function() {}
411 use test_mod::test_function;
420 fn associated_struct_function() {
425 pub struct TestStruct {}
427 pub fn test_function() {}
432 TestStruct::test_function$0
436 use test_mod::TestStruct;
439 pub struct TestStruct {}
441 pub fn test_function() {}
446 TestStruct::test_function
453 fn associated_struct_const() {
458 pub struct TestStruct {}
460 const TEST_CONST: u8 = 42;
465 TestStruct::TEST_CONST$0
469 use test_mod::TestStruct;
472 pub struct TestStruct {}
474 const TEST_CONST: u8 = 42;
479 TestStruct::TEST_CONST
486 fn associated_trait_function() {
491 pub trait TestTrait {
494 pub struct TestStruct {}
495 impl TestTrait for TestStruct {
496 fn test_function() {}
501 test_mod::TestStruct::test_function$0
505 use test_mod::TestTrait;
508 pub trait TestTrait {
511 pub struct TestStruct {}
512 impl TestTrait for TestStruct {
513 fn test_function() {}
518 test_mod::TestStruct::test_function
525 fn not_applicable_for_imported_trait_for_function() {
526 check_assist_not_applicable(
530 pub trait TestTrait {
533 pub trait TestTrait2 {
540 impl TestTrait2 for TestEnum {
541 fn test_function() {}
543 impl TestTrait for TestEnum {
544 fn test_function() {}
548 use test_mod::TestTrait2;
550 test_mod::TestEnum::test_function$0;
557 fn associated_trait_const() {
562 pub trait TestTrait {
563 const TEST_CONST: u8;
565 pub struct TestStruct {}
566 impl TestTrait for TestStruct {
567 const TEST_CONST: u8 = 42;
572 test_mod::TestStruct::TEST_CONST$0
576 use test_mod::TestTrait;
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
596 fn not_applicable_for_imported_trait_for_const() {
597 check_assist_not_applicable(
601 pub trait TestTrait {
602 const TEST_CONST: u8;
604 pub trait TestTrait2 {
605 const TEST_CONST: f64;
611 impl TestTrait2 for TestEnum {
612 const TEST_CONST: f64 = 42.0;
614 impl TestTrait for TestEnum {
615 const TEST_CONST: u8 = 42;
619 use test_mod::TestTrait2;
621 test_mod::TestEnum::TEST_CONST$0;
633 pub trait TestTrait {
634 fn test_method(&self);
636 pub struct TestStruct {}
637 impl TestTrait for TestStruct {
638 fn test_method(&self) {}
643 let test_struct = test_mod::TestStruct {};
644 test_struct.test_meth$0od()
648 use test_mod::TestTrait;
651 pub trait TestTrait {
652 fn test_method(&self);
654 pub struct TestStruct {}
655 impl TestTrait for TestStruct {
656 fn test_method(&self) {}
661 let test_struct = test_mod::TestStruct {};
662 test_struct.test_method()
669 fn trait_method_cross_crate() {
673 //- /main.rs crate:main deps:dep
675 let test_struct = dep::test_mod::TestStruct {};
676 test_struct.test_meth$0od()
678 //- /dep.rs crate:dep
680 pub trait TestTrait {
681 fn test_method(&self);
683 pub struct TestStruct {}
684 impl TestTrait for TestStruct {
685 fn test_method(&self) {}
690 use dep::test_mod::TestTrait;
693 let test_struct = dep::test_mod::TestStruct {};
694 test_struct.test_method()
701 fn assoc_fn_cross_crate() {
705 //- /main.rs crate:main deps:dep
707 dep::test_mod::TestStruct::test_func$0tion
709 //- /dep.rs crate:dep
711 pub trait TestTrait {
714 pub struct TestStruct {}
715 impl TestTrait for TestStruct {
716 fn test_function() {}
721 use dep::test_mod::TestTrait;
724 dep::test_mod::TestStruct::test_function
731 fn assoc_const_cross_crate() {
735 //- /main.rs crate:main deps:dep
737 dep::test_mod::TestStruct::CONST$0
739 //- /dep.rs crate:dep
741 pub trait TestTrait {
744 pub struct TestStruct {}
745 impl TestTrait for TestStruct {
746 const CONST: bool = true;
751 use dep::test_mod::TestTrait;
754 dep::test_mod::TestStruct::CONST
761 fn assoc_fn_as_method_cross_crate() {
762 check_assist_not_applicable(
765 //- /main.rs crate:main deps:dep
767 let test_struct = dep::test_mod::TestStruct {};
768 test_struct.test_func$0tion()
770 //- /dep.rs crate:dep
772 pub trait TestTrait {
775 pub struct TestStruct {}
776 impl TestTrait for TestStruct {
777 fn test_function() {}
785 fn private_trait_cross_crate() {
786 check_assist_not_applicable(
789 //- /main.rs crate:main deps:dep
791 let test_struct = dep::test_mod::TestStruct {};
792 test_struct.test_meth$0od()
794 //- /dep.rs crate:dep
797 fn test_method(&self);
799 pub struct TestStruct {}
800 impl TestTrait for TestStruct {
801 fn test_method(&self) {}
809 fn not_applicable_for_imported_trait_for_method() {
810 check_assist_not_applicable(
814 pub trait TestTrait {
815 fn test_method(&self);
817 pub trait TestTrait2 {
818 fn test_method(&self);
824 impl TestTrait2 for TestEnum {
825 fn test_method(&self) {}
827 impl TestTrait for TestEnum {
828 fn test_method(&self) {}
832 use test_mod::TestTrait2;
834 let one = test_mod::TestEnum::One;
846 //- /lib.rs crate:dep
849 //- /main.rs crate:main deps:dep
865 // Tests that only imports whose last segment matches the identifier get suggested.
869 //- /lib.rs crate:dep
874 pub fn panic_fmt() {}
876 //- /main.rs crate:main deps:dep
879 impl f$0mt::Display for S {}
885 impl fmt::Display for S {}
891 fn macro_generated() {
892 // Tests that macro-generated items are suggested from external crates.
896 //- /lib.rs crate:dep
905 //- /main.rs crate:main deps:dep
921 // Tests that differently cased names don't interfere and we only suggest the matching one.
925 //- /lib.rs crate:dep
929 //- /main.rs crate:main deps:dep
977 fn uses_abs_path_with_extern_crate_clash() {
981 //- /main.rs crate:main deps:foo
987 //- /foo.rs crate:foo