1 //! See [`import_on_the_fly`].
3 import_assets::{ImportAssets, ImportCandidate},
4 insert_use::ImportScope,
6 use itertools::Itertools;
7 use syntax::{AstNode, SyntaxNode, T};
10 context::CompletionContext,
11 render::{render_resolution_with_import, RenderContext},
15 use super::Completions;
17 // Feature: Completion With Autoimport
19 // When completing names in the current scope, proposes additional imports from other modules or crates,
20 // if they can be qualified in the scope, and their name contains all symbols from the completion input.
22 // To be considered applicable, the name must contain all input symbols in the given order, not necessarily adjacent.
23 // If any input symbol is not lowercased, the name must contain all symbols in exact case; otherwise the containing is checked case-insensitively.
29 // # pub mod std { pub mod marker { pub struct PhantomData { } } }
33 // use std::marker::PhantomData;
38 // # pub mod std { pub mod marker { pub struct PhantomData { } } }
41 // Also completes associated items, that require trait imports.
42 // If any unresolved and/or partially-qualified path precedes the input, it will be taken into account.
43 // Currently, only the imports with their import path ending with the whole qualifier will be proposed
44 // (no fuzzy matching for qualifier).
52 // pub const TEST_ASSOC: usize = 3;
58 // bar::Item::TEST_A$0
70 // pub const TEST_ASSOC: usize = 3;
76 // bar::Item::TEST_ASSOC
80 // 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,
81 // no imports will be proposed.
83 // .Fuzzy search details
85 // To avoid an excessive amount of the results returned, completion input is checked for inclusion in the names only
86 // (i.e. in `HashMap` in the `std::collections::HashMap` path).
87 // For the same reasons, avoids searching for any path imports for inputs with their length less than 2 symbols
88 // (but shows all associated items for any input length).
90 // .Import configuration
92 // It is possible to configure how use-trees are merged with the `importMergeBehavior` setting.
93 // Mimics the corresponding behavior of the `Auto Import` feature.
95 // .LSP and performance implications
97 // The feature is enabled only if the LSP client supports LSP protocol version 3.16+ and reports the `additionalTextEdits`
98 // (case-sensitive) resolve client capability in its client capabilities.
99 // This way the server is able to defer the costly computations, doing them for a selected completion item only.
100 // For clients with no such support, all edits have to be calculated on the completion request, including the fuzzy search completion ones,
101 // which might be slow ergo the feature is automatically disabled.
105 // The feature can be forcefully turned off in the settings with the `rust-analyzer.completion.autoimport.enable` flag.
106 // Note that having this flag set to `true` does not guarantee that the feature is enabled: your client needs to have the corresponding
107 // capability enabled.
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_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)?.original,
185 dot_receiver.syntax().clone(),
188 let fuzzy_name_length = fuzzy_name.len();
189 let assets_for_path = ImportAssets::for_fuzzy_path(
191 ctx.path_qual().cloned(),
197 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
198 && fuzzy_name_length < 2
200 cov_mark::hit!(ignore_short_input_for_path);
203 Some(assets_for_path)
208 fn compute_fuzzy_completion_order_key(
209 proposed_mod_path: &hir::ModPath,
210 user_input_lowercased: &str,
212 cov_mark::hit!(certain_fuzzy_order_test);
213 let import_name = match proposed_mod_path.segments().last() {
214 Some(name) => name.to_string().to_lowercase(),
215 None => return usize::MAX,
217 match import_name.match_indices(user_input_lowercased).next() {
218 Some((first_matching_index, _)) => first_matching_index,
225 use expect_test::{expect, Expect};
228 item::CompletionKind,
229 tests::{check_edit, check_edit_with_config, filtered_completion_list, TEST_CONFIG},
232 fn check(ra_fixture: &str, expect: Expect) {
233 let actual = filtered_completion_list(ra_fixture, CompletionKind::Magic);
234 expect.assert_eq(&actual);
238 fn function_fuzzy_completion() {
242 //- /lib.rs crate:dep
247 //- /main.rs crate:main deps:dep
263 fn macro_fuzzy_completion() {
265 "macro_with_curlies!",
267 //- /lib.rs crate:dep
268 /// Please call me as macro_with_curlies! {}
270 macro_rules! macro_with_curlies {
274 //- /main.rs crate:main deps:dep
280 use dep::macro_with_curlies;
283 macro_with_curlies! {$0}
290 fn struct_fuzzy_completion() {
294 //- /lib.rs crate:dep
295 pub struct FirstStruct;
296 pub mod some_module {
297 pub struct SecondStruct;
298 pub struct ThirdStruct;
301 //- /main.rs crate:main deps:dep
302 use dep::{FirstStruct, some_module::SecondStruct};
309 use dep::{FirstStruct, some_module::{SecondStruct, ThirdStruct}};
319 fn short_paths_are_ignored() {
320 cov_mark::check!(ignore_short_input_for_path);
324 //- /lib.rs crate:dep
325 pub struct FirstStruct;
326 pub mod some_module {
327 pub struct SecondStruct;
328 pub struct ThirdStruct;
331 //- /main.rs crate:main deps:dep
332 use dep::{FirstStruct, some_module::SecondStruct};
343 fn fuzzy_completions_come_in_specific_order() {
344 cov_mark::check!(certain_fuzzy_order_test);
347 //- /lib.rs crate:dep
348 pub struct FirstStruct;
349 pub mod some_module {
350 // already imported, omitted
351 pub struct SecondStruct;
352 // does not contain all letters from the query, omitted
353 pub struct UnrelatedOne;
354 // contains all letters from the query, but not in sequence, displayed last
355 pub struct ThiiiiiirdStruct;
356 // contains all letters from the query, but not in the beginning, displayed second
357 pub struct AfterThirdStruct;
358 // contains all letters from the query in the begginning, displayed first
359 pub struct ThirdStruct;
362 //- /main.rs crate:main deps:dep
363 use dep::{FirstStruct, some_module::SecondStruct};
370 st ThirdStruct (use dep::some_module::ThirdStruct)
371 st AfterThirdStruct (use dep::some_module::AfterThirdStruct)
372 st ThiiiiiirdStruct (use dep::some_module::ThiiiiiirdStruct)
378 fn trait_function_fuzzy_completion() {
380 //- /lib.rs crate:dep
382 pub trait TestTrait {
383 const SPECIAL_CONST: u8;
386 fn random_method(&self);
388 pub struct TestStruct {}
389 impl TestTrait for TestStruct {
390 const SPECIAL_CONST: u8 = 42;
391 type HumbleType = ();
392 fn weird_function() {}
393 fn random_method(&self) {}
397 //- /main.rs crate:main deps:dep
399 dep::test_mod::TestStruct::wei$0
406 fn weird_function() (use dep::test_mod::TestTrait) fn()
414 use dep::test_mod::TestTrait;
417 dep::test_mod::TestStruct::weird_function()$0
424 fn trait_const_fuzzy_completion() {
426 //- /lib.rs crate:dep
428 pub trait TestTrait {
429 const SPECIAL_CONST: u8;
432 fn random_method(&self);
434 pub struct TestStruct {}
435 impl TestTrait for TestStruct {
436 const SPECIAL_CONST: u8 = 42;
437 type HumbleType = ();
438 fn weird_function() {}
439 fn random_method(&self) {}
443 //- /main.rs crate:main deps:dep
445 dep::test_mod::TestStruct::spe$0
452 ct SPECIAL_CONST (use dep::test_mod::TestTrait)
460 use dep::test_mod::TestTrait;
463 dep::test_mod::TestStruct::SPECIAL_CONST
470 fn trait_method_fuzzy_completion() {
472 //- /lib.rs crate:dep
474 pub trait TestTrait {
475 const SPECIAL_CONST: u8;
478 fn random_method(&self);
480 pub struct TestStruct {}
481 impl TestTrait for TestStruct {
482 const SPECIAL_CONST: u8 = 42;
483 type HumbleType = ();
484 fn weird_function() {}
485 fn random_method(&self) {}
489 //- /main.rs crate:main deps:dep
491 let test_struct = dep::test_mod::TestStruct {};
499 me random_method() (use dep::test_mod::TestTrait) fn(&self)
507 use dep::test_mod::TestTrait;
510 let test_struct = dep::test_mod::TestStruct {};
511 test_struct.random_method()$0
518 fn no_trait_type_fuzzy_completion() {
521 //- /lib.rs crate:dep
523 pub trait TestTrait {
524 const SPECIAL_CONST: u8;
527 fn random_method(&self);
529 pub struct TestStruct {}
530 impl TestTrait for TestStruct {
531 const SPECIAL_CONST: u8 = 42;
532 type HumbleType = ();
533 fn weird_function() {}
534 fn random_method(&self) {}
538 //- /main.rs crate:main deps:dep
540 dep::test_mod::TestStruct::hum$0
548 fn does_not_propose_names_in_scope() {
551 //- /lib.rs crate:dep
553 pub trait TestTrait {
554 const SPECIAL_CONST: u8;
557 fn random_method(&self);
559 pub struct TestStruct {}
560 impl TestTrait for TestStruct {
561 const SPECIAL_CONST: u8 = 42;
562 type HumbleType = ();
563 fn weird_function() {}
564 fn random_method(&self) {}
568 //- /main.rs crate:main deps:dep
569 use dep::test_mod::TestStruct;
579 fn does_not_propose_traits_in_scope() {
582 //- /lib.rs crate:dep
584 pub trait TestTrait {
585 const SPECIAL_CONST: u8;
588 fn random_method(&self);
590 pub struct TestStruct {}
591 impl TestTrait for TestStruct {
592 const SPECIAL_CONST: u8 = 42;
593 type HumbleType = ();
594 fn weird_function() {}
595 fn random_method(&self) {}
599 //- /main.rs crate:main deps:dep
600 use dep::test_mod::{TestStruct, TestTrait};
602 dep::test_mod::TestStruct::hum$0
610 fn blanket_trait_impl_import() {
614 //- /lib.rs crate:dep
616 pub struct TestStruct {}
617 pub trait TestTrait {
618 fn another_function();
620 impl<T> TestTrait for T {
621 fn another_function() {}
625 //- /main.rs crate:main deps:dep
627 dep::test_mod::TestStruct::ano$0
631 use dep::test_mod::TestTrait;
634 dep::test_mod::TestStruct::another_function()$0
641 fn zero_input_deprecated_assoc_item_completion() {
644 //- /lib.rs crate:dep
647 pub trait TestTrait {
648 const SPECIAL_CONST: u8;
651 fn random_method(&self);
653 pub struct TestStruct {}
654 impl TestTrait for TestStruct {
655 const SPECIAL_CONST: u8 = 42;
656 type HumbleType = ();
657 fn weird_function() {}
658 fn random_method(&self) {}
662 //- /main.rs crate:main deps:dep
664 let test_struct = dep::test_mod::TestStruct {};
669 me random_method() (use dep::test_mod::TestTrait) fn(&self) DEPRECATED
675 //- /lib.rs crate:dep
678 pub trait TestTrait {
679 const SPECIAL_CONST: u8;
682 fn random_method(&self);
684 pub struct TestStruct {}
685 impl TestTrait for TestStruct {
686 const SPECIAL_CONST: u8 = 42;
687 type HumbleType = ();
688 fn weird_function() {}
689 fn random_method(&self) {}
693 //- /main.rs crate:main deps:dep
695 dep::test_mod::TestStruct::$0
699 fn weird_function() (use dep::test_mod::TestTrait) fn() DEPRECATED
700 ct SPECIAL_CONST (use dep::test_mod::TestTrait) DEPRECATED
706 fn no_completions_in_use_statements() {
709 //- /lib.rs crate:dep
714 //- /main.rs crate:main deps:dep
724 fn prefix_config_usage() {
737 let mut config = TEST_CONFIG;
739 config.insert_use.prefix_kind = hir::PrefixKind::ByCrate;
740 check_edit_with_config(
751 use crate::foo::bar::{self, Item};
758 config.insert_use.prefix_kind = hir::PrefixKind::BySelf;
759 check_edit_with_config(
772 use self::foo::bar::Item;
779 config.insert_use.prefix_kind = hir::PrefixKind::Plain;
780 check_edit_with_config(
802 fn unresolved_qualifier() {
819 st Item (use foo::bar::baz::Item)
844 fn unresolved_assoc_item_container() {
850 pub const TEST_ASSOC: usize = 3;
861 ct TEST_ASSOC (use foo::Item)
875 pub const TEST_ASSOC: usize = 3;
886 fn unresolved_assoc_item_container_with_path() {
893 pub const TEST_ASSOC: usize = 3;
905 ct TEST_ASSOC (use foo::bar::Item)
920 pub const TEST_ASSOC: usize = 3;
926 bar::Item::TEST_ASSOC
932 fn fuzzy_unresolved_path() {
940 pub const TEST_ASSOC: usize = 3;
953 fn unqualified_assoc_items_are_omitted() {
957 pub trait BaseTrait {
958 fn test_function() -> i32;
964 impl BaseTrait for Item1 {
965 fn test_function() -> i32 {
970 impl BaseTrait for Item2 {
971 fn test_function() -> i32 {
989 pub const TEST_CONST: usize = 3;
990 pub fn test_function() -> i32 {
999 ct TEST_CONST (use foo::TEST_CONST)
1006 pub const TEST_CONST: usize = 3;
1007 pub fn test_function() -> i32 {
1016 ct TEST_CONST (use foo::TEST_CONST)
1017 fn test_function() (use foo::test_function) fn() -> i32
1024 pub const TEST_CONST: usize = 3;
1025 pub fn test_function() -> i32 {
1038 fn no_fuzzy_during_fields_of_record_lit_syntax() {
1042 pub fn some_fn() -> i32 {
1050 let _ = Foo { so$0 };
1058 fn fuzzy_after_fields_of_record_lit_syntax() {
1062 pub fn some_fn() -> i32 {
1070 let _ = Foo { some_field: so$0 };
1074 fn some_fn() (use m::some_fn) fn() -> i32
1080 fn no_flyimports_in_traits_and_impl_declarations() {
1084 pub fn some_fn() -> i32 {
1098 pub fn some_fn() -> i32 {
1113 pub fn some_fn() -> i32 {
1128 fn no_inherent_candidates_proposed() {
1132 pub trait DefDatabase {
1135 pub trait HirDatabase: DefDatabase {
1141 fn test(db: &dyn crate::baz::HirDatabase) {
1151 fn respects_doc_hidden() {
1154 //- /lib.rs crate:lib deps:dep
1159 //- /dep.rs crate:dep
1165 impl<T> Private for T {}
1171 //- /lib.rs crate:lib deps:dep
1176 //- /dep.rs crate:dep
1182 impl<T> Private for T {}
1189 fn regression_9760() {
1197 let struct_instance = Stru$0
1202 st Struct (use crate::Struct)
1208 fn flyimport_pattern() {
1219 st Struct (use module::Struct)