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()
116 || ctx.expects_variant()
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.clone());
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(
134 &position_for_import(ctx, Some(import_assets.import_candidate()))?,
140 .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
143 !ctx.is_item_hidden(&import.item_to_import)
144 && !ctx.is_item_hidden(&import.original_item)
146 .sorted_by_key(|located_import| {
147 compute_fuzzy_completion_order_key(
148 &located_import.import_path,
149 &user_input_lowercased,
152 .filter_map(|import| {
153 render_resolution_with_import(
154 RenderContext::new(ctx),
155 ImportEdit { import, scope: import_scope.clone() },
162 pub(crate) fn position_for_import(
163 ctx: &CompletionContext,
164 import_candidate: Option<&ImportCandidate>,
165 ) -> Option<SyntaxNode> {
167 match import_candidate {
168 Some(ImportCandidate::Path(_)) => ctx.name_syntax.as_ref()?.syntax(),
169 Some(ImportCandidate::TraitAssocItem(_)) => ctx.path_qual()?.syntax(),
170 Some(ImportCandidate::TraitMethod(_)) => ctx.dot_receiver()?.syntax(),
171 None => return ctx.original_token.parent(),
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)?.original,
184 dot_receiver.syntax().clone(),
187 let fuzzy_name_length = fuzzy_name.len();
188 let assets_for_path = ImportAssets::for_fuzzy_path(
190 ctx.path_qual().cloned(),
196 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
197 && fuzzy_name_length < 2
199 cov_mark::hit!(ignore_short_input_for_path);
202 Some(assets_for_path)
207 pub(crate) fn compute_fuzzy_completion_order_key(
208 proposed_mod_path: &hir::ModPath,
209 user_input_lowercased: &str,
211 cov_mark::hit!(certain_fuzzy_order_test);
212 let import_name = match proposed_mod_path.segments().last() {
213 Some(name) => name.to_smol_str().to_lowercase(),
214 None => return usize::MAX,
216 match import_name.match_indices(user_input_lowercased).next() {
217 Some((first_matching_index, _)) => first_matching_index,