1 //! Feature: completion with imports-on-the-fly
3 //! When completing names in the current scope, proposes additional imports from other modules or crates,
4 //! if they can be qualified in the scope and their name contains all symbols from the completion input
5 //! (case-insensitive, in any order or places).
11 //! # pub mod std { pub mod marker { pub struct PhantomData { } } }
15 //! use std::marker::PhantomData;
20 //! # pub mod std { pub mod marker { pub struct PhantomData { } } }
23 //! Also completes associated items, that require trait imports.
25 //! .Fuzzy search details
27 //! To avoid an excessive amount of the results returned, completion input is checked for inclusion in the names only
28 //! (i.e. in `HashMap` in the `std::collections::HashMap` path).
29 //! For the same reasons, avoids searching for any path imports for inputs with their length less that 2 symbols
30 //! (but shows all associated items for any input length).
32 //! .Import configuration
34 //! It is possible to configure how use-trees are merged with the `importMergeBehavior` setting.
35 //! Mimics the corresponding behavior of the `Auto Import` feature.
37 //! .LSP and performance implications
39 //! The feature is enabled only if the LSP client supports LSP protocol version 3.16+ and reports the `additionalTextEdits`
40 //! (case sensitive) resolve client capability in its client capabilities.
41 //! This way the server is able to defer the costly computations, doing them for a selected completion item only.
42 //! For clients with no such support, all edits have to be calculated on the completion request, including the fuzzy search completion ones,
43 //! which might be slow ergo the feature is automatically disabled.
47 //! The feature can be forcefully turned off in the settings with the `rust-analyzer.completion.enableAutoimportCompletions` flag.
48 //! Note that having this flag set to `true` does not guarantee that the feature is enabled: your client needs to have the corredponding
49 //! capability enabled.
51 use hir::{AsAssocItem, ModPath, ScopeDef};
52 use ide_db::helpers::{
53 import_assets::{ImportAssets, ImportCandidate},
54 insert_use::ImportScope,
56 use rustc_hash::FxHashSet;
57 use syntax::{AstNode, SyntaxNode, T};
60 context::CompletionContext,
61 render::{render_resolution_with_import, RenderContext},
65 use super::Completions;
67 pub(crate) fn import_on_the_fly(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
68 if !ctx.config.enable_imports_on_the_fly {
71 if ctx.use_item_syntax.is_some()
72 || ctx.attribute_under_caret.is_some()
73 || ctx.mod_declaration_under_caret.is_some()
77 let potential_import_name = {
78 let token_kind = ctx.token.kind();
79 if matches!(token_kind, T![.] | T![::]) {
86 let _p = profile::span("import_on_the_fly").detail(|| potential_import_name.to_string());
88 let user_input_lowercased = potential_import_name.to_lowercase();
89 let import_assets = import_assets(ctx, potential_import_name)?;
90 let import_scope = ImportScope::find_insert_use_container(
91 position_for_import(ctx, Some(import_assets.import_candidate()))?,
95 let scope_definitions = scope_definitions(ctx);
96 let mut all_mod_paths = import_assets
97 .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
99 .map(|(mod_path, item_in_ns)| {
100 let scope_item = match item_in_ns {
101 hir::ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()),
102 hir::ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()),
103 hir::ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()),
105 (mod_path, scope_item)
107 .filter(|(_, proposed_def)| !scope_definitions.contains(proposed_def))
108 .collect::<Vec<_>>();
109 all_mod_paths.sort_by_cached_key(|(mod_path, _)| {
110 compute_fuzzy_completion_order_key(mod_path, &user_input_lowercased)
113 acc.add_all(all_mod_paths.into_iter().filter_map(|(import_path, definition)| {
114 let import_for_trait_assoc_item = match definition {
115 ScopeDef::ModuleDef(module_def) => module_def
116 .as_assoc_item(ctx.db)
117 .and_then(|assoc| assoc.containing_trait(ctx.db))
121 let import_edit = ImportEdit {
123 import_scope: import_scope.clone(),
124 import_for_trait_assoc_item,
126 render_resolution_with_import(RenderContext::new(ctx), import_edit, &definition)
131 fn scope_definitions(ctx: &CompletionContext) -> FxHashSet<ScopeDef> {
132 let mut scope_definitions = FxHashSet::default();
133 ctx.scope.process_all_names(&mut |_, scope_def| {
134 scope_definitions.insert(scope_def);
139 pub(crate) fn position_for_import<'a>(
140 ctx: &'a CompletionContext,
141 import_candidate: Option<&ImportCandidate>,
142 ) -> Option<&'a SyntaxNode> {
143 Some(match import_candidate {
144 Some(ImportCandidate::Path(_)) => ctx.name_ref_syntax.as_ref()?.syntax(),
145 Some(ImportCandidate::TraitAssocItem(_)) => ctx.path_qual.as_ref()?.syntax(),
146 Some(ImportCandidate::TraitMethod(_)) => ctx.dot_receiver.as_ref()?.syntax(),
150 .map(|name_ref| name_ref.syntax())
151 .or_else(|| ctx.path_qual.as_ref().map(|path| path.syntax()))
152 .or_else(|| ctx.dot_receiver.as_ref().map(|expr| expr.syntax()))?,
156 fn import_assets(ctx: &CompletionContext, fuzzy_name: String) -> Option<ImportAssets> {
157 let current_module = ctx.scope.module()?;
158 if let Some(dot_receiver) = &ctx.dot_receiver {
159 ImportAssets::for_fuzzy_method_call(
161 ctx.sema.type_of_expr(dot_receiver)?,
165 let fuzzy_name_length = fuzzy_name.len();
166 let assets_for_path = ImportAssets::for_fuzzy_path(
168 ctx.path_qual.clone(),
173 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
174 && fuzzy_name_length < 2
176 cov_mark::hit!(ignore_short_input_for_path);
179 Some(assets_for_path)
184 fn compute_fuzzy_completion_order_key(
185 proposed_mod_path: &ModPath,
186 user_input_lowercased: &str,
188 cov_mark::hit!(certain_fuzzy_order_test);
189 let proposed_import_name = match proposed_mod_path.segments().last() {
190 Some(name) => name.to_string().to_lowercase(),
191 None => return usize::MAX,
193 match proposed_import_name.match_indices(user_input_lowercased).next() {
194 Some((first_matching_index, _)) => first_matching_index,
201 use expect_test::{expect, Expect};
204 item::CompletionKind,
205 test_utils::{check_edit, check_edit_with_config, completion_list, TEST_CONFIG},
208 fn check(ra_fixture: &str, expect: Expect) {
209 let actual = completion_list(ra_fixture, CompletionKind::Magic);
210 expect.assert_eq(&actual);
214 fn function_fuzzy_completion() {
218 //- /lib.rs crate:dep
223 //- /main.rs crate:main deps:dep
239 fn macro_fuzzy_completion() {
241 "macro_with_curlies!",
243 //- /lib.rs crate:dep
244 /// Please call me as macro_with_curlies! {}
246 macro_rules! macro_with_curlies {
250 //- /main.rs crate:main deps:dep
256 use dep::macro_with_curlies;
259 macro_with_curlies! {$0}
266 fn struct_fuzzy_completion() {
270 //- /lib.rs crate:dep
271 pub struct FirstStruct;
272 pub mod some_module {
273 pub struct SecondStruct;
274 pub struct ThirdStruct;
277 //- /main.rs crate:main deps:dep
278 use dep::{FirstStruct, some_module::SecondStruct};
285 use dep::{FirstStruct, some_module::{SecondStruct, ThirdStruct}};
295 fn short_paths_are_ignored() {
296 cov_mark::check!(ignore_short_input_for_path);
300 //- /lib.rs crate:dep
301 pub struct FirstStruct;
302 pub mod some_module {
303 pub struct SecondStruct;
304 pub struct ThirdStruct;
307 //- /main.rs crate:main deps:dep
308 use dep::{FirstStruct, some_module::SecondStruct};
319 fn fuzzy_completions_come_in_specific_order() {
320 cov_mark::check!(certain_fuzzy_order_test);
323 //- /lib.rs crate:dep
324 pub struct FirstStruct;
325 pub mod some_module {
326 // already imported, omitted
327 pub struct SecondStruct;
328 // does not contain all letters from the query, omitted
329 pub struct UnrelatedOne;
330 // contains all letters from the query, but not in sequence, displayed last
331 pub struct ThiiiiiirdStruct;
332 // contains all letters from the query, but not in the beginning, displayed second
333 pub struct AfterThirdStruct;
334 // contains all letters from the query in the begginning, displayed first
335 pub struct ThirdStruct;
338 //- /main.rs crate:main deps:dep
339 use dep::{FirstStruct, some_module::SecondStruct};
346 st dep::some_module::ThirdStruct
347 st dep::some_module::AfterThirdStruct
348 st dep::some_module::ThiiiiiirdStruct
354 fn trait_function_fuzzy_completion() {
356 //- /lib.rs crate:dep
358 pub trait TestTrait {
359 const SPECIAL_CONST: u8;
362 fn random_method(&self);
364 pub struct TestStruct {}
365 impl TestTrait for TestStruct {
366 const SPECIAL_CONST: u8 = 42;
367 type HumbleType = ();
368 fn weird_function() {}
369 fn random_method(&self) {}
373 //- /main.rs crate:main deps:dep
375 dep::test_mod::TestStruct::wei$0
382 fn weird_function() (dep::test_mod::TestTrait) -> ()
390 use dep::test_mod::TestTrait;
393 dep::test_mod::TestStruct::weird_function()$0
400 fn trait_const_fuzzy_completion() {
402 //- /lib.rs crate:dep
404 pub trait TestTrait {
405 const SPECIAL_CONST: u8;
408 fn random_method(&self);
410 pub struct TestStruct {}
411 impl TestTrait for TestStruct {
412 const SPECIAL_CONST: u8 = 42;
413 type HumbleType = ();
414 fn weird_function() {}
415 fn random_method(&self) {}
419 //- /main.rs crate:main deps:dep
421 dep::test_mod::TestStruct::spe$0
428 ct SPECIAL_CONST (dep::test_mod::TestTrait)
436 use dep::test_mod::TestTrait;
439 dep::test_mod::TestStruct::SPECIAL_CONST
446 fn trait_method_fuzzy_completion() {
448 //- /lib.rs crate:dep
450 pub trait TestTrait {
451 const SPECIAL_CONST: u8;
454 fn random_method(&self);
456 pub struct TestStruct {}
457 impl TestTrait for TestStruct {
458 const SPECIAL_CONST: u8 = 42;
459 type HumbleType = ();
460 fn weird_function() {}
461 fn random_method(&self) {}
465 //- /main.rs crate:main deps:dep
467 let test_struct = dep::test_mod::TestStruct {};
475 me random_method() (dep::test_mod::TestTrait) -> ()
483 use dep::test_mod::TestTrait;
486 let test_struct = dep::test_mod::TestStruct {};
487 test_struct.random_method()$0
494 fn no_trait_type_fuzzy_completion() {
497 //- /lib.rs crate:dep
499 pub trait TestTrait {
500 const SPECIAL_CONST: u8;
503 fn random_method(&self);
505 pub struct TestStruct {}
506 impl TestTrait for TestStruct {
507 const SPECIAL_CONST: u8 = 42;
508 type HumbleType = ();
509 fn weird_function() {}
510 fn random_method(&self) {}
514 //- /main.rs crate:main deps:dep
516 dep::test_mod::TestStruct::hum$0
524 fn does_not_propose_names_in_scope() {
527 //- /lib.rs crate:dep
529 pub trait TestTrait {
530 const SPECIAL_CONST: u8;
533 fn random_method(&self);
535 pub struct TestStruct {}
536 impl TestTrait for TestStruct {
537 const SPECIAL_CONST: u8 = 42;
538 type HumbleType = ();
539 fn weird_function() {}
540 fn random_method(&self) {}
544 //- /main.rs crate:main deps:dep
545 use dep::test_mod::TestStruct;
555 fn does_not_propose_traits_in_scope() {
558 //- /lib.rs crate:dep
560 pub trait TestTrait {
561 const SPECIAL_CONST: u8;
564 fn random_method(&self);
566 pub struct TestStruct {}
567 impl TestTrait for TestStruct {
568 const SPECIAL_CONST: u8 = 42;
569 type HumbleType = ();
570 fn weird_function() {}
571 fn random_method(&self) {}
575 //- /main.rs crate:main deps:dep
576 use dep::test_mod::{TestStruct, TestTrait};
578 dep::test_mod::TestStruct::hum$0
586 fn blanket_trait_impl_import() {
590 //- /lib.rs crate:dep
592 pub struct TestStruct {}
593 pub trait TestTrait {
594 fn another_function();
596 impl<T> TestTrait for T {
597 fn another_function() {}
601 //- /main.rs crate:main deps:dep
603 dep::test_mod::TestStruct::ano$0
607 use dep::test_mod::TestTrait;
610 dep::test_mod::TestStruct::another_function()$0
617 fn zero_input_deprecated_assoc_item_completion() {
620 //- /lib.rs crate:dep
623 pub trait TestTrait {
624 const SPECIAL_CONST: u8;
627 fn random_method(&self);
629 pub struct TestStruct {}
630 impl TestTrait for TestStruct {
631 const SPECIAL_CONST: u8 = 42;
632 type HumbleType = ();
633 fn weird_function() {}
634 fn random_method(&self) {}
638 //- /main.rs crate:main deps:dep
640 let test_struct = dep::test_mod::TestStruct {};
645 me random_method() (dep::test_mod::TestTrait) -> () DEPRECATED
651 //- /lib.rs crate:dep
654 pub trait TestTrait {
655 const SPECIAL_CONST: u8;
658 fn random_method(&self);
660 pub struct TestStruct {}
661 impl TestTrait for TestStruct {
662 const SPECIAL_CONST: u8 = 42;
663 type HumbleType = ();
664 fn weird_function() {}
665 fn random_method(&self) {}
669 //- /main.rs crate:main deps:dep
671 dep::test_mod::TestStruct::$0
675 ct SPECIAL_CONST (dep::test_mod::TestTrait) DEPRECATED
676 fn weird_function() (dep::test_mod::TestTrait) -> () DEPRECATED
682 fn no_completions_in_use_statements() {
685 //- /lib.rs crate:dep
690 //- /main.rs crate:main deps:dep
700 fn prefix_config_usage() {
713 let mut config = TEST_CONFIG;
715 config.insert_use.prefix_kind = hir::PrefixKind::ByCrate;
716 check_edit_with_config(
727 use crate::foo::bar::{self, Item};
734 config.insert_use.prefix_kind = hir::PrefixKind::BySelf;
735 check_edit_with_config(
748 use self::foo::bar::Item;
755 config.insert_use.prefix_kind = hir::PrefixKind::Plain;
756 check_edit_with_config(
778 fn unresolved_qualifier() {
813 fn unresolved_assoc_item_container() {
821 pub const TEST_ASSOC: usize = 3;
836 pub const TEST_ASSOC: usize = 3;
848 fn unresolved_assoc_item_container_with_path() {
857 pub const TEST_ASSOC: usize = 3;
874 pub const TEST_ASSOC: usize = 3;
880 bar::Item::TEST_ASSOC