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.is_path_disallowed()
115 || ctx.expects_item()
116 || ctx.expects_assoc_item()
120 let potential_import_name = {
121 let token_kind = ctx.token.kind();
122 if matches!(token_kind, T![.] | T![::]) {
125 ctx.token.to_string()
129 let _p = profile::span("import_on_the_fly").detail(|| potential_import_name.to_string());
131 let user_input_lowercased = potential_import_name.to_lowercase();
132 let import_assets = import_assets(ctx, potential_import_name)?;
133 let import_scope = ImportScope::find_insert_use_container_with_macros(
134 position_for_import(ctx, Some(import_assets.import_candidate()))?,
140 .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
142 .sorted_by_key(|located_import| {
143 compute_fuzzy_completion_order_key(
144 &located_import.import_path,
145 &user_input_lowercased,
148 .filter_map(|import| {
149 render_resolution_with_import(
150 RenderContext::new(ctx),
151 ImportEdit { import, scope: import_scope.clone() },
158 pub(crate) fn position_for_import<'a>(
159 ctx: &'a CompletionContext,
160 import_candidate: Option<&ImportCandidate>,
161 ) -> Option<&'a SyntaxNode> {
162 Some(match import_candidate {
163 Some(ImportCandidate::Path(_)) => ctx.name_ref_syntax.as_ref()?.syntax(),
164 Some(ImportCandidate::TraitAssocItem(_)) => ctx.path_qual.as_ref()?.syntax(),
165 Some(ImportCandidate::TraitMethod(_)) => ctx.dot_receiver.as_ref()?.syntax(),
169 .map(|name_ref| name_ref.syntax())
170 .or_else(|| ctx.path_qual.as_ref().map(|path| path.syntax()))
171 .or_else(|| ctx.dot_receiver.as_ref().map(|expr| expr.syntax()))?,
175 fn import_assets(ctx: &CompletionContext, fuzzy_name: String) -> Option<ImportAssets> {
176 let current_module = ctx.scope.module()?;
177 if let Some(dot_receiver) = &ctx.dot_receiver {
178 ImportAssets::for_fuzzy_method_call(
180 ctx.sema.type_of_expr(dot_receiver)?,
182 dot_receiver.syntax().clone(),
185 let fuzzy_name_length = fuzzy_name.len();
186 let approximate_node = match current_module.definition_source(ctx.db).value {
187 hir::ModuleSource::SourceFile(s) => s.syntax().clone(),
188 hir::ModuleSource::Module(m) => m.syntax().clone(),
189 hir::ModuleSource::BlockExpr(b) => b.syntax().clone(),
191 let assets_for_path = ImportAssets::for_fuzzy_path(
193 ctx.path_qual.clone(),
199 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
200 && fuzzy_name_length < 2
202 cov_mark::hit!(ignore_short_input_for_path);
205 Some(assets_for_path)
210 fn compute_fuzzy_completion_order_key(
211 proposed_mod_path: &ModPath,
212 user_input_lowercased: &str,
214 cov_mark::hit!(certain_fuzzy_order_test);
215 let import_name = match proposed_mod_path.segments().last() {
216 Some(name) => name.to_string().to_lowercase(),
217 None => return usize::MAX,
219 match import_name.match_indices(user_input_lowercased).next() {
220 Some((first_matching_index, _)) => first_matching_index,
227 use expect_test::{expect, Expect};
230 item::CompletionKind,
231 test_utils::{check_edit, check_edit_with_config, completion_list, TEST_CONFIG},
234 fn check(ra_fixture: &str, expect: Expect) {
235 let actual = completion_list(ra_fixture, CompletionKind::Magic);
236 expect.assert_eq(&actual);
240 fn function_fuzzy_completion() {
244 //- /lib.rs crate:dep
249 //- /main.rs crate:main deps:dep
265 fn macro_fuzzy_completion() {
267 "macro_with_curlies!",
269 //- /lib.rs crate:dep
270 /// Please call me as macro_with_curlies! {}
272 macro_rules! macro_with_curlies {
276 //- /main.rs crate:main deps:dep
282 use dep::macro_with_curlies;
285 macro_with_curlies! {$0}
292 fn struct_fuzzy_completion() {
296 //- /lib.rs crate:dep
297 pub struct FirstStruct;
298 pub mod some_module {
299 pub struct SecondStruct;
300 pub struct ThirdStruct;
303 //- /main.rs crate:main deps:dep
304 use dep::{FirstStruct, some_module::SecondStruct};
311 use dep::{FirstStruct, some_module::{SecondStruct, ThirdStruct}};
321 fn short_paths_are_ignored() {
322 cov_mark::check!(ignore_short_input_for_path);
326 //- /lib.rs crate:dep
327 pub struct FirstStruct;
328 pub mod some_module {
329 pub struct SecondStruct;
330 pub struct ThirdStruct;
333 //- /main.rs crate:main deps:dep
334 use dep::{FirstStruct, some_module::SecondStruct};
345 fn fuzzy_completions_come_in_specific_order() {
346 cov_mark::check!(certain_fuzzy_order_test);
349 //- /lib.rs crate:dep
350 pub struct FirstStruct;
351 pub mod some_module {
352 // already imported, omitted
353 pub struct SecondStruct;
354 // does not contain all letters from the query, omitted
355 pub struct UnrelatedOne;
356 // contains all letters from the query, but not in sequence, displayed last
357 pub struct ThiiiiiirdStruct;
358 // contains all letters from the query, but not in the beginning, displayed second
359 pub struct AfterThirdStruct;
360 // contains all letters from the query in the begginning, displayed first
361 pub struct ThirdStruct;
364 //- /main.rs crate:main deps:dep
365 use dep::{FirstStruct, some_module::SecondStruct};
372 st dep::some_module::ThirdStruct
373 st dep::some_module::AfterThirdStruct
374 st dep::some_module::ThiiiiiirdStruct
380 fn trait_function_fuzzy_completion() {
382 //- /lib.rs crate:dep
384 pub trait TestTrait {
385 const SPECIAL_CONST: u8;
388 fn random_method(&self);
390 pub struct TestStruct {}
391 impl TestTrait for TestStruct {
392 const SPECIAL_CONST: u8 = 42;
393 type HumbleType = ();
394 fn weird_function() {}
395 fn random_method(&self) {}
399 //- /main.rs crate:main deps:dep
401 dep::test_mod::TestStruct::wei$0
408 fn weird_function() (dep::test_mod::TestTrait) fn()
416 use dep::test_mod::TestTrait;
419 dep::test_mod::TestStruct::weird_function()$0
426 fn trait_const_fuzzy_completion() {
428 //- /lib.rs crate:dep
430 pub trait TestTrait {
431 const SPECIAL_CONST: u8;
434 fn random_method(&self);
436 pub struct TestStruct {}
437 impl TestTrait for TestStruct {
438 const SPECIAL_CONST: u8 = 42;
439 type HumbleType = ();
440 fn weird_function() {}
441 fn random_method(&self) {}
445 //- /main.rs crate:main deps:dep
447 dep::test_mod::TestStruct::spe$0
454 ct SPECIAL_CONST (dep::test_mod::TestTrait)
462 use dep::test_mod::TestTrait;
465 dep::test_mod::TestStruct::SPECIAL_CONST
472 fn trait_method_fuzzy_completion() {
474 //- /lib.rs crate:dep
476 pub trait TestTrait {
477 const SPECIAL_CONST: u8;
480 fn random_method(&self);
482 pub struct TestStruct {}
483 impl TestTrait for TestStruct {
484 const SPECIAL_CONST: u8 = 42;
485 type HumbleType = ();
486 fn weird_function() {}
487 fn random_method(&self) {}
491 //- /main.rs crate:main deps:dep
493 let test_struct = dep::test_mod::TestStruct {};
501 me random_method() (dep::test_mod::TestTrait) fn(&self)
509 use dep::test_mod::TestTrait;
512 let test_struct = dep::test_mod::TestStruct {};
513 test_struct.random_method()$0
520 fn no_trait_type_fuzzy_completion() {
523 //- /lib.rs crate:dep
525 pub trait TestTrait {
526 const SPECIAL_CONST: u8;
529 fn random_method(&self);
531 pub struct TestStruct {}
532 impl TestTrait for TestStruct {
533 const SPECIAL_CONST: u8 = 42;
534 type HumbleType = ();
535 fn weird_function() {}
536 fn random_method(&self) {}
540 //- /main.rs crate:main deps:dep
542 dep::test_mod::TestStruct::hum$0
550 fn does_not_propose_names_in_scope() {
553 //- /lib.rs crate:dep
555 pub trait TestTrait {
556 const SPECIAL_CONST: u8;
559 fn random_method(&self);
561 pub struct TestStruct {}
562 impl TestTrait for TestStruct {
563 const SPECIAL_CONST: u8 = 42;
564 type HumbleType = ();
565 fn weird_function() {}
566 fn random_method(&self) {}
570 //- /main.rs crate:main deps:dep
571 use dep::test_mod::TestStruct;
581 fn does_not_propose_traits_in_scope() {
584 //- /lib.rs crate:dep
586 pub trait TestTrait {
587 const SPECIAL_CONST: u8;
590 fn random_method(&self);
592 pub struct TestStruct {}
593 impl TestTrait for TestStruct {
594 const SPECIAL_CONST: u8 = 42;
595 type HumbleType = ();
596 fn weird_function() {}
597 fn random_method(&self) {}
601 //- /main.rs crate:main deps:dep
602 use dep::test_mod::{TestStruct, TestTrait};
604 dep::test_mod::TestStruct::hum$0
612 fn blanket_trait_impl_import() {
616 //- /lib.rs crate:dep
618 pub struct TestStruct {}
619 pub trait TestTrait {
620 fn another_function();
622 impl<T> TestTrait for T {
623 fn another_function() {}
627 //- /main.rs crate:main deps:dep
629 dep::test_mod::TestStruct::ano$0
633 use dep::test_mod::TestTrait;
636 dep::test_mod::TestStruct::another_function()$0
643 fn zero_input_deprecated_assoc_item_completion() {
646 //- /lib.rs crate:dep
649 pub trait TestTrait {
650 const SPECIAL_CONST: u8;
653 fn random_method(&self);
655 pub struct TestStruct {}
656 impl TestTrait for TestStruct {
657 const SPECIAL_CONST: u8 = 42;
658 type HumbleType = ();
659 fn weird_function() {}
660 fn random_method(&self) {}
664 //- /main.rs crate:main deps:dep
666 let test_struct = dep::test_mod::TestStruct {};
671 me random_method() (dep::test_mod::TestTrait) fn(&self) DEPRECATED
677 //- /lib.rs crate:dep
680 pub trait TestTrait {
681 const SPECIAL_CONST: u8;
684 fn random_method(&self);
686 pub struct TestStruct {}
687 impl TestTrait for TestStruct {
688 const SPECIAL_CONST: u8 = 42;
689 type HumbleType = ();
690 fn weird_function() {}
691 fn random_method(&self) {}
695 //- /main.rs crate:main deps:dep
697 dep::test_mod::TestStruct::$0
701 ct SPECIAL_CONST (dep::test_mod::TestTrait) DEPRECATED
702 fn weird_function() (dep::test_mod::TestTrait) fn() DEPRECATED
708 fn no_completions_in_use_statements() {
711 //- /lib.rs crate:dep
716 //- /main.rs crate:main deps:dep
726 fn prefix_config_usage() {
739 let mut config = TEST_CONFIG;
741 config.insert_use.prefix_kind = hir::PrefixKind::ByCrate;
742 check_edit_with_config(
753 use crate::foo::bar::{self, Item};
760 config.insert_use.prefix_kind = hir::PrefixKind::BySelf;
761 check_edit_with_config(
774 use self::foo::bar::Item;
781 config.insert_use.prefix_kind = hir::PrefixKind::Plain;
782 check_edit_with_config(
804 fn unresolved_qualifier() {
821 st foo::bar::baz::Item
846 fn unresolved_assoc_item_container() {
852 pub const TEST_ASSOC: usize = 3;
863 ct TEST_ASSOC (foo::Item)
877 pub const TEST_ASSOC: usize = 3;
888 fn unresolved_assoc_item_container_with_path() {
895 pub const TEST_ASSOC: usize = 3;
907 ct TEST_ASSOC (foo::bar::Item)
922 pub const TEST_ASSOC: usize = 3;
928 bar::Item::TEST_ASSOC
934 fn fuzzy_unresolved_path() {
942 pub const TEST_ASSOC: usize = 3;
955 fn unqualified_assoc_items_are_omitted() {
959 pub trait BaseTrait {
960 fn test_function() -> i32;
966 impl BaseTrait for Item1 {
967 fn test_function() -> i32 {
972 impl BaseTrait for Item2 {
973 fn test_function() -> i32 {
991 pub const TEST_CONST: usize = 3;
992 pub fn test_function() -> i32 {
1008 pub const TEST_CONST: usize = 3;
1009 pub fn test_function() -> i32 {
1019 fn test_function() (foo::test_function) fn() -> i32
1026 pub const TEST_CONST: usize = 3;
1027 pub fn test_function() -> i32 {
1040 fn no_fuzzy_during_fields_of_record_lit_syntax() {
1044 pub fn some_fn() -> i32 {
1052 let _ = Foo { so$0 };
1060 fn fuzzy_after_fields_of_record_lit_syntax() {
1064 pub fn some_fn() -> i32 {
1072 let _ = Foo { some_field: so$0 };
1076 fn some_fn() (m::some_fn) fn() -> i32
1082 fn no_flyimports_in_traits_and_impl_declarations() {
1086 pub fn some_fn() -> i32 {
1100 pub fn some_fn() -> i32 {
1115 pub fn some_fn() -> i32 {
1130 fn no_inherent_candidates_proposed() {
1134 pub trait DefDatabase {
1137 pub trait HirDatabase: DefDatabase {
1143 fn test(db: &dyn crate::baz::HirDatabase) {