1 //! See [`import_on_the_fly`].
4 import_assets::{ImportAssets, ImportCandidate, LocatedImport},
5 insert_use::ImportScope,
7 use itertools::Itertools;
8 use syntax::{AstNode, SyntaxNode, T};
11 context::{CompletionContext, PathKind},
12 render::{render_resolution_with_import, RenderContext},
16 use super::Completions;
18 // Feature: Completion With Autoimport
20 // When completing names in the current scope, proposes additional imports from other modules or crates,
21 // if they can be qualified in the scope, and their name contains all symbols from the completion input.
23 // To be considered applicable, the name must contain all input symbols in the given order, not necessarily adjacent.
24 // If any input symbol is not lowercased, the name must contain all symbols in exact case; otherwise the containing is checked case-insensitively.
30 // # pub mod std { pub mod marker { pub struct PhantomData { } } }
34 // use std::marker::PhantomData;
39 // # pub mod std { pub mod marker { pub struct PhantomData { } } }
42 // Also completes associated items, that require trait imports.
43 // If any unresolved and/or partially-qualified path precedes the input, it will be taken into account.
44 // Currently, only the imports with their import path ending with the whole qualifier will be proposed
45 // (no fuzzy matching for qualifier).
53 // pub const TEST_ASSOC: usize = 3;
59 // bar::Item::TEST_A$0
71 // pub const TEST_ASSOC: usize = 3;
77 // bar::Item::TEST_ASSOC
81 // 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,
82 // no imports will be proposed.
84 // .Fuzzy search details
86 // To avoid an excessive amount of the results returned, completion input is checked for inclusion in the names only
87 // (i.e. in `HashMap` in the `std::collections::HashMap` path).
88 // For the same reasons, avoids searching for any path imports for inputs with their length less than 2 symbols
89 // (but shows all associated items for any input length).
91 // .Import configuration
93 // It is possible to configure how use-trees are merged with the `importMergeBehavior` setting.
94 // Mimics the corresponding behavior of the `Auto Import` feature.
96 // .LSP and performance implications
98 // The feature is enabled only if the LSP client supports LSP protocol version 3.16+ and reports the `additionalTextEdits`
99 // (case-sensitive) resolve client capability in its client capabilities.
100 // This way the server is able to defer the costly computations, doing them for a selected completion item only.
101 // For clients with no such support, all edits have to be calculated on the completion request, including the fuzzy search completion ones,
102 // which might be slow ergo the feature is automatically disabled.
106 // The feature can be forcefully turned off in the settings with the `rust-analyzer.completion.autoimport.enable` flag.
107 // Note that having this flag set to `true` does not guarantee that the feature is enabled: your client needs to have the corresponding
108 // capability enabled.
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 matches!(ctx.path_kind(), Some(PathKind::Vis { .. } | PathKind::Use))
114 || ctx.is_path_disallowed()
115 || ctx.expects_item()
116 || ctx.expects_assoc_item()
117 || ctx.expects_variant()
121 // FIXME: This should be encoded in a different way
122 if ctx.pattern_ctx.is_none() && ctx.path_context.is_none() && !ctx.has_dot_receiver() {
123 // completion inside `ast::Name` of a item declaration
126 let potential_import_name = {
127 let token_kind = ctx.token.kind();
128 if matches!(token_kind, T![.] | T![::]) {
131 ctx.token.to_string()
135 let _p = profile::span("import_on_the_fly").detail(|| potential_import_name.clone());
137 let user_input_lowercased = potential_import_name.to_lowercase();
138 let import_assets = import_assets(ctx, potential_import_name)?;
139 let import_scope = ImportScope::find_insert_use_container(
140 &position_for_import(ctx, Some(import_assets.import_candidate()))?,
144 let ns_filter = |import: &LocatedImport| {
145 let kind = match ctx.path_kind() {
148 return match import.original_item {
149 ItemInNs::Macros(mac) => mac.is_fn_like(),
154 match (kind, import.original_item) {
155 // Aren't handled in flyimport
156 (PathKind::Vis { .. } | PathKind::Use, _) => false,
157 // modules are always fair game
158 (_, ItemInNs::Types(hir::ModuleDef::Module(_))) => true,
159 // and so are macros(except for attributes)
161 PathKind::Expr | PathKind::Type | PathKind::Mac | PathKind::Pat,
162 ItemInNs::Macros(mac),
163 ) => mac.is_fn_like(),
164 (PathKind::Mac, _) => true,
166 (PathKind::Expr, ItemInNs::Types(_) | ItemInNs::Values(_)) => true,
168 (PathKind::Pat, ItemInNs::Types(_)) => true,
169 (PathKind::Pat, ItemInNs::Values(def)) => matches!(def, hir::ModuleDef::Const(_)),
171 (PathKind::Type, ItemInNs::Types(_)) => true,
172 (PathKind::Type, ItemInNs::Values(_)) => false,
174 (PathKind::Attr, ItemInNs::Macros(mac)) => mac.is_attr(),
175 (PathKind::Attr, _) => false,
181 .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
185 !ctx.is_item_hidden(&import.item_to_import)
186 && !ctx.is_item_hidden(&import.original_item)
188 .sorted_by_key(|located_import| {
189 compute_fuzzy_completion_order_key(
190 &located_import.import_path,
191 &user_input_lowercased,
194 .filter_map(|import| {
195 render_resolution_with_import(
196 RenderContext::new(ctx),
197 ImportEdit { import, scope: import_scope.clone() },
204 pub(crate) fn position_for_import(
205 ctx: &CompletionContext,
206 import_candidate: Option<&ImportCandidate>,
207 ) -> Option<SyntaxNode> {
209 match import_candidate {
210 Some(ImportCandidate::Path(_)) => ctx.name_syntax.as_ref()?.syntax(),
211 Some(ImportCandidate::TraitAssocItem(_)) => ctx.path_qual()?.syntax(),
212 Some(ImportCandidate::TraitMethod(_)) => ctx.dot_receiver()?.syntax(),
213 None => return ctx.original_token.parent(),
219 fn import_assets(ctx: &CompletionContext, fuzzy_name: String) -> Option<ImportAssets> {
220 let current_module = ctx.scope.module()?;
221 if let Some(dot_receiver) = ctx.dot_receiver() {
222 ImportAssets::for_fuzzy_method_call(
224 ctx.sema.type_of_expr(dot_receiver)?.original,
226 dot_receiver.syntax().clone(),
229 let fuzzy_name_length = fuzzy_name.len();
230 let assets_for_path = ImportAssets::for_fuzzy_path(
232 ctx.path_qual().cloned(),
238 if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
239 && fuzzy_name_length < 2
241 cov_mark::hit!(ignore_short_input_for_path);
244 Some(assets_for_path)
249 pub(crate) fn compute_fuzzy_completion_order_key(
250 proposed_mod_path: &hir::ModPath,
251 user_input_lowercased: &str,
253 cov_mark::hit!(certain_fuzzy_order_test);
254 let import_name = match proposed_mod_path.segments().last() {
255 Some(name) => name.to_smol_str().to_lowercase(),
256 None => return usize::MAX,
258 match import_name.match_indices(user_input_lowercased).next() {
259 Some((first_matching_index, _)) => first_matching_index,