Skip to main content

ide_completion/completions/
flyimport.rs

1//! See [`import_on_the_fly`].
2use hir::{ItemInNs, ModuleDef};
3use ide_db::imports::{
4    import_assets::{ImportAssets, LocatedImport},
5    insert_use::ImportScope,
6};
7use itertools::Itertools;
8use syntax::{AstNode, SyntaxNode, ast};
9
10use crate::{
11    Completions,
12    config::AutoImportExclusionType,
13    context::{
14        CompletionContext, DotAccess, PathCompletionCtx, PathKind, PatternContext, Qualified,
15        TypeLocation,
16    },
17    render::{RenderContext, render_resolution_with_import, render_resolution_with_import_pat},
18};
19
20// Feature: Completion With Autoimport
21//
22// When completing names in the current scope, proposes additional imports from other modules or crates,
23// if they can be qualified in the scope, and their name contains all symbols from the completion input.
24//
25// To be considered applicable, the name must contain all input symbols in the given order, not necessarily adjacent.
26// If any input symbol is not lowercased, the name must contain all symbols in exact case; otherwise the containing is checked case-insensitively.
27//
28// ```
29// fn main() {
30//     pda$0
31// }
32// # pub mod std { pub mod marker { pub struct PhantomData { } } }
33// ```
34// ->
35// ```
36// use std::marker::PhantomData;
37//
38// fn main() {
39//     PhantomData
40// }
41// # pub mod std { pub mod marker { pub struct PhantomData { } } }
42// ```
43//
44// Also completes associated items, that require trait imports.
45// If any unresolved and/or partially-qualified path precedes the input, it will be taken into account.
46// Currently, only the imports with their import path ending with the whole qualifier will be proposed
47// (no fuzzy matching for qualifier).
48//
49// ```
50// mod foo {
51//     pub mod bar {
52//         pub struct Item;
53//
54//         impl Item {
55//             pub const TEST_ASSOC: usize = 3;
56//         }
57//     }
58// }
59//
60// fn main() {
61//     bar::Item::TEST_A$0
62// }
63// ```
64// ->
65// ```
66// use foo::bar;
67//
68// mod foo {
69//     pub mod bar {
70//         pub struct Item;
71//
72//         impl Item {
73//             pub const TEST_ASSOC: usize = 3;
74//         }
75//     }
76// }
77//
78// fn main() {
79//     bar::Item::TEST_ASSOC
80// }
81// ```
82//
83// 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,
84// no imports will be proposed.
85//
86// #### Fuzzy search details
87//
88// To avoid an excessive amount of the results returned, completion input is checked for inclusion in the names only
89// (i.e. in `HashMap` in the `std::collections::HashMap` path).
90// For the same reasons, avoids searching for any path imports for inputs with their length less than 2 symbols
91// (but shows all associated items for any input length).
92//
93// #### Import configuration
94//
95// It is possible to configure how use-trees are merged with the `imports.granularity.group` setting.
96// Mimics the corresponding behavior of the `Auto Import` feature.
97//
98// #### LSP and performance implications
99//
100// The feature is enabled only if the LSP client supports LSP protocol version 3.16+ and reports the `additionalTextEdits`
101// (case-sensitive) resolve client capability in its client capabilities.
102// This way the server is able to defer the costly computations, doing them for a selected completion item only.
103// For clients with no such support, all edits have to be calculated on the completion request, including the fuzzy search completion ones,
104// which might be slow ergo the feature is automatically disabled.
105//
106// #### Feature toggle
107//
108// The feature can be forcefully turned off in the settings with the `rust-analyzer.completion.autoimport.enable` flag.
109// Note that having this flag set to `true` does not guarantee that the feature is enabled: your client needs to have the corresponding
110// capability enabled.
111pub(crate) fn import_on_the_fly_path<'db>(
112    acc: &mut Completions,
113    ctx: &CompletionContext<'_, 'db>,
114    path_ctx: &PathCompletionCtx<'db>,
115) -> Option<()> {
116    if !ctx.config.enable_imports_on_the_fly {
117        return None;
118    }
119    let qualified = match path_ctx {
120        PathCompletionCtx {
121            kind:
122                PathKind::Expr { .. }
123                | PathKind::Type { .. }
124                | PathKind::Attr { .. }
125                | PathKind::Derive { .. }
126                | PathKind::Item { .. }
127                | PathKind::Pat { .. },
128            qualified,
129            ..
130        } => qualified,
131        _ => return None,
132    };
133    let potential_import_name = import_name(ctx);
134    let qualifier = match qualified {
135        Qualified::With { path, .. } => Some(path.clone()),
136        Qualified::TypeAnchor { .. } => return None,
137        Qualified::No | Qualified::Absolute => None,
138    };
139    let import_assets = import_assets_for_path(
140        ctx,
141        Some(&path_ctx.path),
142        &potential_import_name,
143        qualifier.clone(),
144    )?;
145
146    import_on_the_fly(
147        acc,
148        ctx,
149        path_ctx,
150        import_assets,
151        qualifier.map(|it| it.syntax().clone()).or_else(|| ctx.original_token.parent())?,
152        potential_import_name,
153    )
154}
155
156pub(crate) fn import_on_the_fly_pat(
157    acc: &mut Completions,
158    ctx: &CompletionContext<'_, '_>,
159    pattern_ctx: &PatternContext,
160) -> Option<()> {
161    if !ctx.config.enable_imports_on_the_fly {
162        return None;
163    }
164    if let PatternContext { record_pat: Some(_), .. } = pattern_ctx {
165        return None;
166    }
167
168    let potential_import_name = import_name(ctx);
169    let import_assets = import_assets_for_path(ctx, None, &potential_import_name, None)?;
170
171    import_on_the_fly_pat_(
172        acc,
173        ctx,
174        pattern_ctx,
175        import_assets,
176        ctx.original_token.parent()?,
177        potential_import_name,
178    )
179}
180
181pub(crate) fn import_on_the_fly_dot<'db>(
182    acc: &mut Completions,
183    ctx: &CompletionContext<'_, 'db>,
184    dot_access: &DotAccess<'db>,
185) -> Option<()> {
186    if !ctx.config.enable_imports_on_the_fly {
187        return None;
188    }
189    let receiver = dot_access.receiver.as_ref()?;
190    let ty = dot_access.receiver_ty.as_ref()?;
191    let potential_import_name = import_name(ctx);
192    let import_assets = ImportAssets::for_fuzzy_method_call(
193        ctx.module,
194        ty.original.clone(),
195        potential_import_name.clone(),
196        receiver.syntax().clone(),
197    )?;
198
199    import_on_the_fly_method(
200        acc,
201        ctx,
202        dot_access,
203        import_assets,
204        receiver.syntax().clone(),
205        potential_import_name,
206    )
207}
208
209fn import_on_the_fly<'db>(
210    acc: &mut Completions,
211    ctx: &CompletionContext<'_, 'db>,
212    path_ctx @ PathCompletionCtx { kind, .. }: &PathCompletionCtx<'db>,
213    import_assets: ImportAssets<'db>,
214    position: SyntaxNode,
215    potential_import_name: String,
216) -> Option<()> {
217    let _p = tracing::info_span!("import_on_the_fly", ?potential_import_name).entered();
218
219    ImportScope::find_insert_use_container(&position, &ctx.sema)?;
220
221    let ns_filter = |import: &LocatedImport| {
222        match (kind, import.original_item) {
223            // Aren't handled in flyimport
224            (PathKind::Vis { .. } | PathKind::Use, _) => false,
225            // modules are always fair game
226            (_, ItemInNs::Types(hir::ModuleDef::Module(_))) => true,
227            // and so are macros(except for attributes)
228            (
229                PathKind::Expr { .. }
230                | PathKind::Type { .. }
231                | PathKind::Item { .. }
232                | PathKind::Pat { .. },
233                ItemInNs::Macros(mac),
234            ) => mac.is_fn_like(ctx.db),
235            (PathKind::Item { .. }, ..) => false,
236
237            (PathKind::Expr { .. }, ItemInNs::Types(_) | ItemInNs::Values(_)) => true,
238
239            (PathKind::Pat { .. }, ItemInNs::Types(_)) => true,
240            (PathKind::Pat { .. }, ItemInNs::Values(def)) => {
241                matches!(def, hir::ModuleDef::Const(_))
242            }
243
244            (PathKind::Type { location }, ItemInNs::Types(ty)) => {
245                if matches!(location, TypeLocation::TypeBound) {
246                    matches!(ty, ModuleDef::Trait(_))
247                } else if matches!(location, TypeLocation::ImplTrait) {
248                    matches!(ty, ModuleDef::Trait(_) | ModuleDef::Module(_))
249                } else {
250                    true
251                }
252            }
253            (PathKind::Type { .. }, ItemInNs::Values(_)) => false,
254
255            (PathKind::Attr { .. }, ItemInNs::Macros(mac)) => mac.is_attr(ctx.db),
256            (PathKind::Attr { .. }, _) => false,
257
258            (PathKind::Derive { existing_derives }, ItemInNs::Macros(mac)) => {
259                mac.is_derive(ctx.db) && !existing_derives.contains(&mac)
260            }
261            (PathKind::Derive { .. }, _) => false,
262        }
263    };
264    let user_input_lowercased = potential_import_name.to_lowercase();
265    let mut import_name_buffer = String::new();
266
267    let import_cfg = ctx.config.import_path_config();
268
269    import_assets
270        .search_for_imports(&ctx.sema, import_cfg, ctx.config.insert_use.prefix_kind)
271        .filter(ns_filter)
272        .filter(|import| {
273            let original_item = &import.original_item;
274            !ctx.is_item_hidden(&import.item_to_import)
275                && !ctx.is_item_hidden(original_item)
276                && ctx.check_stability(original_item.attrs(ctx.db).as_ref())
277        })
278        .filter(|import| filter_excluded_flyimport(ctx, import))
279        .sorted_by(|a, b| {
280            let mut key = |import_path| {
281                (
282                    compute_fuzzy_completion_order_key(
283                        import_path,
284                        &user_input_lowercased,
285                        &mut import_name_buffer,
286                    ),
287                    import_path,
288                )
289            };
290            key(&a.import_path).cmp(&key(&b.import_path))
291        })
292        .filter_map(|import| {
293            render_resolution_with_import(RenderContext::new(ctx), path_ctx, import)
294        })
295        .map(|builder| builder.build(ctx.db))
296        .for_each(|item| acc.add(item));
297    Some(())
298}
299
300fn import_on_the_fly_pat_<'db>(
301    acc: &mut Completions,
302    ctx: &CompletionContext<'_, 'db>,
303    pattern_ctx: &PatternContext,
304    import_assets: ImportAssets<'db>,
305    position: SyntaxNode,
306    potential_import_name: String,
307) -> Option<()> {
308    let _p = tracing::info_span!("import_on_the_fly_pat_", ?potential_import_name).entered();
309
310    ImportScope::find_insert_use_container(&position, &ctx.sema)?;
311
312    let ns_filter = |import: &LocatedImport| match import.original_item {
313        ItemInNs::Macros(mac) => mac.is_fn_like(ctx.db),
314        ItemInNs::Types(_) => true,
315        ItemInNs::Values(def) => matches!(def, hir::ModuleDef::Const(_)),
316    };
317    let user_input_lowercased = potential_import_name.to_lowercase();
318    let mut import_name_buffer = String::new();
319    let cfg = ctx.config.import_path_config();
320
321    import_assets
322        .search_for_imports(&ctx.sema, cfg, ctx.config.insert_use.prefix_kind)
323        .filter(ns_filter)
324        .filter(|import| {
325            let original_item = &import.original_item;
326            !ctx.is_item_hidden(&import.item_to_import)
327                && !ctx.is_item_hidden(original_item)
328                && ctx.check_stability(original_item.attrs(ctx.db).as_ref())
329        })
330        .sorted_by(|a, b| {
331            let mut key = |import_path| {
332                (
333                    compute_fuzzy_completion_order_key(
334                        import_path,
335                        &user_input_lowercased,
336                        &mut import_name_buffer,
337                    ),
338                    import_path,
339                )
340            };
341            key(&a.import_path).cmp(&key(&b.import_path))
342        })
343        .filter_map(|import| {
344            render_resolution_with_import_pat(RenderContext::new(ctx), pattern_ctx, import)
345        })
346        .map(|builder| builder.build(ctx.db))
347        .for_each(|item| acc.add(item));
348    Some(())
349}
350
351fn import_on_the_fly_method<'db>(
352    acc: &mut Completions,
353    ctx: &CompletionContext<'_, 'db>,
354    dot_access: &DotAccess<'db>,
355    import_assets: ImportAssets<'db>,
356    position: SyntaxNode,
357    potential_import_name: String,
358) -> Option<()> {
359    let _p = tracing::info_span!("import_on_the_fly_method", ?potential_import_name).entered();
360
361    ImportScope::find_insert_use_container(&position, &ctx.sema)?;
362
363    let user_input_lowercased = potential_import_name.to_lowercase();
364    let mut import_name_buffer = String::new();
365
366    let cfg = ctx.config.import_path_config();
367
368    import_assets
369        .search_for_imports(&ctx.sema, cfg, ctx.config.insert_use.prefix_kind)
370        .filter(|import| {
371            !ctx.is_item_hidden(&import.item_to_import)
372                && !ctx.is_item_hidden(&import.original_item)
373        })
374        .filter(|import| filter_excluded_flyimport(ctx, import))
375        .sorted_by(|a, b| {
376            let mut key = |import_path| {
377                (
378                    compute_fuzzy_completion_order_key(
379                        import_path,
380                        &user_input_lowercased,
381                        &mut import_name_buffer,
382                    ),
383                    import_path,
384                )
385            };
386            key(&a.import_path).cmp(&key(&b.import_path))
387        })
388        .for_each(|import| {
389            if let ItemInNs::Values(hir::ModuleDef::Function(f)) = import.original_item {
390                acc.add_method_with_import(ctx, dot_access, f, import);
391            }
392        });
393    Some(())
394}
395
396fn filter_excluded_flyimport(ctx: &CompletionContext<'_, '_>, import: &LocatedImport) -> bool {
397    let def = import.item_to_import.into_module_def();
398    let is_exclude_flyimport = ctx.exclude_flyimport.get(&def).copied();
399
400    if matches!(is_exclude_flyimport, Some(AutoImportExclusionType::Always))
401        || !import.complete_in_flyimport.0
402    {
403        return false;
404    }
405    let method_imported = import.item_to_import != import.original_item;
406    if method_imported
407        && (is_exclude_flyimport.is_some()
408            || ctx.exclude_flyimport.contains_key(&import.original_item.into_module_def()))
409    {
410        // If this is a method, exclude it either if it was excluded itself (which may not be caught above,
411        // because `item_to_import` is the trait), or if its trait was excluded. We don't need to check
412        // the attributes here, since they pass from trait to methods on import map construction.
413        return false;
414    }
415    true
416}
417
418fn import_name(ctx: &CompletionContext<'_, '_>) -> String {
419    let token_kind = ctx.token.kind();
420
421    if token_kind.is_any_identifier() { ctx.token.to_string() } else { String::new() }
422}
423
424fn import_assets_for_path<'db>(
425    ctx: &CompletionContext<'_, 'db>,
426    path: Option<&ast::Path>,
427    potential_import_name: &str,
428    qualifier: Option<ast::Path>,
429) -> Option<ImportAssets<'db>> {
430    let _p =
431        tracing::info_span!("import_assets_for_path", ?potential_import_name, ?qualifier).entered();
432
433    let fuzzy_name_length = potential_import_name.len();
434    let mut assets_for_path = ImportAssets::for_fuzzy_path(
435        ctx.module,
436        path,
437        qualifier,
438        potential_import_name.to_owned(),
439        &ctx.sema,
440        ctx.token.parent()?,
441    )?;
442    if fuzzy_name_length == 0 {
443        // nothing matches the empty string exactly, but we still compute assoc items in this case
444        assets_for_path.path_fuzzy_name_to_exact();
445    } else if fuzzy_name_length < 3 {
446        cov_mark::hit!(flyimport_prefix_on_short_path);
447        assets_for_path.path_fuzzy_name_to_prefix();
448    }
449    Some(assets_for_path)
450}
451
452fn compute_fuzzy_completion_order_key(
453    proposed_mod_path: &hir::ModPath,
454    user_input_lowercased: &str,
455    import_name_buffer: &mut String,
456) -> usize {
457    cov_mark::hit!(certain_fuzzy_order_test);
458    let Some(import_name) = proposed_mod_path.segments().last() else {
459        return usize::MAX;
460    };
461
462    import_name_buffer.clear();
463    import_name_buffer.push_str(import_name.as_str());
464    import_name_buffer.make_ascii_lowercase();
465    import_name_buffer.find(user_input_lowercased).unwrap_or(usize::MAX)
466}