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_trait_parent
118 || ctx.has_impl_parent
122 let potential_import_name = {
123 let token_kind = ctx.token.kind();
124 if matches!(token_kind, T![.] | T![::]) {
127 ctx.token.to_string()
131 let _p = profile::span("import_on_the_fly").detail(|| potential_import_name.to_string());
133 let user_input_lowercased = potential_import_name.to_lowercase();
134 let import_assets = import_assets(ctx, potential_import_name)?;
135 let import_scope = ImportScope::find_insert_use_container(
136 position_for_import(ctx, Some(import_assets.import_candidate()))?,
142 .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
144 .sorted_by_key(|located_import| {
145 compute_fuzzy_completion_order_key(
146 &located_import.import_path,
147 &user_input_lowercased,
150 .filter_map(|import| {
151 render_resolution_with_import(
152 RenderContext::new(ctx),
153 ImportEdit { import, scope: import_scope.clone() },
160 pub(crate) fn position_for_import<'a>(
161 ctx: &'a CompletionContext,
162 import_candidate: Option<&ImportCandidate>,
163 ) -> Option<&'a SyntaxNode> {
164 Some(match import_candidate {
165 Some(ImportCandidate::Path(_)) => ctx.name_ref_syntax.as_ref()?.syntax(),
166 Some(ImportCandidate::TraitAssocItem(_)) => ctx.path_qual.as_ref()?.syntax(),
167 Some(ImportCandidate::TraitMethod(_)) => ctx.dot_receiver.as_ref()?.syntax(),
171 .map(|name_ref| name_ref.syntax())
172 .or_else(|| ctx.path_qual.as_ref().map(|path| path.syntax()))
173 .or_else(|| ctx.dot_receiver.as_ref().map(|expr| expr.syntax()))?,
177 fn import_assets(ctx: &CompletionContext, fuzzy_name: String) -> Option<ImportAssets> {
178 let current_module = ctx.scope.module()?;
179 if let Some(dot_receiver) = &ctx.dot_receiver {
180 ImportAssets::for_fuzzy_method_call(
182 ctx.sema.type_of_expr(dot_receiver)?,
184 dot_receiver.syntax().clone(),
187 let fuzzy_name_length = fuzzy_name.len();
188 let approximate_node = match current_module.definition_source(ctx.db).value {
189 hir::ModuleSource::SourceFile(s) => s.syntax().clone(),
190 hir::ModuleSource::Module(m) => m.syntax().clone(),
191 hir::ModuleSource::BlockExpr(b) => b.syntax().clone(),
193 let assets_for_path = ImportAssets::for_fuzzy_path(
195 ctx.path_qual.clone(),
201 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
202 && fuzzy_name_length < 2
204 cov_mark::hit!(ignore_short_input_for_path);
207 Some(assets_for_path)
212 fn compute_fuzzy_completion_order_key(
213 proposed_mod_path: &ModPath,
214 user_input_lowercased: &str,
216 cov_mark::hit!(certain_fuzzy_order_test);
217 let import_name = match proposed_mod_path.segments().last() {
218 Some(name) => name.to_string().to_lowercase(),
219 None => return usize::MAX,
221 match import_name.match_indices(user_input_lowercased).next() {
222 Some((first_matching_index, _)) => first_matching_index,
229 use expect_test::{expect, Expect};
232 item::CompletionKind,
233 test_utils::{check_edit, check_edit_with_config, completion_list, TEST_CONFIG},
236 fn check(ra_fixture: &str, expect: Expect) {
237 let actual = completion_list(ra_fixture, CompletionKind::Magic);
238 expect.assert_eq(&actual);
242 fn function_fuzzy_completion() {
246 //- /lib.rs crate:dep
251 //- /main.rs crate:main deps:dep
267 fn macro_fuzzy_completion() {
269 "macro_with_curlies!",
271 //- /lib.rs crate:dep
272 /// Please call me as macro_with_curlies! {}
274 macro_rules! macro_with_curlies {
278 //- /main.rs crate:main deps:dep
284 use dep::macro_with_curlies;
287 macro_with_curlies! {$0}
294 fn struct_fuzzy_completion() {
298 //- /lib.rs crate:dep
299 pub struct FirstStruct;
300 pub mod some_module {
301 pub struct SecondStruct;
302 pub struct ThirdStruct;
305 //- /main.rs crate:main deps:dep
306 use dep::{FirstStruct, some_module::SecondStruct};
313 use dep::{FirstStruct, some_module::{SecondStruct, ThirdStruct}};
323 fn short_paths_are_ignored() {
324 cov_mark::check!(ignore_short_input_for_path);
328 //- /lib.rs crate:dep
329 pub struct FirstStruct;
330 pub mod some_module {
331 pub struct SecondStruct;
332 pub struct ThirdStruct;
335 //- /main.rs crate:main deps:dep
336 use dep::{FirstStruct, some_module::SecondStruct};
347 fn fuzzy_completions_come_in_specific_order() {
348 cov_mark::check!(certain_fuzzy_order_test);
351 //- /lib.rs crate:dep
352 pub struct FirstStruct;
353 pub mod some_module {
354 // already imported, omitted
355 pub struct SecondStruct;
356 // does not contain all letters from the query, omitted
357 pub struct UnrelatedOne;
358 // contains all letters from the query, but not in sequence, displayed last
359 pub struct ThiiiiiirdStruct;
360 // contains all letters from the query, but not in the beginning, displayed second
361 pub struct AfterThirdStruct;
362 // contains all letters from the query in the begginning, displayed first
363 pub struct ThirdStruct;
366 //- /main.rs crate:main deps:dep
367 use dep::{FirstStruct, some_module::SecondStruct};
374 st dep::some_module::ThirdStruct
375 st dep::some_module::AfterThirdStruct
376 st dep::some_module::ThiiiiiirdStruct
382 fn trait_function_fuzzy_completion() {
384 //- /lib.rs crate:dep
386 pub trait TestTrait {
387 const SPECIAL_CONST: u8;
390 fn random_method(&self);
392 pub struct TestStruct {}
393 impl TestTrait for TestStruct {
394 const SPECIAL_CONST: u8 = 42;
395 type HumbleType = ();
396 fn weird_function() {}
397 fn random_method(&self) {}
401 //- /main.rs crate:main deps:dep
403 dep::test_mod::TestStruct::wei$0
410 fn weird_function() (dep::test_mod::TestTrait) fn()
418 use dep::test_mod::TestTrait;
421 dep::test_mod::TestStruct::weird_function()$0
428 fn trait_const_fuzzy_completion() {
430 //- /lib.rs crate:dep
432 pub trait TestTrait {
433 const SPECIAL_CONST: u8;
436 fn random_method(&self);
438 pub struct TestStruct {}
439 impl TestTrait for TestStruct {
440 const SPECIAL_CONST: u8 = 42;
441 type HumbleType = ();
442 fn weird_function() {}
443 fn random_method(&self) {}
447 //- /main.rs crate:main deps:dep
449 dep::test_mod::TestStruct::spe$0
456 ct SPECIAL_CONST (dep::test_mod::TestTrait)
464 use dep::test_mod::TestTrait;
467 dep::test_mod::TestStruct::SPECIAL_CONST
474 fn trait_method_fuzzy_completion() {
476 //- /lib.rs crate:dep
478 pub trait TestTrait {
479 const SPECIAL_CONST: u8;
482 fn random_method(&self);
484 pub struct TestStruct {}
485 impl TestTrait for TestStruct {
486 const SPECIAL_CONST: u8 = 42;
487 type HumbleType = ();
488 fn weird_function() {}
489 fn random_method(&self) {}
493 //- /main.rs crate:main deps:dep
495 let test_struct = dep::test_mod::TestStruct {};
503 me random_method() (dep::test_mod::TestTrait) fn(&self)
511 use dep::test_mod::TestTrait;
514 let test_struct = dep::test_mod::TestStruct {};
515 test_struct.random_method()$0
522 fn no_trait_type_fuzzy_completion() {
525 //- /lib.rs crate:dep
527 pub trait TestTrait {
528 const SPECIAL_CONST: u8;
531 fn random_method(&self);
533 pub struct TestStruct {}
534 impl TestTrait for TestStruct {
535 const SPECIAL_CONST: u8 = 42;
536 type HumbleType = ();
537 fn weird_function() {}
538 fn random_method(&self) {}
542 //- /main.rs crate:main deps:dep
544 dep::test_mod::TestStruct::hum$0
552 fn does_not_propose_names_in_scope() {
555 //- /lib.rs crate:dep
557 pub trait TestTrait {
558 const SPECIAL_CONST: u8;
561 fn random_method(&self);
563 pub struct TestStruct {}
564 impl TestTrait for TestStruct {
565 const SPECIAL_CONST: u8 = 42;
566 type HumbleType = ();
567 fn weird_function() {}
568 fn random_method(&self) {}
572 //- /main.rs crate:main deps:dep
573 use dep::test_mod::TestStruct;
583 fn does_not_propose_traits_in_scope() {
586 //- /lib.rs crate:dep
588 pub trait TestTrait {
589 const SPECIAL_CONST: u8;
592 fn random_method(&self);
594 pub struct TestStruct {}
595 impl TestTrait for TestStruct {
596 const SPECIAL_CONST: u8 = 42;
597 type HumbleType = ();
598 fn weird_function() {}
599 fn random_method(&self) {}
603 //- /main.rs crate:main deps:dep
604 use dep::test_mod::{TestStruct, TestTrait};
606 dep::test_mod::TestStruct::hum$0
614 fn blanket_trait_impl_import() {
618 //- /lib.rs crate:dep
620 pub struct TestStruct {}
621 pub trait TestTrait {
622 fn another_function();
624 impl<T> TestTrait for T {
625 fn another_function() {}
629 //- /main.rs crate:main deps:dep
631 dep::test_mod::TestStruct::ano$0
635 use dep::test_mod::TestTrait;
638 dep::test_mod::TestStruct::another_function()$0
645 fn zero_input_deprecated_assoc_item_completion() {
648 //- /lib.rs crate:dep
651 pub trait TestTrait {
652 const SPECIAL_CONST: u8;
655 fn random_method(&self);
657 pub struct TestStruct {}
658 impl TestTrait for TestStruct {
659 const SPECIAL_CONST: u8 = 42;
660 type HumbleType = ();
661 fn weird_function() {}
662 fn random_method(&self) {}
666 //- /main.rs crate:main deps:dep
668 let test_struct = dep::test_mod::TestStruct {};
673 me random_method() (dep::test_mod::TestTrait) fn(&self) DEPRECATED
679 //- /lib.rs crate:dep
682 pub trait TestTrait {
683 const SPECIAL_CONST: u8;
686 fn random_method(&self);
688 pub struct TestStruct {}
689 impl TestTrait for TestStruct {
690 const SPECIAL_CONST: u8 = 42;
691 type HumbleType = ();
692 fn weird_function() {}
693 fn random_method(&self) {}
697 //- /main.rs crate:main deps:dep
699 dep::test_mod::TestStruct::$0
703 ct SPECIAL_CONST (dep::test_mod::TestTrait) DEPRECATED
704 fn weird_function() (dep::test_mod::TestTrait) fn() DEPRECATED
710 fn no_completions_in_use_statements() {
713 //- /lib.rs crate:dep
718 //- /main.rs crate:main deps:dep
728 fn prefix_config_usage() {
741 let mut config = TEST_CONFIG;
743 config.insert_use.prefix_kind = hir::PrefixKind::ByCrate;
744 check_edit_with_config(
755 use crate::foo::bar::{self, Item};
762 config.insert_use.prefix_kind = hir::PrefixKind::BySelf;
763 check_edit_with_config(
776 use self::foo::bar::Item;
783 config.insert_use.prefix_kind = hir::PrefixKind::Plain;
784 check_edit_with_config(
806 fn unresolved_qualifier() {
823 st foo::bar::baz::Item
848 fn unresolved_assoc_item_container() {
854 pub const TEST_ASSOC: usize = 3;
865 ct TEST_ASSOC (foo::Item)
879 pub const TEST_ASSOC: usize = 3;
890 fn unresolved_assoc_item_container_with_path() {
897 pub const TEST_ASSOC: usize = 3;
909 ct TEST_ASSOC (foo::bar::Item)
924 pub const TEST_ASSOC: usize = 3;
930 bar::Item::TEST_ASSOC
936 fn fuzzy_unresolved_path() {
944 pub const TEST_ASSOC: usize = 3;
957 fn unqualified_assoc_items_are_omitted() {
961 pub trait BaseTrait {
962 fn test_function() -> i32;
968 impl BaseTrait for Item1 {
969 fn test_function() -> i32 {
974 impl BaseTrait for Item2 {
975 fn test_function() -> i32 {
993 pub const TEST_CONST: usize = 3;
994 pub fn test_function() -> i32 {
1010 pub const TEST_CONST: usize = 3;
1011 pub fn test_function() -> i32 {
1021 fn test_function() (foo::test_function) fn() -> i32
1028 pub const TEST_CONST: usize = 3;
1029 pub fn test_function() -> i32 {
1042 fn no_fuzzy_during_fields_of_record_lit_syntax() {
1046 pub fn some_fn() -> i32 {
1054 let _ = Foo { so$0 };
1062 fn fuzzy_after_fields_of_record_lit_syntax() {
1066 pub fn some_fn() -> i32 {
1074 let _ = Foo { some_field: so$0 };
1078 fn some_fn() (m::some_fn) fn() -> i32
1084 fn no_flyimports_in_traits_and_impl_declarations() {
1088 pub fn some_fn() -> i32 {
1102 pub fn some_fn() -> i32 {
1117 pub fn some_fn() -> i32 {