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.
6 //! To be considered applicable, the name must contain all input symbols in the given order, not necessarily adjacent.
7 //! If any input symbol is not lowercased, the name must contain all symbols in exact case; otherwise the contaning is checked case-insensitively.
13 //! # pub mod std { pub mod marker { pub struct PhantomData { } } }
17 //! use std::marker::PhantomData;
22 //! # pub mod std { pub mod marker { pub struct PhantomData { } } }
25 //! Also completes associated items, that require trait imports.
26 //! If any unresolved and/or partially-qualified path predeces the input, it will be taken into account.
27 //! Currently, only the imports with their import path ending with the whole qialifier will be proposed
28 //! (no fuzzy matching for qualifier).
36 //! pub const TEST_ASSOC: usize = 3;
42 //! bar::Item::TEST_A$0
54 //! pub const TEST_ASSOC: usize = 3;
60 //! bar::Item::TEST_ASSOC
64 //! 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,
65 //! no imports will be proposed.
67 //! .Fuzzy search details
69 //! To avoid an excessive amount of the results returned, completion input is checked for inclusion in the names only
70 //! (i.e. in `HashMap` in the `std::collections::HashMap` path).
71 //! For the same reasons, avoids searching for any path imports for inputs with their length less that 2 symbols
72 //! (but shows all associated items for any input length).
74 //! .Import configuration
76 //! It is possible to configure how use-trees are merged with the `importMergeBehavior` setting.
77 //! Mimics the corresponding behavior of the `Auto Import` feature.
79 //! .LSP and performance implications
81 //! The feature is enabled only if the LSP client supports LSP protocol version 3.16+ and reports the `additionalTextEdits`
82 //! (case sensitive) resolve client capability in its client capabilities.
83 //! This way the server is able to defer the costly computations, doing them for a selected completion item only.
84 //! For clients with no such support, all edits have to be calculated on the completion request, including the fuzzy search completion ones,
85 //! which might be slow ergo the feature is automatically disabled.
89 //! The feature can be forcefully turned off in the settings with the `rust-analyzer.completion.enableAutoimportCompletions` flag.
90 //! Note that having this flag set to `true` does not guarantee that the feature is enabled: your client needs to have the corredponding
91 //! capability enabled.
94 use ide_db::helpers::{
95 import_assets::{ImportAssets, ImportCandidate},
96 insert_use::ImportScope,
98 use itertools::Itertools;
99 use syntax::{AstNode, SyntaxNode, T};
102 context::CompletionContext,
103 render::{render_resolution_with_import, RenderContext},
107 use super::Completions;
109 pub(crate) fn import_on_the_fly(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
110 if !ctx.config.enable_imports_on_the_fly {
113 if ctx.use_item_syntax.is_some()
114 || ctx.attribute_under_caret.is_some()
115 || ctx.mod_declaration_under_caret.is_some()
119 let potential_import_name = {
120 let token_kind = ctx.token.kind();
121 if matches!(token_kind, T![.] | T![::]) {
124 ctx.token.to_string()
128 let _p = profile::span("import_on_the_fly").detail(|| potential_import_name.to_string());
130 let user_input_lowercased = potential_import_name.to_lowercase();
131 let import_assets = import_assets(ctx, potential_import_name)?;
132 let import_scope = ImportScope::find_insert_use_container(
133 position_for_import(ctx, Some(import_assets.import_candidate()))?,
139 .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
141 .sorted_by_key(|located_import| {
142 compute_fuzzy_completion_order_key(
143 &located_import.import_path,
144 &user_input_lowercased,
147 .filter_map(|import| {
148 render_resolution_with_import(
149 RenderContext::new(ctx),
150 ImportEdit { import, scope: import_scope.clone() },
157 pub(crate) fn position_for_import<'a>(
158 ctx: &'a CompletionContext,
159 import_candidate: Option<&ImportCandidate>,
160 ) -> Option<&'a SyntaxNode> {
161 Some(match import_candidate {
162 Some(ImportCandidate::Path(_)) => ctx.name_ref_syntax.as_ref()?.syntax(),
163 Some(ImportCandidate::TraitAssocItem(_)) => ctx.path_qual.as_ref()?.syntax(),
164 Some(ImportCandidate::TraitMethod(_)) => ctx.dot_receiver.as_ref()?.syntax(),
168 .map(|name_ref| name_ref.syntax())
169 .or_else(|| ctx.path_qual.as_ref().map(|path| path.syntax()))
170 .or_else(|| ctx.dot_receiver.as_ref().map(|expr| expr.syntax()))?,
174 fn import_assets(ctx: &CompletionContext, fuzzy_name: String) -> Option<ImportAssets> {
175 let current_module = ctx.scope.module()?;
176 if let Some(dot_receiver) = &ctx.dot_receiver {
177 ImportAssets::for_fuzzy_method_call(
179 ctx.sema.type_of_expr(dot_receiver)?,
181 dot_receiver.syntax().clone(),
184 let fuzzy_name_length = fuzzy_name.len();
185 let approximate_node = match current_module.definition_source(ctx.db).value {
186 hir::ModuleSource::SourceFile(s) => s.syntax().clone(),
187 hir::ModuleSource::Module(m) => m.syntax().clone(),
188 hir::ModuleSource::BlockExpr(b) => b.syntax().clone(),
190 let assets_for_path = ImportAssets::for_fuzzy_path(
192 ctx.path_qual.clone(),
198 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
199 && fuzzy_name_length < 2
201 cov_mark::hit!(ignore_short_input_for_path);
204 Some(assets_for_path)
209 fn compute_fuzzy_completion_order_key(
210 proposed_mod_path: &ModPath,
211 user_input_lowercased: &str,
213 cov_mark::hit!(certain_fuzzy_order_test);
214 let import_name = match proposed_mod_path.segments().last() {
215 Some(name) => name.to_string().to_lowercase(),
216 None => return usize::MAX,
218 match import_name.match_indices(user_input_lowercased).next() {
219 Some((first_matching_index, _)) => first_matching_index,
226 use expect_test::{expect, Expect};
229 item::CompletionKind,
230 test_utils::{check_edit, check_edit_with_config, completion_list, TEST_CONFIG},
233 fn check(ra_fixture: &str, expect: Expect) {
234 let actual = completion_list(ra_fixture, CompletionKind::Magic);
235 expect.assert_eq(&actual);
239 fn function_fuzzy_completion() {
243 //- /lib.rs crate:dep
248 //- /main.rs crate:main deps:dep
264 fn macro_fuzzy_completion() {
266 "macro_with_curlies!",
268 //- /lib.rs crate:dep
269 /// Please call me as macro_with_curlies! {}
271 macro_rules! macro_with_curlies {
275 //- /main.rs crate:main deps:dep
281 use dep::macro_with_curlies;
284 macro_with_curlies! {$0}
291 fn struct_fuzzy_completion() {
295 //- /lib.rs crate:dep
296 pub struct FirstStruct;
297 pub mod some_module {
298 pub struct SecondStruct;
299 pub struct ThirdStruct;
302 //- /main.rs crate:main deps:dep
303 use dep::{FirstStruct, some_module::SecondStruct};
310 use dep::{FirstStruct, some_module::{SecondStruct, ThirdStruct}};
320 fn short_paths_are_ignored() {
321 cov_mark::check!(ignore_short_input_for_path);
325 //- /lib.rs crate:dep
326 pub struct FirstStruct;
327 pub mod some_module {
328 pub struct SecondStruct;
329 pub struct ThirdStruct;
332 //- /main.rs crate:main deps:dep
333 use dep::{FirstStruct, some_module::SecondStruct};
344 fn fuzzy_completions_come_in_specific_order() {
345 cov_mark::check!(certain_fuzzy_order_test);
348 //- /lib.rs crate:dep
349 pub struct FirstStruct;
350 pub mod some_module {
351 // already imported, omitted
352 pub struct SecondStruct;
353 // does not contain all letters from the query, omitted
354 pub struct UnrelatedOne;
355 // contains all letters from the query, but not in sequence, displayed last
356 pub struct ThiiiiiirdStruct;
357 // contains all letters from the query, but not in the beginning, displayed second
358 pub struct AfterThirdStruct;
359 // contains all letters from the query in the begginning, displayed first
360 pub struct ThirdStruct;
363 //- /main.rs crate:main deps:dep
364 use dep::{FirstStruct, some_module::SecondStruct};
371 st dep::some_module::ThirdStruct
372 st dep::some_module::AfterThirdStruct
373 st dep::some_module::ThiiiiiirdStruct
379 fn trait_function_fuzzy_completion() {
381 //- /lib.rs crate:dep
383 pub trait TestTrait {
384 const SPECIAL_CONST: u8;
387 fn random_method(&self);
389 pub struct TestStruct {}
390 impl TestTrait for TestStruct {
391 const SPECIAL_CONST: u8 = 42;
392 type HumbleType = ();
393 fn weird_function() {}
394 fn random_method(&self) {}
398 //- /main.rs crate:main deps:dep
400 dep::test_mod::TestStruct::wei$0
407 fn weird_function() (dep::test_mod::TestTrait) fn()
415 use dep::test_mod::TestTrait;
418 dep::test_mod::TestStruct::weird_function()$0
425 fn trait_const_fuzzy_completion() {
427 //- /lib.rs crate:dep
429 pub trait TestTrait {
430 const SPECIAL_CONST: u8;
433 fn random_method(&self);
435 pub struct TestStruct {}
436 impl TestTrait for TestStruct {
437 const SPECIAL_CONST: u8 = 42;
438 type HumbleType = ();
439 fn weird_function() {}
440 fn random_method(&self) {}
444 //- /main.rs crate:main deps:dep
446 dep::test_mod::TestStruct::spe$0
453 ct SPECIAL_CONST (dep::test_mod::TestTrait)
461 use dep::test_mod::TestTrait;
464 dep::test_mod::TestStruct::SPECIAL_CONST
471 fn trait_method_fuzzy_completion() {
473 //- /lib.rs crate:dep
475 pub trait TestTrait {
476 const SPECIAL_CONST: u8;
479 fn random_method(&self);
481 pub struct TestStruct {}
482 impl TestTrait for TestStruct {
483 const SPECIAL_CONST: u8 = 42;
484 type HumbleType = ();
485 fn weird_function() {}
486 fn random_method(&self) {}
490 //- /main.rs crate:main deps:dep
492 let test_struct = dep::test_mod::TestStruct {};
500 me random_method() (dep::test_mod::TestTrait) fn(&self)
508 use dep::test_mod::TestTrait;
511 let test_struct = dep::test_mod::TestStruct {};
512 test_struct.random_method()$0
519 fn no_trait_type_fuzzy_completion() {
522 //- /lib.rs crate:dep
524 pub trait TestTrait {
525 const SPECIAL_CONST: u8;
528 fn random_method(&self);
530 pub struct TestStruct {}
531 impl TestTrait for TestStruct {
532 const SPECIAL_CONST: u8 = 42;
533 type HumbleType = ();
534 fn weird_function() {}
535 fn random_method(&self) {}
539 //- /main.rs crate:main deps:dep
541 dep::test_mod::TestStruct::hum$0
549 fn does_not_propose_names_in_scope() {
552 //- /lib.rs crate:dep
554 pub trait TestTrait {
555 const SPECIAL_CONST: u8;
558 fn random_method(&self);
560 pub struct TestStruct {}
561 impl TestTrait for TestStruct {
562 const SPECIAL_CONST: u8 = 42;
563 type HumbleType = ();
564 fn weird_function() {}
565 fn random_method(&self) {}
569 //- /main.rs crate:main deps:dep
570 use dep::test_mod::TestStruct;
580 fn does_not_propose_traits_in_scope() {
583 //- /lib.rs crate:dep
585 pub trait TestTrait {
586 const SPECIAL_CONST: u8;
589 fn random_method(&self);
591 pub struct TestStruct {}
592 impl TestTrait for TestStruct {
593 const SPECIAL_CONST: u8 = 42;
594 type HumbleType = ();
595 fn weird_function() {}
596 fn random_method(&self) {}
600 //- /main.rs crate:main deps:dep
601 use dep::test_mod::{TestStruct, TestTrait};
603 dep::test_mod::TestStruct::hum$0
611 fn blanket_trait_impl_import() {
615 //- /lib.rs crate:dep
617 pub struct TestStruct {}
618 pub trait TestTrait {
619 fn another_function();
621 impl<T> TestTrait for T {
622 fn another_function() {}
626 //- /main.rs crate:main deps:dep
628 dep::test_mod::TestStruct::ano$0
632 use dep::test_mod::TestTrait;
635 dep::test_mod::TestStruct::another_function()$0
642 fn zero_input_deprecated_assoc_item_completion() {
645 //- /lib.rs crate:dep
648 pub trait TestTrait {
649 const SPECIAL_CONST: u8;
652 fn random_method(&self);
654 pub struct TestStruct {}
655 impl TestTrait for TestStruct {
656 const SPECIAL_CONST: u8 = 42;
657 type HumbleType = ();
658 fn weird_function() {}
659 fn random_method(&self) {}
663 //- /main.rs crate:main deps:dep
665 let test_struct = dep::test_mod::TestStruct {};
670 me random_method() (dep::test_mod::TestTrait) fn(&self) DEPRECATED
676 //- /lib.rs crate:dep
679 pub trait TestTrait {
680 const SPECIAL_CONST: u8;
683 fn random_method(&self);
685 pub struct TestStruct {}
686 impl TestTrait for TestStruct {
687 const SPECIAL_CONST: u8 = 42;
688 type HumbleType = ();
689 fn weird_function() {}
690 fn random_method(&self) {}
694 //- /main.rs crate:main deps:dep
696 dep::test_mod::TestStruct::$0
700 ct SPECIAL_CONST (dep::test_mod::TestTrait) DEPRECATED
701 fn weird_function() (dep::test_mod::TestTrait) fn() DEPRECATED
707 fn no_completions_in_use_statements() {
710 //- /lib.rs crate:dep
715 //- /main.rs crate:main deps:dep
725 fn prefix_config_usage() {
738 let mut config = TEST_CONFIG;
740 config.insert_use.prefix_kind = hir::PrefixKind::ByCrate;
741 check_edit_with_config(
752 use crate::foo::bar::{self, Item};
759 config.insert_use.prefix_kind = hir::PrefixKind::BySelf;
760 check_edit_with_config(
773 use self::foo::bar::Item;
780 config.insert_use.prefix_kind = hir::PrefixKind::Plain;
781 check_edit_with_config(
803 fn unresolved_qualifier() {
820 st foo::bar::baz::Item
845 fn unresolved_assoc_item_container() {
851 pub const TEST_ASSOC: usize = 3;
862 ct TEST_ASSOC (foo::Item)
876 pub const TEST_ASSOC: usize = 3;
887 fn unresolved_assoc_item_container_with_path() {
894 pub const TEST_ASSOC: usize = 3;
906 ct TEST_ASSOC (foo::bar::Item)
921 pub const TEST_ASSOC: usize = 3;
927 bar::Item::TEST_ASSOC
933 fn fuzzy_unresolved_path() {
941 pub const TEST_ASSOC: usize = 3;
954 fn unqualified_assoc_items_are_omitted() {
958 pub trait BaseTrait {
959 fn test_function() -> i32;
965 impl BaseTrait for Item1 {
966 fn test_function() -> i32 {
971 impl BaseTrait for Item2 {
972 fn test_function() -> i32 {
990 pub const TEST_CONST: usize = 3;
991 pub fn test_function() -> i32 {
1007 pub const TEST_CONST: usize = 3;
1008 pub fn test_function() -> i32 {
1018 fn test_function() (foo::test_function) fn() -> i32
1025 pub const TEST_CONST: usize = 3;
1026 pub fn test_function() -> i32 {