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()
116 || ctx.record_lit_syntax.is_some()
117 || ctx.has_impl_or_trait_parent()
121 let potential_import_name = {
122 let token_kind = ctx.token.kind();
123 if matches!(token_kind, T![.] | T![::]) {
126 ctx.token.to_string()
130 let _p = profile::span("import_on_the_fly").detail(|| potential_import_name.to_string());
132 let user_input_lowercased = potential_import_name.to_lowercase();
133 let import_assets = import_assets(ctx, potential_import_name)?;
134 let import_scope = ImportScope::find_insert_use_container_with_macros(
135 position_for_import(ctx, Some(import_assets.import_candidate()))?,
141 .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
143 .sorted_by_key(|located_import| {
144 compute_fuzzy_completion_order_key(
145 &located_import.import_path,
146 &user_input_lowercased,
149 .filter_map(|import| {
150 render_resolution_with_import(
151 RenderContext::new(ctx),
152 ImportEdit { import, scope: import_scope.clone() },
159 pub(crate) fn position_for_import<'a>(
160 ctx: &'a CompletionContext,
161 import_candidate: Option<&ImportCandidate>,
162 ) -> Option<&'a SyntaxNode> {
163 Some(match import_candidate {
164 Some(ImportCandidate::Path(_)) => ctx.name_ref_syntax.as_ref()?.syntax(),
165 Some(ImportCandidate::TraitAssocItem(_)) => ctx.path_qual.as_ref()?.syntax(),
166 Some(ImportCandidate::TraitMethod(_)) => ctx.dot_receiver.as_ref()?.syntax(),
170 .map(|name_ref| name_ref.syntax())
171 .or_else(|| ctx.path_qual.as_ref().map(|path| path.syntax()))
172 .or_else(|| ctx.dot_receiver.as_ref().map(|expr| expr.syntax()))?,
176 fn import_assets(ctx: &CompletionContext, fuzzy_name: String) -> Option<ImportAssets> {
177 let current_module = ctx.scope.module()?;
178 if let Some(dot_receiver) = &ctx.dot_receiver {
179 ImportAssets::for_fuzzy_method_call(
181 ctx.sema.type_of_expr(dot_receiver)?,
183 dot_receiver.syntax().clone(),
186 let fuzzy_name_length = fuzzy_name.len();
187 let approximate_node = match current_module.definition_source(ctx.db).value {
188 hir::ModuleSource::SourceFile(s) => s.syntax().clone(),
189 hir::ModuleSource::Module(m) => m.syntax().clone(),
190 hir::ModuleSource::BlockExpr(b) => b.syntax().clone(),
192 let assets_for_path = ImportAssets::for_fuzzy_path(
194 ctx.path_qual.clone(),
200 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
201 && fuzzy_name_length < 2
203 cov_mark::hit!(ignore_short_input_for_path);
206 Some(assets_for_path)
211 fn compute_fuzzy_completion_order_key(
212 proposed_mod_path: &ModPath,
213 user_input_lowercased: &str,
215 cov_mark::hit!(certain_fuzzy_order_test);
216 let import_name = match proposed_mod_path.segments().last() {
217 Some(name) => name.to_string().to_lowercase(),
218 None => return usize::MAX,
220 match import_name.match_indices(user_input_lowercased).next() {
221 Some((first_matching_index, _)) => first_matching_index,
228 use expect_test::{expect, Expect};
231 item::CompletionKind,
232 test_utils::{check_edit, check_edit_with_config, completion_list, TEST_CONFIG},
235 fn check(ra_fixture: &str, expect: Expect) {
236 let actual = completion_list(ra_fixture, CompletionKind::Magic);
237 expect.assert_eq(&actual);
241 fn function_fuzzy_completion() {
245 //- /lib.rs crate:dep
250 //- /main.rs crate:main deps:dep
266 fn macro_fuzzy_completion() {
268 "macro_with_curlies!",
270 //- /lib.rs crate:dep
271 /// Please call me as macro_with_curlies! {}
273 macro_rules! macro_with_curlies {
277 //- /main.rs crate:main deps:dep
283 use dep::macro_with_curlies;
286 macro_with_curlies! {$0}
293 fn struct_fuzzy_completion() {
297 //- /lib.rs crate:dep
298 pub struct FirstStruct;
299 pub mod some_module {
300 pub struct SecondStruct;
301 pub struct ThirdStruct;
304 //- /main.rs crate:main deps:dep
305 use dep::{FirstStruct, some_module::SecondStruct};
312 use dep::{FirstStruct, some_module::{SecondStruct, ThirdStruct}};
322 fn short_paths_are_ignored() {
323 cov_mark::check!(ignore_short_input_for_path);
327 //- /lib.rs crate:dep
328 pub struct FirstStruct;
329 pub mod some_module {
330 pub struct SecondStruct;
331 pub struct ThirdStruct;
334 //- /main.rs crate:main deps:dep
335 use dep::{FirstStruct, some_module::SecondStruct};
346 fn fuzzy_completions_come_in_specific_order() {
347 cov_mark::check!(certain_fuzzy_order_test);
350 //- /lib.rs crate:dep
351 pub struct FirstStruct;
352 pub mod some_module {
353 // already imported, omitted
354 pub struct SecondStruct;
355 // does not contain all letters from the query, omitted
356 pub struct UnrelatedOne;
357 // contains all letters from the query, but not in sequence, displayed last
358 pub struct ThiiiiiirdStruct;
359 // contains all letters from the query, but not in the beginning, displayed second
360 pub struct AfterThirdStruct;
361 // contains all letters from the query in the begginning, displayed first
362 pub struct ThirdStruct;
365 //- /main.rs crate:main deps:dep
366 use dep::{FirstStruct, some_module::SecondStruct};
373 st dep::some_module::ThirdStruct
374 st dep::some_module::AfterThirdStruct
375 st dep::some_module::ThiiiiiirdStruct
381 fn trait_function_fuzzy_completion() {
383 //- /lib.rs crate:dep
385 pub trait TestTrait {
386 const SPECIAL_CONST: u8;
389 fn random_method(&self);
391 pub struct TestStruct {}
392 impl TestTrait for TestStruct {
393 const SPECIAL_CONST: u8 = 42;
394 type HumbleType = ();
395 fn weird_function() {}
396 fn random_method(&self) {}
400 //- /main.rs crate:main deps:dep
402 dep::test_mod::TestStruct::wei$0
409 fn weird_function() (dep::test_mod::TestTrait) fn()
417 use dep::test_mod::TestTrait;
420 dep::test_mod::TestStruct::weird_function()$0
427 fn trait_const_fuzzy_completion() {
429 //- /lib.rs crate:dep
431 pub trait TestTrait {
432 const SPECIAL_CONST: u8;
435 fn random_method(&self);
437 pub struct TestStruct {}
438 impl TestTrait for TestStruct {
439 const SPECIAL_CONST: u8 = 42;
440 type HumbleType = ();
441 fn weird_function() {}
442 fn random_method(&self) {}
446 //- /main.rs crate:main deps:dep
448 dep::test_mod::TestStruct::spe$0
455 ct SPECIAL_CONST (dep::test_mod::TestTrait)
463 use dep::test_mod::TestTrait;
466 dep::test_mod::TestStruct::SPECIAL_CONST
473 fn trait_method_fuzzy_completion() {
475 //- /lib.rs crate:dep
477 pub trait TestTrait {
478 const SPECIAL_CONST: u8;
481 fn random_method(&self);
483 pub struct TestStruct {}
484 impl TestTrait for TestStruct {
485 const SPECIAL_CONST: u8 = 42;
486 type HumbleType = ();
487 fn weird_function() {}
488 fn random_method(&self) {}
492 //- /main.rs crate:main deps:dep
494 let test_struct = dep::test_mod::TestStruct {};
502 me random_method() (dep::test_mod::TestTrait) fn(&self)
510 use dep::test_mod::TestTrait;
513 let test_struct = dep::test_mod::TestStruct {};
514 test_struct.random_method()$0
521 fn no_trait_type_fuzzy_completion() {
524 //- /lib.rs crate:dep
526 pub trait TestTrait {
527 const SPECIAL_CONST: u8;
530 fn random_method(&self);
532 pub struct TestStruct {}
533 impl TestTrait for TestStruct {
534 const SPECIAL_CONST: u8 = 42;
535 type HumbleType = ();
536 fn weird_function() {}
537 fn random_method(&self) {}
541 //- /main.rs crate:main deps:dep
543 dep::test_mod::TestStruct::hum$0
551 fn does_not_propose_names_in_scope() {
554 //- /lib.rs crate:dep
556 pub trait TestTrait {
557 const SPECIAL_CONST: u8;
560 fn random_method(&self);
562 pub struct TestStruct {}
563 impl TestTrait for TestStruct {
564 const SPECIAL_CONST: u8 = 42;
565 type HumbleType = ();
566 fn weird_function() {}
567 fn random_method(&self) {}
571 //- /main.rs crate:main deps:dep
572 use dep::test_mod::TestStruct;
582 fn does_not_propose_traits_in_scope() {
585 //- /lib.rs crate:dep
587 pub trait TestTrait {
588 const SPECIAL_CONST: u8;
591 fn random_method(&self);
593 pub struct TestStruct {}
594 impl TestTrait for TestStruct {
595 const SPECIAL_CONST: u8 = 42;
596 type HumbleType = ();
597 fn weird_function() {}
598 fn random_method(&self) {}
602 //- /main.rs crate:main deps:dep
603 use dep::test_mod::{TestStruct, TestTrait};
605 dep::test_mod::TestStruct::hum$0
613 fn blanket_trait_impl_import() {
617 //- /lib.rs crate:dep
619 pub struct TestStruct {}
620 pub trait TestTrait {
621 fn another_function();
623 impl<T> TestTrait for T {
624 fn another_function() {}
628 //- /main.rs crate:main deps:dep
630 dep::test_mod::TestStruct::ano$0
634 use dep::test_mod::TestTrait;
637 dep::test_mod::TestStruct::another_function()$0
644 fn zero_input_deprecated_assoc_item_completion() {
647 //- /lib.rs crate:dep
650 pub trait TestTrait {
651 const SPECIAL_CONST: u8;
654 fn random_method(&self);
656 pub struct TestStruct {}
657 impl TestTrait for TestStruct {
658 const SPECIAL_CONST: u8 = 42;
659 type HumbleType = ();
660 fn weird_function() {}
661 fn random_method(&self) {}
665 //- /main.rs crate:main deps:dep
667 let test_struct = dep::test_mod::TestStruct {};
672 me random_method() (dep::test_mod::TestTrait) fn(&self) DEPRECATED
678 //- /lib.rs crate:dep
681 pub trait TestTrait {
682 const SPECIAL_CONST: u8;
685 fn random_method(&self);
687 pub struct TestStruct {}
688 impl TestTrait for TestStruct {
689 const SPECIAL_CONST: u8 = 42;
690 type HumbleType = ();
691 fn weird_function() {}
692 fn random_method(&self) {}
696 //- /main.rs crate:main deps:dep
698 dep::test_mod::TestStruct::$0
702 ct SPECIAL_CONST (dep::test_mod::TestTrait) DEPRECATED
703 fn weird_function() (dep::test_mod::TestTrait) fn() DEPRECATED
709 fn no_completions_in_use_statements() {
712 //- /lib.rs crate:dep
717 //- /main.rs crate:main deps:dep
727 fn prefix_config_usage() {
740 let mut config = TEST_CONFIG;
742 config.insert_use.prefix_kind = hir::PrefixKind::ByCrate;
743 check_edit_with_config(
754 use crate::foo::bar::{self, Item};
761 config.insert_use.prefix_kind = hir::PrefixKind::BySelf;
762 check_edit_with_config(
775 use self::foo::bar::Item;
782 config.insert_use.prefix_kind = hir::PrefixKind::Plain;
783 check_edit_with_config(
805 fn unresolved_qualifier() {
822 st foo::bar::baz::Item
847 fn unresolved_assoc_item_container() {
853 pub const TEST_ASSOC: usize = 3;
864 ct TEST_ASSOC (foo::Item)
878 pub const TEST_ASSOC: usize = 3;
889 fn unresolved_assoc_item_container_with_path() {
896 pub const TEST_ASSOC: usize = 3;
908 ct TEST_ASSOC (foo::bar::Item)
923 pub const TEST_ASSOC: usize = 3;
929 bar::Item::TEST_ASSOC
935 fn fuzzy_unresolved_path() {
943 pub const TEST_ASSOC: usize = 3;
956 fn unqualified_assoc_items_are_omitted() {
960 pub trait BaseTrait {
961 fn test_function() -> i32;
967 impl BaseTrait for Item1 {
968 fn test_function() -> i32 {
973 impl BaseTrait for Item2 {
974 fn test_function() -> i32 {
992 pub const TEST_CONST: usize = 3;
993 pub fn test_function() -> i32 {
1009 pub const TEST_CONST: usize = 3;
1010 pub fn test_function() -> i32 {
1020 fn test_function() (foo::test_function) fn() -> i32
1027 pub const TEST_CONST: usize = 3;
1028 pub fn test_function() -> i32 {
1041 fn no_fuzzy_during_fields_of_record_lit_syntax() {
1045 pub fn some_fn() -> i32 {
1053 let _ = Foo { so$0 };
1061 fn fuzzy_after_fields_of_record_lit_syntax() {
1065 pub fn some_fn() -> i32 {
1073 let _ = Foo { some_field: so$0 };
1077 fn some_fn() (m::some_fn) fn() -> i32
1083 fn no_flyimports_in_traits_and_impl_declarations() {
1087 pub fn some_fn() -> i32 {
1101 pub fn some_fn() -> i32 {
1116 pub fn some_fn() -> i32 {
1131 fn no_inherent_candidates_proposed() {
1135 pub trait DefDatabase {
1138 pub trait HirDatabase: DefDatabase {
1144 fn test(db: &dyn crate::baz::HirDatabase) {