]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/flyimport.rs
fix: flyimport triggers on enum variant declarations
[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         || ctx.expects_variant()
117     {
118         return None;
119     }
120     let potential_import_name = {
121         let token_kind = ctx.token.kind();
122         if matches!(token_kind, T![.] | T![::]) {
123             String::new()
124         } else {
125             ctx.token.to_string()
126         }
127     };
128
129     let _p = profile::span("import_on_the_fly").detail(|| potential_import_name.clone());
130
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()))?,
135         &ctx.sema,
136     )?;
137
138     acc.add_all(
139         import_assets
140             .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
141             .into_iter()
142             .filter(|import| {
143                 !ctx.is_item_hidden(&import.item_to_import)
144                     && !ctx.is_item_hidden(&import.original_item)
145             })
146             .sorted_by_key(|located_import| {
147                 compute_fuzzy_completion_order_key(
148                     &located_import.import_path,
149                     &user_input_lowercased,
150                 )
151             })
152             .filter_map(|import| {
153                 render_resolution_with_import(
154                     RenderContext::new(ctx),
155                     ImportEdit { import, scope: import_scope.clone() },
156                 )
157             }),
158     );
159     Some(())
160 }
161
162 pub(crate) fn position_for_import(
163     ctx: &CompletionContext,
164     import_candidate: Option<&ImportCandidate>,
165 ) -> Option<SyntaxNode> {
166     Some(
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(),
172         }
173         .clone(),
174     )
175 }
176
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(
181             current_module,
182             ctx.sema.type_of_expr(dot_receiver)?.original,
183             fuzzy_name,
184             dot_receiver.syntax().clone(),
185         )
186     } else {
187         let fuzzy_name_length = fuzzy_name.len();
188         let assets_for_path = ImportAssets::for_fuzzy_path(
189             current_module,
190             ctx.path_qual().cloned(),
191             fuzzy_name,
192             &ctx.sema,
193             ctx.token.parent()?,
194         )?;
195
196         if matches!(assets_for_path.import_candidate(), ImportCandidate::Path(_))
197             && fuzzy_name_length < 2
198         {
199             cov_mark::hit!(ignore_short_input_for_path);
200             None
201         } else {
202             Some(assets_for_path)
203         }
204     }
205 }
206
207 pub(crate) fn compute_fuzzy_completion_order_key(
208     proposed_mod_path: &hir::ModPath,
209     user_input_lowercased: &str,
210 ) -> usize {
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,
215     };
216     match import_name.match_indices(user_input_lowercased).next() {
217         Some((first_matching_index, _)) => first_matching_index,
218         None => usize::MAX,
219     }
220 }