]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/flyimport.rs
Merge #10704
[rust.git] / crates / ide_completion / src / completions / flyimport.rs
1 //! See [`import_on_the_fly`].
2 use ide_db::helpers::{
3     import_assets::{ImportAssets, ImportCandidate},
4     insert_use::ImportScope,
5 };
6 use itertools::Itertools;
7 use syntax::{AstNode, SyntaxNode, T};
8
9 use crate::{
10     context::CompletionContext,
11     render::{render_resolution_with_import, RenderContext},
12     ImportEdit,
13 };
14
15 use super::Completions;
16
17 // Feature: Completion With Autoimport
18 //
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.
21 //
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.
24 //
25 // ```
26 // fn main() {
27 //     pda$0
28 // }
29 // # pub mod std { pub mod marker { pub struct PhantomData { } } }
30 // ```
31 // ->
32 // ```
33 // use std::marker::PhantomData;
34 //
35 // fn main() {
36 //     PhantomData
37 // }
38 // # pub mod std { pub mod marker { pub struct PhantomData { } } }
39 // ```
40 //
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).
45 //
46 // ```
47 // mod foo {
48 //     pub mod bar {
49 //         pub struct Item;
50 //
51 //         impl Item {
52 //             pub const TEST_ASSOC: usize = 3;
53 //         }
54 //     }
55 // }
56 //
57 // fn main() {
58 //     bar::Item::TEST_A$0
59 // }
60 // ```
61 // ->
62 // ```
63 // use foo::bar;
64 //
65 // mod foo {
66 //     pub mod bar {
67 //         pub struct Item;
68 //
69 //         impl Item {
70 //             pub const TEST_ASSOC: usize = 3;
71 //         }
72 //     }
73 // }
74 //
75 // fn main() {
76 //     bar::Item::TEST_ASSOC
77 // }
78 // ```
79 //
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.
82 //
83 // .Fuzzy search details
84 //
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).
89 //
90 // .Import configuration
91 //
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.
94 //
95 // .LSP and performance implications
96 //
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.
102 //
103 // .Feature toggle
104 //
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 {
110         return None;
111     }
112     if ctx.in_use_tree()
113         || ctx.is_path_disallowed()
114         || ctx.expects_item()
115         || ctx.expects_assoc_item()
116     {
117         return None;
118     }
119     let potential_import_name = {
120         let token_kind = ctx.token.kind();
121         if matches!(token_kind, T![.] | T![::]) {
122             String::new()
123         } else {
124             ctx.token.to_string()
125         }
126     };
127
128     let _p = profile::span("import_on_the_fly").detail(|| potential_import_name.clone());
129
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()))?,
134         &ctx.sema,
135     )?;
136
137     acc.add_all(
138         import_assets
139             .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
140             .into_iter()
141             .filter(|import| {
142                 !ctx.is_item_hidden(&import.item_to_import)
143                     && !ctx.is_item_hidden(&import.original_item)
144             })
145             .sorted_by_key(|located_import| {
146                 compute_fuzzy_completion_order_key(
147                     &located_import.import_path,
148                     &user_input_lowercased,
149                 )
150             })
151             .filter_map(|import| {
152                 render_resolution_with_import(
153                     RenderContext::new(ctx),
154                     ImportEdit { import, scope: import_scope.clone() },
155                 )
156             }),
157     );
158     Some(())
159 }
160
161 pub(crate) fn position_for_import(
162     ctx: &CompletionContext,
163     import_candidate: Option<&ImportCandidate>,
164 ) -> Option<SyntaxNode> {
165     Some(
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(),
171         }
172         .clone(),
173     )
174 }
175
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(
180             current_module,
181             ctx.sema.type_of_expr(dot_receiver)?.original,
182             fuzzy_name,
183             dot_receiver.syntax().clone(),
184         )
185     } else {
186         let fuzzy_name_length = fuzzy_name.len();
187         let assets_for_path = ImportAssets::for_fuzzy_path(
188             current_module,
189             ctx.path_qual().cloned(),
190             fuzzy_name,
191             &ctx.sema,
192             ctx.token.parent()?,
193         )?;
194
195         if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
196             && fuzzy_name_length < 2
197         {
198             cov_mark::hit!(ignore_short_input_for_path);
199             None
200         } else {
201             Some(assets_for_path)
202         }
203     }
204 }
205
206 pub(crate) fn compute_fuzzy_completion_order_key(
207     proposed_mod_path: &hir::ModPath,
208     user_input_lowercased: &str,
209 ) -> usize {
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,
214     };
215     match import_name.match_indices(user_input_lowercased).next() {
216         Some((first_matching_index, _)) => first_matching_index,
217         None => usize::MAX,
218     }
219 }