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.clone());
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(
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(
162 ctx: &CompletionContext,
163 import_candidate: Option<&ImportCandidate>,
164 ) -> Option<SyntaxNode> {
166 match import_candidate {
167 Some(ImportCandidate::Path(_)) => ctx.name_syntax.as_ref()?.syntax(),
168 Some(ImportCandidate::TraitAssocItem(_)) => ctx.path_qual()?.syntax(),
169 Some(ImportCandidate::TraitMethod(_)) => ctx.dot_receiver()?.syntax(),
170 None => return ctx.original_token.parent(),
176 fn import_assets(ctx: &CompletionContext, fuzzy_name: String) -> Option<ImportAssets> {
177 let current_module = ctx.scope.module()?;
178 if let Some(dot_receiver) = ctx.dot_receiver() {
179 ImportAssets::for_fuzzy_method_call(
181 ctx.sema.type_of_expr(dot_receiver)?.original,
183 dot_receiver.syntax().clone(),
186 let fuzzy_name_length = fuzzy_name.len();
187 let assets_for_path = ImportAssets::for_fuzzy_path(
189 ctx.path_qual().cloned(),
195 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
196 && fuzzy_name_length < 2
198 cov_mark::hit!(ignore_short_input_for_path);
201 Some(assets_for_path)
206 pub(crate) fn compute_fuzzy_completion_order_key(
207 proposed_mod_path: &hir::ModPath,
208 user_input_lowercased: &str,
210 cov_mark::hit!(certain_fuzzy_order_test);
211 let import_name = match proposed_mod_path.segments().last() {
212 Some(name) => name.to_smol_str().to_lowercase(),
213 None => return usize::MAX,
215 match import_name.match_indices(user_input_lowercased).next() {
216 Some((first_matching_index, _)) => first_matching_index,