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 containing 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 precedes the input, it will be taken into account.
27 //! Currently, only the imports with their import path ending with the whole qualifier 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 than 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.autoimport.enable` flag.
90 //! Note that having this flag set to `true` does not guarantee that the feature is enabled: your client needs to have the corresponding
91 //! capability enabled.
93 use ide_db::helpers::{
94 import_assets::{ImportAssets, ImportCandidate},
95 insert_use::ImportScope,
97 use itertools::Itertools;
98 use syntax::{AstNode, SyntaxNode, T};
101 context::CompletionContext,
102 render::{render_resolution_with_import, RenderContext},
106 use super::Completions;
108 pub(crate) fn import_on_the_fly(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
109 if !ctx.config.enable_imports_on_the_fly {
113 || ctx.is_path_disallowed()
114 || ctx.expects_item()
115 || ctx.expects_assoc_item()
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_with_macros(
133 position_for_import(ctx, Some(import_assets.import_candidate()))?,
139 .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
142 !ctx.is_item_hidden(&import.item_to_import)
143 && !ctx.is_item_hidden(&import.original_item)
145 .sorted_by_key(|located_import| {
146 compute_fuzzy_completion_order_key(
147 &located_import.import_path,
148 &user_input_lowercased,
151 .filter_map(|import| {
152 render_resolution_with_import(
153 RenderContext::new(ctx),
154 ImportEdit { import, scope: import_scope.clone() },
161 pub(crate) fn position_for_import<'a>(
162 ctx: &'a CompletionContext,
163 import_candidate: Option<&ImportCandidate>,
164 ) -> Option<&'a SyntaxNode> {
165 Some(match import_candidate {
166 Some(ImportCandidate::Path(_)) => ctx.name_ref_syntax.as_ref()?.syntax(),
167 Some(ImportCandidate::TraitAssocItem(_)) => ctx.path_qual()?.syntax(),
168 Some(ImportCandidate::TraitMethod(_)) => ctx.dot_receiver()?.syntax(),
172 .map(|name_ref| name_ref.syntax())
173 .or_else(|| ctx.path_qual().map(|path| path.syntax()))
174 .or_else(|| ctx.dot_receiver().map(|expr| expr.syntax()))?,
178 fn import_assets(ctx: &CompletionContext, fuzzy_name: String) -> Option<ImportAssets> {
179 let current_module = ctx.scope.module()?;
180 if let Some(dot_receiver) = ctx.dot_receiver() {
181 ImportAssets::for_fuzzy_method_call(
183 ctx.sema.type_of_expr(dot_receiver)?.ty,
185 dot_receiver.syntax().clone(),
188 let fuzzy_name_length = fuzzy_name.len();
189 let approximate_node = match current_module.definition_source(ctx.db).value {
190 hir::ModuleSource::SourceFile(s) => s.syntax().clone(),
191 hir::ModuleSource::Module(m) => m.syntax().clone(),
192 hir::ModuleSource::BlockExpr(b) => b.syntax().clone(),
194 let assets_for_path = ImportAssets::for_fuzzy_path(
196 ctx.path_qual().cloned(),
202 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
203 && fuzzy_name_length < 2
205 cov_mark::hit!(ignore_short_input_for_path);
208 Some(assets_for_path)
213 fn compute_fuzzy_completion_order_key(
214 proposed_mod_path: &hir::ModPath,
215 user_input_lowercased: &str,
217 cov_mark::hit!(certain_fuzzy_order_test);
218 let import_name = match proposed_mod_path.segments().last() {
219 Some(name) => name.to_string().to_lowercase(),
220 None => return usize::MAX,
222 match import_name.match_indices(user_input_lowercased).next() {
223 Some((first_matching_index, _)) => first_matching_index,
230 use expect_test::{expect, Expect};
233 item::CompletionKind,
234 tests::{check_edit, check_edit_with_config, filtered_completion_list, TEST_CONFIG},
237 fn check(ra_fixture: &str, expect: Expect) {
238 let actual = filtered_completion_list(ra_fixture, CompletionKind::Magic);
239 expect.assert_eq(&actual);
243 fn function_fuzzy_completion() {
247 //- /lib.rs crate:dep
252 //- /main.rs crate:main deps:dep
268 fn macro_fuzzy_completion() {
270 "macro_with_curlies!",
272 //- /lib.rs crate:dep
273 /// Please call me as macro_with_curlies! {}
275 macro_rules! macro_with_curlies {
279 //- /main.rs crate:main deps:dep
285 use dep::macro_with_curlies;
288 macro_with_curlies! {$0}
295 fn struct_fuzzy_completion() {
299 //- /lib.rs crate:dep
300 pub struct FirstStruct;
301 pub mod some_module {
302 pub struct SecondStruct;
303 pub struct ThirdStruct;
306 //- /main.rs crate:main deps:dep
307 use dep::{FirstStruct, some_module::SecondStruct};
314 use dep::{FirstStruct, some_module::{SecondStruct, ThirdStruct}};
324 fn short_paths_are_ignored() {
325 cov_mark::check!(ignore_short_input_for_path);
329 //- /lib.rs crate:dep
330 pub struct FirstStruct;
331 pub mod some_module {
332 pub struct SecondStruct;
333 pub struct ThirdStruct;
336 //- /main.rs crate:main deps:dep
337 use dep::{FirstStruct, some_module::SecondStruct};
348 fn fuzzy_completions_come_in_specific_order() {
349 cov_mark::check!(certain_fuzzy_order_test);
352 //- /lib.rs crate:dep
353 pub struct FirstStruct;
354 pub mod some_module {
355 // already imported, omitted
356 pub struct SecondStruct;
357 // does not contain all letters from the query, omitted
358 pub struct UnrelatedOne;
359 // contains all letters from the query, but not in sequence, displayed last
360 pub struct ThiiiiiirdStruct;
361 // contains all letters from the query, but not in the beginning, displayed second
362 pub struct AfterThirdStruct;
363 // contains all letters from the query in the begginning, displayed first
364 pub struct ThirdStruct;
367 //- /main.rs crate:main deps:dep
368 use dep::{FirstStruct, some_module::SecondStruct};
375 st ThirdStruct (use dep::some_module::ThirdStruct)
376 st AfterThirdStruct (use dep::some_module::AfterThirdStruct)
377 st ThiiiiiirdStruct (use dep::some_module::ThiiiiiirdStruct)
383 fn trait_function_fuzzy_completion() {
385 //- /lib.rs crate:dep
387 pub trait TestTrait {
388 const SPECIAL_CONST: u8;
391 fn random_method(&self);
393 pub struct TestStruct {}
394 impl TestTrait for TestStruct {
395 const SPECIAL_CONST: u8 = 42;
396 type HumbleType = ();
397 fn weird_function() {}
398 fn random_method(&self) {}
402 //- /main.rs crate:main deps:dep
404 dep::test_mod::TestStruct::wei$0
411 fn weird_function() (use dep::test_mod::TestTrait) fn()
419 use dep::test_mod::TestTrait;
422 dep::test_mod::TestStruct::weird_function()$0
429 fn trait_const_fuzzy_completion() {
431 //- /lib.rs crate:dep
433 pub trait TestTrait {
434 const SPECIAL_CONST: u8;
437 fn random_method(&self);
439 pub struct TestStruct {}
440 impl TestTrait for TestStruct {
441 const SPECIAL_CONST: u8 = 42;
442 type HumbleType = ();
443 fn weird_function() {}
444 fn random_method(&self) {}
448 //- /main.rs crate:main deps:dep
450 dep::test_mod::TestStruct::spe$0
457 ct SPECIAL_CONST (use dep::test_mod::TestTrait)
465 use dep::test_mod::TestTrait;
468 dep::test_mod::TestStruct::SPECIAL_CONST
475 fn trait_method_fuzzy_completion() {
477 //- /lib.rs crate:dep
479 pub trait TestTrait {
480 const SPECIAL_CONST: u8;
483 fn random_method(&self);
485 pub struct TestStruct {}
486 impl TestTrait for TestStruct {
487 const SPECIAL_CONST: u8 = 42;
488 type HumbleType = ();
489 fn weird_function() {}
490 fn random_method(&self) {}
494 //- /main.rs crate:main deps:dep
496 let test_struct = dep::test_mod::TestStruct {};
504 me random_method() (use dep::test_mod::TestTrait) fn(&self)
512 use dep::test_mod::TestTrait;
515 let test_struct = dep::test_mod::TestStruct {};
516 test_struct.random_method()$0
523 fn no_trait_type_fuzzy_completion() {
526 //- /lib.rs crate:dep
528 pub trait TestTrait {
529 const SPECIAL_CONST: u8;
532 fn random_method(&self);
534 pub struct TestStruct {}
535 impl TestTrait for TestStruct {
536 const SPECIAL_CONST: u8 = 42;
537 type HumbleType = ();
538 fn weird_function() {}
539 fn random_method(&self) {}
543 //- /main.rs crate:main deps:dep
545 dep::test_mod::TestStruct::hum$0
553 fn does_not_propose_names_in_scope() {
556 //- /lib.rs crate:dep
558 pub trait TestTrait {
559 const SPECIAL_CONST: u8;
562 fn random_method(&self);
564 pub struct TestStruct {}
565 impl TestTrait for TestStruct {
566 const SPECIAL_CONST: u8 = 42;
567 type HumbleType = ();
568 fn weird_function() {}
569 fn random_method(&self) {}
573 //- /main.rs crate:main deps:dep
574 use dep::test_mod::TestStruct;
584 fn does_not_propose_traits_in_scope() {
587 //- /lib.rs crate:dep
589 pub trait TestTrait {
590 const SPECIAL_CONST: u8;
593 fn random_method(&self);
595 pub struct TestStruct {}
596 impl TestTrait for TestStruct {
597 const SPECIAL_CONST: u8 = 42;
598 type HumbleType = ();
599 fn weird_function() {}
600 fn random_method(&self) {}
604 //- /main.rs crate:main deps:dep
605 use dep::test_mod::{TestStruct, TestTrait};
607 dep::test_mod::TestStruct::hum$0
615 fn blanket_trait_impl_import() {
619 //- /lib.rs crate:dep
621 pub struct TestStruct {}
622 pub trait TestTrait {
623 fn another_function();
625 impl<T> TestTrait for T {
626 fn another_function() {}
630 //- /main.rs crate:main deps:dep
632 dep::test_mod::TestStruct::ano$0
636 use dep::test_mod::TestTrait;
639 dep::test_mod::TestStruct::another_function()$0
646 fn zero_input_deprecated_assoc_item_completion() {
649 //- /lib.rs crate:dep
652 pub trait TestTrait {
653 const SPECIAL_CONST: u8;
656 fn random_method(&self);
658 pub struct TestStruct {}
659 impl TestTrait for TestStruct {
660 const SPECIAL_CONST: u8 = 42;
661 type HumbleType = ();
662 fn weird_function() {}
663 fn random_method(&self) {}
667 //- /main.rs crate:main deps:dep
669 let test_struct = dep::test_mod::TestStruct {};
674 me random_method() (use dep::test_mod::TestTrait) fn(&self) DEPRECATED
680 //- /lib.rs crate:dep
683 pub trait TestTrait {
684 const SPECIAL_CONST: u8;
687 fn random_method(&self);
689 pub struct TestStruct {}
690 impl TestTrait for TestStruct {
691 const SPECIAL_CONST: u8 = 42;
692 type HumbleType = ();
693 fn weird_function() {}
694 fn random_method(&self) {}
698 //- /main.rs crate:main deps:dep
700 dep::test_mod::TestStruct::$0
704 ct SPECIAL_CONST (use dep::test_mod::TestTrait) DEPRECATED
705 fn weird_function() (use dep::test_mod::TestTrait) fn() DEPRECATED
711 fn no_completions_in_use_statements() {
714 //- /lib.rs crate:dep
719 //- /main.rs crate:main deps:dep
729 fn prefix_config_usage() {
742 let mut config = TEST_CONFIG;
744 config.insert_use.prefix_kind = hir::PrefixKind::ByCrate;
745 check_edit_with_config(
756 use crate::foo::bar::{self, Item};
763 config.insert_use.prefix_kind = hir::PrefixKind::BySelf;
764 check_edit_with_config(
777 use self::foo::bar::Item;
784 config.insert_use.prefix_kind = hir::PrefixKind::Plain;
785 check_edit_with_config(
807 fn unresolved_qualifier() {
824 st Item (use foo::bar::baz::Item)
849 fn unresolved_assoc_item_container() {
855 pub const TEST_ASSOC: usize = 3;
866 ct TEST_ASSOC (use foo::Item)
880 pub const TEST_ASSOC: usize = 3;
891 fn unresolved_assoc_item_container_with_path() {
898 pub const TEST_ASSOC: usize = 3;
910 ct TEST_ASSOC (use foo::bar::Item)
925 pub const TEST_ASSOC: usize = 3;
931 bar::Item::TEST_ASSOC
937 fn fuzzy_unresolved_path() {
945 pub const TEST_ASSOC: usize = 3;
958 fn unqualified_assoc_items_are_omitted() {
962 pub trait BaseTrait {
963 fn test_function() -> i32;
969 impl BaseTrait for Item1 {
970 fn test_function() -> i32 {
975 impl BaseTrait for Item2 {
976 fn test_function() -> i32 {
994 pub const TEST_CONST: usize = 3;
995 pub fn test_function() -> i32 {
1004 ct TEST_CONST (use foo::TEST_CONST)
1011 pub const TEST_CONST: usize = 3;
1012 pub fn test_function() -> i32 {
1021 ct TEST_CONST (use foo::TEST_CONST)
1022 fn test_function() (use foo::test_function) fn() -> i32
1029 pub const TEST_CONST: usize = 3;
1030 pub fn test_function() -> i32 {
1043 fn no_fuzzy_during_fields_of_record_lit_syntax() {
1047 pub fn some_fn() -> i32 {
1055 let _ = Foo { so$0 };
1063 fn fuzzy_after_fields_of_record_lit_syntax() {
1067 pub fn some_fn() -> i32 {
1075 let _ = Foo { some_field: so$0 };
1079 fn some_fn() (use m::some_fn) fn() -> i32
1085 fn no_flyimports_in_traits_and_impl_declarations() {
1089 pub fn some_fn() -> i32 {
1103 pub fn some_fn() -> i32 {
1118 pub fn some_fn() -> i32 {
1133 fn no_inherent_candidates_proposed() {
1137 pub trait DefDatabase {
1140 pub trait HirDatabase: DefDatabase {
1146 fn test(db: &dyn crate::baz::HirDatabase) {
1156 fn respects_doc_hidden() {
1159 //- /lib.rs crate:lib deps:dep
1164 //- /dep.rs crate:dep
1170 impl<T> Private for T {}
1176 //- /lib.rs crate:lib deps:dep
1181 //- /dep.rs crate:dep
1187 impl<T> Private for T {}