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() || ctx.is_path_disallowed() {
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_with_macros(
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(ctx: &CompletionContext, fuzzy_name: String) -> Option<ImportAssets> {
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)?,
178 dot_receiver.syntax().clone(),
181 let fuzzy_name_length = fuzzy_name.len();
182 let approximate_node = match current_module.definition_source(ctx.db).value {
183 hir::ModuleSource::SourceFile(s) => s.syntax().clone(),
184 hir::ModuleSource::Module(m) => m.syntax().clone(),
185 hir::ModuleSource::BlockExpr(b) => b.syntax().clone(),
187 let assets_for_path = ImportAssets::for_fuzzy_path(
189 ctx.path_qual.clone(),
195 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
196 && fuzzy_name_length < 2
198 cov_mark::hit!(ignore_short_input_for_path);
201 Some(assets_for_path)
206 fn compute_fuzzy_completion_order_key(
207 proposed_mod_path: &ModPath,
208 user_input_lowercased: &str,
210 cov_mark::hit!(certain_fuzzy_order_test);
211 let import_name = match proposed_mod_path.segments().last() {
212 Some(name) => name.to_string().to_lowercase(),
213 None => return usize::MAX,
215 match import_name.match_indices(user_input_lowercased).next() {
216 Some((first_matching_index, _)) => first_matching_index,
223 use expect_test::{expect, Expect};
226 item::CompletionKind,
227 test_utils::{check_edit, check_edit_with_config, completion_list, TEST_CONFIG},
230 fn check(ra_fixture: &str, expect: Expect) {
231 let actual = completion_list(ra_fixture, CompletionKind::Magic);
232 expect.assert_eq(&actual);
236 fn function_fuzzy_completion() {
240 //- /lib.rs crate:dep
245 //- /main.rs crate:main deps:dep
261 fn macro_fuzzy_completion() {
263 "macro_with_curlies!",
265 //- /lib.rs crate:dep
266 /// Please call me as macro_with_curlies! {}
268 macro_rules! macro_with_curlies {
272 //- /main.rs crate:main deps:dep
278 use dep::macro_with_curlies;
281 macro_with_curlies! {$0}
288 fn struct_fuzzy_completion() {
292 //- /lib.rs crate:dep
293 pub struct FirstStruct;
294 pub mod some_module {
295 pub struct SecondStruct;
296 pub struct ThirdStruct;
299 //- /main.rs crate:main deps:dep
300 use dep::{FirstStruct, some_module::SecondStruct};
307 use dep::{FirstStruct, some_module::{SecondStruct, ThirdStruct}};
317 fn short_paths_are_ignored() {
318 cov_mark::check!(ignore_short_input_for_path);
322 //- /lib.rs crate:dep
323 pub struct FirstStruct;
324 pub mod some_module {
325 pub struct SecondStruct;
326 pub struct ThirdStruct;
329 //- /main.rs crate:main deps:dep
330 use dep::{FirstStruct, some_module::SecondStruct};
341 fn fuzzy_completions_come_in_specific_order() {
342 cov_mark::check!(certain_fuzzy_order_test);
345 //- /lib.rs crate:dep
346 pub struct FirstStruct;
347 pub mod some_module {
348 // already imported, omitted
349 pub struct SecondStruct;
350 // does not contain all letters from the query, omitted
351 pub struct UnrelatedOne;
352 // contains all letters from the query, but not in sequence, displayed last
353 pub struct ThiiiiiirdStruct;
354 // contains all letters from the query, but not in the beginning, displayed second
355 pub struct AfterThirdStruct;
356 // contains all letters from the query in the begginning, displayed first
357 pub struct ThirdStruct;
360 //- /main.rs crate:main deps:dep
361 use dep::{FirstStruct, some_module::SecondStruct};
368 st dep::some_module::ThirdStruct
369 st dep::some_module::AfterThirdStruct
370 st dep::some_module::ThiiiiiirdStruct
376 fn trait_function_fuzzy_completion() {
378 //- /lib.rs crate:dep
380 pub trait TestTrait {
381 const SPECIAL_CONST: u8;
384 fn random_method(&self);
386 pub struct TestStruct {}
387 impl TestTrait for TestStruct {
388 const SPECIAL_CONST: u8 = 42;
389 type HumbleType = ();
390 fn weird_function() {}
391 fn random_method(&self) {}
395 //- /main.rs crate:main deps:dep
397 dep::test_mod::TestStruct::wei$0
404 fn weird_function() (dep::test_mod::TestTrait) fn()
412 use dep::test_mod::TestTrait;
415 dep::test_mod::TestStruct::weird_function()$0
422 fn trait_const_fuzzy_completion() {
424 //- /lib.rs crate:dep
426 pub trait TestTrait {
427 const SPECIAL_CONST: u8;
430 fn random_method(&self);
432 pub struct TestStruct {}
433 impl TestTrait for TestStruct {
434 const SPECIAL_CONST: u8 = 42;
435 type HumbleType = ();
436 fn weird_function() {}
437 fn random_method(&self) {}
441 //- /main.rs crate:main deps:dep
443 dep::test_mod::TestStruct::spe$0
450 ct SPECIAL_CONST (dep::test_mod::TestTrait)
458 use dep::test_mod::TestTrait;
461 dep::test_mod::TestStruct::SPECIAL_CONST
468 fn trait_method_fuzzy_completion() {
470 //- /lib.rs crate:dep
472 pub trait TestTrait {
473 const SPECIAL_CONST: u8;
476 fn random_method(&self);
478 pub struct TestStruct {}
479 impl TestTrait for TestStruct {
480 const SPECIAL_CONST: u8 = 42;
481 type HumbleType = ();
482 fn weird_function() {}
483 fn random_method(&self) {}
487 //- /main.rs crate:main deps:dep
489 let test_struct = dep::test_mod::TestStruct {};
497 me random_method() (dep::test_mod::TestTrait) fn(&self)
505 use dep::test_mod::TestTrait;
508 let test_struct = dep::test_mod::TestStruct {};
509 test_struct.random_method()$0
516 fn no_trait_type_fuzzy_completion() {
519 //- /lib.rs crate:dep
521 pub trait TestTrait {
522 const SPECIAL_CONST: u8;
525 fn random_method(&self);
527 pub struct TestStruct {}
528 impl TestTrait for TestStruct {
529 const SPECIAL_CONST: u8 = 42;
530 type HumbleType = ();
531 fn weird_function() {}
532 fn random_method(&self) {}
536 //- /main.rs crate:main deps:dep
538 dep::test_mod::TestStruct::hum$0
546 fn does_not_propose_names_in_scope() {
549 //- /lib.rs crate:dep
551 pub trait TestTrait {
552 const SPECIAL_CONST: u8;
555 fn random_method(&self);
557 pub struct TestStruct {}
558 impl TestTrait for TestStruct {
559 const SPECIAL_CONST: u8 = 42;
560 type HumbleType = ();
561 fn weird_function() {}
562 fn random_method(&self) {}
566 //- /main.rs crate:main deps:dep
567 use dep::test_mod::TestStruct;
577 fn does_not_propose_traits_in_scope() {
580 //- /lib.rs crate:dep
582 pub trait TestTrait {
583 const SPECIAL_CONST: u8;
586 fn random_method(&self);
588 pub struct TestStruct {}
589 impl TestTrait for TestStruct {
590 const SPECIAL_CONST: u8 = 42;
591 type HumbleType = ();
592 fn weird_function() {}
593 fn random_method(&self) {}
597 //- /main.rs crate:main deps:dep
598 use dep::test_mod::{TestStruct, TestTrait};
600 dep::test_mod::TestStruct::hum$0
608 fn blanket_trait_impl_import() {
612 //- /lib.rs crate:dep
614 pub struct TestStruct {}
615 pub trait TestTrait {
616 fn another_function();
618 impl<T> TestTrait for T {
619 fn another_function() {}
623 //- /main.rs crate:main deps:dep
625 dep::test_mod::TestStruct::ano$0
629 use dep::test_mod::TestTrait;
632 dep::test_mod::TestStruct::another_function()$0
639 fn zero_input_deprecated_assoc_item_completion() {
642 //- /lib.rs crate:dep
645 pub trait TestTrait {
646 const SPECIAL_CONST: u8;
649 fn random_method(&self);
651 pub struct TestStruct {}
652 impl TestTrait for TestStruct {
653 const SPECIAL_CONST: u8 = 42;
654 type HumbleType = ();
655 fn weird_function() {}
656 fn random_method(&self) {}
660 //- /main.rs crate:main deps:dep
662 let test_struct = dep::test_mod::TestStruct {};
667 me random_method() (dep::test_mod::TestTrait) fn(&self) DEPRECATED
673 //- /lib.rs crate:dep
676 pub trait TestTrait {
677 const SPECIAL_CONST: u8;
680 fn random_method(&self);
682 pub struct TestStruct {}
683 impl TestTrait for TestStruct {
684 const SPECIAL_CONST: u8 = 42;
685 type HumbleType = ();
686 fn weird_function() {}
687 fn random_method(&self) {}
691 //- /main.rs crate:main deps:dep
693 dep::test_mod::TestStruct::$0
697 ct SPECIAL_CONST (dep::test_mod::TestTrait) DEPRECATED
698 fn weird_function() (dep::test_mod::TestTrait) fn() DEPRECATED
704 fn no_completions_in_use_statements() {
707 //- /lib.rs crate:dep
712 //- /main.rs crate:main deps:dep
722 fn prefix_config_usage() {
735 let mut config = TEST_CONFIG;
737 config.insert_use.prefix_kind = hir::PrefixKind::ByCrate;
738 check_edit_with_config(
749 use crate::foo::bar::{self, Item};
756 config.insert_use.prefix_kind = hir::PrefixKind::BySelf;
757 check_edit_with_config(
770 use self::foo::bar::Item;
777 config.insert_use.prefix_kind = hir::PrefixKind::Plain;
778 check_edit_with_config(
800 fn unresolved_qualifier() {
817 st foo::bar::baz::Item
842 fn unresolved_assoc_item_container() {
848 pub const TEST_ASSOC: usize = 3;
859 ct TEST_ASSOC (foo::Item)
873 pub const TEST_ASSOC: usize = 3;
884 fn unresolved_assoc_item_container_with_path() {
891 pub const TEST_ASSOC: usize = 3;
903 ct TEST_ASSOC (foo::bar::Item)
918 pub const TEST_ASSOC: usize = 3;
924 bar::Item::TEST_ASSOC
930 fn fuzzy_unresolved_path() {
938 pub const TEST_ASSOC: usize = 3;
951 fn unqualified_assoc_items_are_omitted() {
955 pub trait BaseTrait {
956 fn test_function() -> i32;
962 impl BaseTrait for Item1 {
963 fn test_function() -> i32 {
968 impl BaseTrait for Item2 {
969 fn test_function() -> i32 {
987 pub const TEST_CONST: usize = 3;
988 pub fn test_function() -> i32 {
1004 pub const TEST_CONST: usize = 3;
1005 pub fn test_function() -> i32 {
1015 fn test_function() (foo::test_function) fn() -> i32
1022 pub const TEST_CONST: usize = 3;
1023 pub fn test_function() -> i32 {
1036 fn no_fuzzy_during_fields_of_record_lit_syntax() {
1040 pub fn some_fn() -> i32 {
1048 let _ = Foo { so$0 };
1056 fn fuzzy_after_fields_of_record_lit_syntax() {
1060 pub fn some_fn() -> i32 {
1068 let _ = Foo { some_field: so$0 };
1072 fn some_fn() (m::some_fn) fn() -> i32
1078 fn no_flyimports_in_traits_and_impl_declarations() {
1082 pub fn some_fn() -> i32 {
1096 pub fn some_fn() -> i32 {
1111 pub fn some_fn() -> i32 {
1126 fn no_inherent_candidates_proposed() {
1130 pub trait DefDatabase {
1133 pub trait HirDatabase: DefDatabase {
1139 fn test(db: &dyn crate::baz::HirDatabase) {