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.
24 //! If any unresolved and/or partially-qualified path predeces the input, it will be taken into account: only the items with import string
25 //! containing this whole path will be considered and the corresponding path import will be added:
33 //! pub const TEST_ASSOC: usize = 3;
39 //! bar::Item::TEST_A$0
51 //! pub const TEST_ASSOC: usize = 3;
57 //! bar::Item::TEST_ASSOC
61 //! NOTE: currently, if an assoc item comes from a trait that's not currently imported and it also has an unresolved and/or partially-qualified path,
62 //! no imports will be proposed.
64 //! .Fuzzy search details
66 //! To avoid an excessive amount of the results returned, completion input is checked for inclusion in the names only
67 //! (i.e. in `HashMap` in the `std::collections::HashMap` path).
68 //! For the same reasons, avoids searching for any path imports for inputs with their length less that 2 symbols
69 //! (but shows all associated items for any input length).
71 //! .Import configuration
73 //! It is possible to configure how use-trees are merged with the `importMergeBehavior` setting.
74 //! Mimics the corresponding behavior of the `Auto Import` feature.
76 //! .LSP and performance implications
78 //! The feature is enabled only if the LSP client supports LSP protocol version 3.16+ and reports the `additionalTextEdits`
79 //! (case sensitive) resolve client capability in its client capabilities.
80 //! This way the server is able to defer the costly computations, doing them for a selected completion item only.
81 //! For clients with no such support, all edits have to be calculated on the completion request, including the fuzzy search completion ones,
82 //! which might be slow ergo the feature is automatically disabled.
86 //! The feature can be forcefully turned off in the settings with the `rust-analyzer.completion.enableAutoimportCompletions` flag.
87 //! Note that having this flag set to `true` does not guarantee that the feature is enabled: your client needs to have the corredponding
88 //! capability enabled.
91 use ide_db::helpers::{
92 import_assets::{ImportAssets, ImportCandidate},
93 insert_use::ImportScope,
95 use itertools::Itertools;
96 use syntax::{AstNode, SyntaxNode, T};
99 context::CompletionContext,
100 render::{render_resolution_with_import, RenderContext},
104 use super::Completions;
106 pub(crate) fn import_on_the_fly(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
107 if !ctx.config.enable_imports_on_the_fly {
110 if ctx.use_item_syntax.is_some()
111 || ctx.attribute_under_caret.is_some()
112 || ctx.mod_declaration_under_caret.is_some()
116 let potential_import_name = {
117 let token_kind = ctx.token.kind();
118 if matches!(token_kind, T![.] | T![::]) {
121 ctx.token.to_string()
125 let _p = profile::span("import_on_the_fly").detail(|| potential_import_name.to_string());
127 let user_input_lowercased = potential_import_name.to_lowercase();
128 let import_assets = import_assets(ctx, potential_import_name)?;
129 let import_scope = ImportScope::find_insert_use_container(
130 position_for_import(ctx, Some(import_assets.import_candidate()))?,
136 .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
138 .sorted_by_key(|located_import| {
139 compute_fuzzy_completion_order_key(
140 &located_import.import_path,
141 &user_input_lowercased,
144 .filter_map(|import| {
145 render_resolution_with_import(
146 RenderContext::new(ctx),
147 ImportEdit { import, scope: import_scope.clone() },
154 pub(crate) fn position_for_import<'a>(
155 ctx: &'a CompletionContext,
156 import_candidate: Option<&ImportCandidate>,
157 ) -> Option<&'a SyntaxNode> {
158 Some(match import_candidate {
159 Some(ImportCandidate::Path(_)) => ctx.name_ref_syntax.as_ref()?.syntax(),
160 Some(ImportCandidate::TraitAssocItem(_)) => ctx.path_qual.as_ref()?.syntax(),
161 Some(ImportCandidate::TraitMethod(_)) => ctx.dot_receiver.as_ref()?.syntax(),
165 .map(|name_ref| name_ref.syntax())
166 .or_else(|| ctx.path_qual.as_ref().map(|path| path.syntax()))
167 .or_else(|| ctx.dot_receiver.as_ref().map(|expr| expr.syntax()))?,
171 fn import_assets<'a>(ctx: &'a CompletionContext, fuzzy_name: String) -> Option<ImportAssets<'a>> {
172 let current_module = ctx.scope.module()?;
173 if let Some(dot_receiver) = &ctx.dot_receiver {
174 ImportAssets::for_fuzzy_method_call(
176 ctx.sema.type_of_expr(dot_receiver)?,
181 let fuzzy_name_length = fuzzy_name.len();
182 let assets_for_path = ImportAssets::for_fuzzy_path(
184 ctx.path_qual.clone(),
190 // TODO kb bad: with the path prefix, the "min 3 symbols" limit applies. Fix in a separate PR on the symbol_index level
191 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
192 && fuzzy_name_length < 2
194 cov_mark::hit!(ignore_short_input_for_path);
197 Some(assets_for_path)
202 fn compute_fuzzy_completion_order_key(
203 proposed_mod_path: &ModPath,
204 user_input_lowercased: &str,
206 cov_mark::hit!(certain_fuzzy_order_test);
207 let import_name = match proposed_mod_path.segments().last() {
208 Some(name) => name.to_string().to_lowercase(),
209 None => return usize::MAX,
211 match import_name.match_indices(user_input_lowercased).next() {
212 Some((first_matching_index, _)) => first_matching_index,
219 use expect_test::{expect, Expect};
222 item::CompletionKind,
223 test_utils::{check_edit, check_edit_with_config, completion_list, TEST_CONFIG},
226 fn check(ra_fixture: &str, expect: Expect) {
227 let actual = completion_list(ra_fixture, CompletionKind::Magic);
228 expect.assert_eq(&actual);
232 fn function_fuzzy_completion() {
236 //- /lib.rs crate:dep
241 //- /main.rs crate:main deps:dep
257 fn macro_fuzzy_completion() {
259 "macro_with_curlies!",
261 //- /lib.rs crate:dep
262 /// Please call me as macro_with_curlies! {}
264 macro_rules! macro_with_curlies {
268 //- /main.rs crate:main deps:dep
274 use dep::macro_with_curlies;
277 macro_with_curlies! {$0}
284 fn struct_fuzzy_completion() {
288 //- /lib.rs crate:dep
289 pub struct FirstStruct;
290 pub mod some_module {
291 pub struct SecondStruct;
292 pub struct ThirdStruct;
295 //- /main.rs crate:main deps:dep
296 use dep::{FirstStruct, some_module::SecondStruct};
303 use dep::{FirstStruct, some_module::{SecondStruct, ThirdStruct}};
313 fn short_paths_are_ignored() {
314 cov_mark::check!(ignore_short_input_for_path);
318 //- /lib.rs crate:dep
319 pub struct FirstStruct;
320 pub mod some_module {
321 pub struct SecondStruct;
322 pub struct ThirdStruct;
325 //- /main.rs crate:main deps:dep
326 use dep::{FirstStruct, some_module::SecondStruct};
337 fn fuzzy_completions_come_in_specific_order() {
338 cov_mark::check!(certain_fuzzy_order_test);
341 //- /lib.rs crate:dep
342 pub struct FirstStruct;
343 pub mod some_module {
344 // already imported, omitted
345 pub struct SecondStruct;
346 // does not contain all letters from the query, omitted
347 pub struct UnrelatedOne;
348 // contains all letters from the query, but not in sequence, displayed last
349 pub struct ThiiiiiirdStruct;
350 // contains all letters from the query, but not in the beginning, displayed second
351 pub struct AfterThirdStruct;
352 // contains all letters from the query in the begginning, displayed first
353 pub struct ThirdStruct;
356 //- /main.rs crate:main deps:dep
357 use dep::{FirstStruct, some_module::SecondStruct};
364 st dep::some_module::ThirdStruct
365 st dep::some_module::AfterThirdStruct
366 st dep::some_module::ThiiiiiirdStruct
372 fn trait_function_fuzzy_completion() {
374 //- /lib.rs crate:dep
376 pub trait TestTrait {
377 const SPECIAL_CONST: u8;
380 fn random_method(&self);
382 pub struct TestStruct {}
383 impl TestTrait for TestStruct {
384 const SPECIAL_CONST: u8 = 42;
385 type HumbleType = ();
386 fn weird_function() {}
387 fn random_method(&self) {}
391 //- /main.rs crate:main deps:dep
393 dep::test_mod::TestStruct::wei$0
400 fn weird_function() (dep::test_mod::TestTrait) -> ()
408 use dep::test_mod::TestTrait;
411 dep::test_mod::TestStruct::weird_function()$0
418 fn trait_const_fuzzy_completion() {
420 //- /lib.rs crate:dep
422 pub trait TestTrait {
423 const SPECIAL_CONST: u8;
426 fn random_method(&self);
428 pub struct TestStruct {}
429 impl TestTrait for TestStruct {
430 const SPECIAL_CONST: u8 = 42;
431 type HumbleType = ();
432 fn weird_function() {}
433 fn random_method(&self) {}
437 //- /main.rs crate:main deps:dep
439 dep::test_mod::TestStruct::spe$0
446 ct SPECIAL_CONST (dep::test_mod::TestTrait)
454 use dep::test_mod::TestTrait;
457 dep::test_mod::TestStruct::SPECIAL_CONST
464 fn trait_method_fuzzy_completion() {
466 //- /lib.rs crate:dep
468 pub trait TestTrait {
469 const SPECIAL_CONST: u8;
472 fn random_method(&self);
474 pub struct TestStruct {}
475 impl TestTrait for TestStruct {
476 const SPECIAL_CONST: u8 = 42;
477 type HumbleType = ();
478 fn weird_function() {}
479 fn random_method(&self) {}
483 //- /main.rs crate:main deps:dep
485 let test_struct = dep::test_mod::TestStruct {};
493 me random_method() (dep::test_mod::TestTrait) -> ()
501 use dep::test_mod::TestTrait;
504 let test_struct = dep::test_mod::TestStruct {};
505 test_struct.random_method()$0
512 fn no_trait_type_fuzzy_completion() {
515 //- /lib.rs crate:dep
517 pub trait TestTrait {
518 const SPECIAL_CONST: u8;
521 fn random_method(&self);
523 pub struct TestStruct {}
524 impl TestTrait for TestStruct {
525 const SPECIAL_CONST: u8 = 42;
526 type HumbleType = ();
527 fn weird_function() {}
528 fn random_method(&self) {}
532 //- /main.rs crate:main deps:dep
534 dep::test_mod::TestStruct::hum$0
542 fn does_not_propose_names_in_scope() {
545 //- /lib.rs crate:dep
547 pub trait TestTrait {
548 const SPECIAL_CONST: u8;
551 fn random_method(&self);
553 pub struct TestStruct {}
554 impl TestTrait for TestStruct {
555 const SPECIAL_CONST: u8 = 42;
556 type HumbleType = ();
557 fn weird_function() {}
558 fn random_method(&self) {}
562 //- /main.rs crate:main deps:dep
563 use dep::test_mod::TestStruct;
573 fn does_not_propose_traits_in_scope() {
576 //- /lib.rs crate:dep
578 pub trait TestTrait {
579 const SPECIAL_CONST: u8;
582 fn random_method(&self);
584 pub struct TestStruct {}
585 impl TestTrait for TestStruct {
586 const SPECIAL_CONST: u8 = 42;
587 type HumbleType = ();
588 fn weird_function() {}
589 fn random_method(&self) {}
593 //- /main.rs crate:main deps:dep
594 use dep::test_mod::{TestStruct, TestTrait};
596 dep::test_mod::TestStruct::hum$0
604 fn blanket_trait_impl_import() {
608 //- /lib.rs crate:dep
610 pub struct TestStruct {}
611 pub trait TestTrait {
612 fn another_function();
614 impl<T> TestTrait for T {
615 fn another_function() {}
619 //- /main.rs crate:main deps:dep
621 dep::test_mod::TestStruct::ano$0
625 use dep::test_mod::TestTrait;
628 dep::test_mod::TestStruct::another_function()$0
635 fn zero_input_deprecated_assoc_item_completion() {
638 //- /lib.rs crate:dep
641 pub trait TestTrait {
642 const SPECIAL_CONST: u8;
645 fn random_method(&self);
647 pub struct TestStruct {}
648 impl TestTrait for TestStruct {
649 const SPECIAL_CONST: u8 = 42;
650 type HumbleType = ();
651 fn weird_function() {}
652 fn random_method(&self) {}
656 //- /main.rs crate:main deps:dep
658 let test_struct = dep::test_mod::TestStruct {};
663 me random_method() (dep::test_mod::TestTrait) -> () DEPRECATED
669 //- /lib.rs crate:dep
672 pub trait TestTrait {
673 const SPECIAL_CONST: u8;
676 fn random_method(&self);
678 pub struct TestStruct {}
679 impl TestTrait for TestStruct {
680 const SPECIAL_CONST: u8 = 42;
681 type HumbleType = ();
682 fn weird_function() {}
683 fn random_method(&self) {}
687 //- /main.rs crate:main deps:dep
689 dep::test_mod::TestStruct::$0
693 ct SPECIAL_CONST (dep::test_mod::TestTrait) DEPRECATED
694 fn weird_function() (dep::test_mod::TestTrait) -> () DEPRECATED
700 fn no_completions_in_use_statements() {
703 //- /lib.rs crate:dep
708 //- /main.rs crate:main deps:dep
718 fn prefix_config_usage() {
731 let mut config = TEST_CONFIG;
733 config.insert_use.prefix_kind = hir::PrefixKind::ByCrate;
734 check_edit_with_config(
745 use crate::foo::bar::{self, Item};
752 config.insert_use.prefix_kind = hir::PrefixKind::BySelf;
753 check_edit_with_config(
766 use self::foo::bar::Item;
773 config.insert_use.prefix_kind = hir::PrefixKind::Plain;
774 check_edit_with_config(
796 fn unresolved_qualifier() {
813 st foo::bar::baz::Item
838 fn unresolved_assoc_item_container() {
844 pub const TEST_ASSOC: usize = 3;
855 ct TEST_ASSOC (foo::Item)
869 pub const TEST_ASSOC: usize = 3;
880 fn unresolved_assoc_item_container_with_path() {
887 pub const TEST_ASSOC: usize = 3;
899 ct TEST_ASSOC (foo::bar::Item)
914 pub const TEST_ASSOC: usize = 3;
920 bar::Item::TEST_ASSOC