]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/helpers/import_assets.rs
Merge #11393
[rust.git] / crates / ide_db / src / helpers / import_assets.rs
1 //! Look up accessible paths for items.
2 use hir::{
3     AsAssocItem, AssocItem, AssocItemContainer, Crate, ItemInNs, MacroDef, ModPath, Module,
4     ModuleDef, PathResolution, PrefixKind, ScopeDef, Semantics, Type,
5 };
6 use itertools::Itertools;
7 use rustc_hash::FxHashSet;
8 use syntax::{
9     ast::{self, HasName},
10     utils::path_to_string_stripping_turbo_fish,
11     AstNode, AstToken, SyntaxNode,
12 };
13
14 use crate::{
15     helpers::get_path_in_derive_attr,
16     items_locator::{self, AssocItemSearch, DEFAULT_QUERY_SEARCH_LIMIT},
17     RootDatabase,
18 };
19
20 use super::item_name;
21
22 /// A candidate for import, derived during various IDE activities:
23 /// * completion with imports on the fly proposals
24 /// * completion edit resolve requests
25 /// * assists
26 /// * etc.
27 #[derive(Debug)]
28 pub enum ImportCandidate {
29     /// A path, qualified (`std::collections::HashMap`) or not (`HashMap`).
30     Path(PathImportCandidate),
31     /// A trait associated function (with no self parameter) or an associated constant.
32     /// For 'test_mod::TestEnum::test_function', `ty` is the `test_mod::TestEnum` expression type
33     /// and `name` is the `test_function`
34     TraitAssocItem(TraitImportCandidate),
35     /// A trait method with self parameter.
36     /// For 'test_enum.test_method()', `ty` is the `test_enum` expression type
37     /// and `name` is the `test_method`
38     TraitMethod(TraitImportCandidate),
39 }
40
41 /// A trait import needed for a given associated item access.
42 /// For `some::path::SomeStruct::ASSOC_`, contains the
43 /// type of `some::path::SomeStruct` and `ASSOC_` as the item name.
44 #[derive(Debug)]
45 pub struct TraitImportCandidate {
46     /// A type of the item that has the associated item accessed at.
47     pub receiver_ty: Type,
48     /// The associated item name that the trait to import should contain.
49     pub assoc_item_name: NameToImport,
50 }
51
52 /// Path import for a given name, qualified or not.
53 #[derive(Debug)]
54 pub struct PathImportCandidate {
55     /// Optional qualifier before name.
56     pub qualifier: Option<FirstSegmentUnresolved>,
57     /// The name the item (struct, trait, enum, etc.) should have.
58     pub name: NameToImport,
59 }
60
61 /// A qualifier that has a first segment and it's unresolved.
62 #[derive(Debug)]
63 pub struct FirstSegmentUnresolved {
64     fist_segment: ast::NameRef,
65     full_qualifier: ast::Path,
66 }
67
68 /// A name that will be used during item lookups.
69 #[derive(Debug, Clone)]
70 pub enum NameToImport {
71     /// Requires items with names that exactly match the given string, bool indicatse case-sensitivity.
72     Exact(String, bool),
73     /// Requires items with names that case-insensitively contain all letters from the string,
74     /// in the same order, but not necessary adjacent.
75     Fuzzy(String),
76 }
77
78 impl NameToImport {
79     pub fn exact_case_sensitive(s: String) -> NameToImport {
80         NameToImport::Exact(s, true)
81     }
82 }
83
84 impl NameToImport {
85     pub fn text(&self) -> &str {
86         match self {
87             NameToImport::Exact(text, _) => text.as_str(),
88             NameToImport::Fuzzy(text) => text.as_str(),
89         }
90     }
91 }
92
93 /// A struct to find imports in the project, given a certain name (or its part) and the context.
94 #[derive(Debug)]
95 pub struct ImportAssets {
96     import_candidate: ImportCandidate,
97     candidate_node: SyntaxNode,
98     module_with_candidate: Module,
99 }
100
101 impl ImportAssets {
102     pub fn for_method_call(
103         method_call: &ast::MethodCallExpr,
104         sema: &Semantics<RootDatabase>,
105     ) -> Option<Self> {
106         let candidate_node = method_call.syntax().clone();
107         Some(Self {
108             import_candidate: ImportCandidate::for_method_call(sema, method_call)?,
109             module_with_candidate: sema.scope(&candidate_node).module()?,
110             candidate_node,
111         })
112     }
113
114     pub fn for_exact_path(
115         fully_qualified_path: &ast::Path,
116         sema: &Semantics<RootDatabase>,
117     ) -> Option<Self> {
118         let candidate_node = fully_qualified_path.syntax().clone();
119         if candidate_node.ancestors().find_map(ast::Use::cast).is_some() {
120             return None;
121         }
122         Some(Self {
123             import_candidate: ImportCandidate::for_regular_path(sema, fully_qualified_path)?,
124             module_with_candidate: sema.scope(&candidate_node).module()?,
125             candidate_node,
126         })
127     }
128
129     pub fn for_ident_pat(sema: &Semantics<RootDatabase>, pat: &ast::IdentPat) -> Option<Self> {
130         if !pat.is_simple_ident() {
131             return None;
132         }
133         let name = pat.name()?;
134         let candidate_node = pat.syntax().clone();
135         Some(Self {
136             import_candidate: ImportCandidate::for_name(sema, &name)?,
137             module_with_candidate: sema.scope(&candidate_node).module()?,
138             candidate_node,
139         })
140     }
141
142     pub fn for_derive_ident(sema: &Semantics<RootDatabase>, ident: &ast::Ident) -> Option<Self> {
143         let attr = ident.syntax().ancestors().find_map(ast::Attr::cast)?;
144         let path = get_path_in_derive_attr(sema, &attr, ident)?;
145
146         if let Some(_) = path.qualifier() {
147             return None;
148         }
149
150         let name = NameToImport::exact_case_sensitive(path.segment()?.name_ref()?.to_string());
151         let candidate_node = attr.syntax().clone();
152         Some(Self {
153             import_candidate: ImportCandidate::Path(PathImportCandidate { qualifier: None, name }),
154             module_with_candidate: sema.scope(&candidate_node).module()?,
155             candidate_node,
156         })
157     }
158
159     pub fn for_fuzzy_path(
160         module_with_candidate: Module,
161         qualifier: Option<ast::Path>,
162         fuzzy_name: String,
163         sema: &Semantics<RootDatabase>,
164         candidate_node: SyntaxNode,
165     ) -> Option<Self> {
166         Some(Self {
167             import_candidate: ImportCandidate::for_fuzzy_path(qualifier, fuzzy_name, sema)?,
168             module_with_candidate,
169             candidate_node,
170         })
171     }
172
173     pub fn for_fuzzy_method_call(
174         module_with_method_call: Module,
175         receiver_ty: Type,
176         fuzzy_method_name: String,
177         candidate_node: SyntaxNode,
178     ) -> Option<Self> {
179         Some(Self {
180             import_candidate: ImportCandidate::TraitMethod(TraitImportCandidate {
181                 receiver_ty,
182                 assoc_item_name: NameToImport::Fuzzy(fuzzy_method_name),
183             }),
184             module_with_candidate: module_with_method_call,
185             candidate_node,
186         })
187     }
188 }
189
190 /// An import (not necessary the only one) that corresponds a certain given [`PathImportCandidate`].
191 /// (the structure is not entirely correct, since there can be situations requiring two imports, see FIXME below for the details)
192 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
193 pub struct LocatedImport {
194     /// The path to use in the `use` statement for a given candidate to be imported.
195     pub import_path: ModPath,
196     /// An item that will be imported with the import path given.
197     pub item_to_import: ItemInNs,
198     /// The path import candidate, resolved.
199     ///
200     /// Not necessary matches the import:
201     /// For any associated constant from the trait, we try to access as `some::path::SomeStruct::ASSOC_`
202     /// the original item is the associated constant, but the import has to be a trait that
203     /// defines this constant.
204     pub original_item: ItemInNs,
205     /// A path of the original item.
206     pub original_path: Option<ModPath>,
207 }
208
209 impl LocatedImport {
210     pub fn new(
211         import_path: ModPath,
212         item_to_import: ItemInNs,
213         original_item: ItemInNs,
214         original_path: Option<ModPath>,
215     ) -> Self {
216         Self { import_path, item_to_import, original_item, original_path }
217     }
218 }
219
220 impl ImportAssets {
221     pub fn import_candidate(&self) -> &ImportCandidate {
222         &self.import_candidate
223     }
224
225     pub fn search_for_imports(
226         &self,
227         sema: &Semantics<RootDatabase>,
228         prefix_kind: PrefixKind,
229     ) -> Vec<LocatedImport> {
230         let _p = profile::span("import_assets::search_for_imports");
231         self.search_for(sema, Some(prefix_kind))
232     }
233
234     /// This may return non-absolute paths if a part of the returned path is already imported into scope.
235     pub fn search_for_relative_paths(&self, sema: &Semantics<RootDatabase>) -> Vec<LocatedImport> {
236         let _p = profile::span("import_assets::search_for_relative_paths");
237         self.search_for(sema, None)
238     }
239
240     pub fn path_fuzzy_name_to_exact(&mut self, case_sensitive: bool) {
241         if let ImportCandidate::Path(PathImportCandidate { name: to_import, .. }) =
242             &mut self.import_candidate
243         {
244             let name = match to_import {
245                 NameToImport::Fuzzy(name) => std::mem::take(name),
246                 _ => return,
247             };
248             *to_import = NameToImport::Exact(name, case_sensitive);
249         }
250     }
251
252     fn search_for(
253         &self,
254         sema: &Semantics<RootDatabase>,
255         prefixed: Option<PrefixKind>,
256     ) -> Vec<LocatedImport> {
257         let _p = profile::span("import_assets::search_for");
258
259         let scope_definitions = self.scope_definitions(sema);
260         let current_crate = self.module_with_candidate.krate();
261         let mod_path = |item| {
262             get_mod_path(
263                 sema.db,
264                 item_for_path_search(sema.db, item)?,
265                 &self.module_with_candidate,
266                 prefixed,
267             )
268         };
269
270         match &self.import_candidate {
271             ImportCandidate::Path(path_candidate) => {
272                 path_applicable_imports(sema, current_crate, path_candidate, mod_path)
273             }
274             ImportCandidate::TraitAssocItem(trait_candidate) => {
275                 trait_applicable_items(sema, current_crate, trait_candidate, true, mod_path)
276             }
277             ImportCandidate::TraitMethod(trait_candidate) => {
278                 trait_applicable_items(sema, current_crate, trait_candidate, false, mod_path)
279             }
280         }
281         .into_iter()
282         .filter(|import| import.import_path.len() > 1)
283         .filter(|import| !scope_definitions.contains(&ScopeDef::from(import.item_to_import)))
284         .sorted_by(|a, b| a.import_path.cmp(&b.import_path))
285         .collect()
286     }
287
288     fn scope_definitions(&self, sema: &Semantics<RootDatabase>) -> FxHashSet<ScopeDef> {
289         let _p = profile::span("import_assets::scope_definitions");
290         let mut scope_definitions = FxHashSet::default();
291         sema.scope(&self.candidate_node).process_all_names(&mut |_, scope_def| {
292             scope_definitions.insert(scope_def);
293         });
294         scope_definitions
295     }
296 }
297
298 fn path_applicable_imports(
299     sema: &Semantics<RootDatabase>,
300     current_crate: Crate,
301     path_candidate: &PathImportCandidate,
302     mod_path: impl Fn(ItemInNs) -> Option<ModPath> + Copy,
303 ) -> FxHashSet<LocatedImport> {
304     let _p = profile::span("import_assets::path_applicable_imports");
305
306     match &path_candidate.qualifier {
307         None => {
308             items_locator::items_with_name(
309                 sema,
310                 current_crate,
311                 path_candidate.name.clone(),
312                 // FIXME: we could look up assoc items by the input and propose those in completion,
313                 // but that requires more preparation first:
314                 // * store non-trait assoc items in import_map to fully enable this lookup
315                 // * ensure that does not degrade the performance (benchmark it)
316                 // * write more logic to check for corresponding trait presence requirement (we're unable to flyimport multiple item right now)
317                 // * improve the associated completion item matching and/or scoring to ensure no noisy completions appear
318                 //
319                 // see also an ignored test under FIXME comment in the qualify_path.rs module
320                 AssocItemSearch::Exclude,
321                 Some(DEFAULT_QUERY_SEARCH_LIMIT.inner()),
322             )
323             .filter_map(|item| {
324                 let mod_path = mod_path(item)?;
325                 Some(LocatedImport::new(mod_path.clone(), item, item, Some(mod_path)))
326             })
327             .collect()
328         }
329         Some(first_segment_unresolved) => {
330             let unresolved_qualifier =
331                 path_to_string_stripping_turbo_fish(&first_segment_unresolved.full_qualifier);
332             let unresolved_first_segment = first_segment_unresolved.fist_segment.text();
333             items_locator::items_with_name(
334                 sema,
335                 current_crate,
336                 path_candidate.name.clone(),
337                 AssocItemSearch::Include,
338                 Some(DEFAULT_QUERY_SEARCH_LIMIT.inner()),
339             )
340             .filter_map(|item| {
341                 import_for_item(
342                     sema.db,
343                     mod_path,
344                     &unresolved_first_segment,
345                     &unresolved_qualifier,
346                     item,
347                 )
348             })
349             .collect()
350         }
351     }
352 }
353
354 fn import_for_item(
355     db: &RootDatabase,
356     mod_path: impl Fn(ItemInNs) -> Option<ModPath>,
357     unresolved_first_segment: &str,
358     unresolved_qualifier: &str,
359     original_item: ItemInNs,
360 ) -> Option<LocatedImport> {
361     let _p = profile::span("import_assets::import_for_item");
362
363     let original_item_candidate = item_for_path_search(db, original_item)?;
364     let import_path_candidate = mod_path(original_item_candidate)?;
365     let import_path_string = import_path_candidate.to_string();
366
367     let expected_import_end = if item_as_assoc(db, original_item).is_some() {
368         unresolved_qualifier.to_string()
369     } else {
370         format!("{}::{}", unresolved_qualifier, item_name(db, original_item)?)
371     };
372     if !import_path_string.contains(unresolved_first_segment)
373         || !import_path_string.ends_with(&expected_import_end)
374     {
375         return None;
376     }
377
378     let segment_import =
379         find_import_for_segment(db, original_item_candidate, unresolved_first_segment)?;
380     let trait_item_to_import = item_as_assoc(db, original_item)
381         .and_then(|assoc| assoc.containing_trait(db))
382         .map(|trait_| ItemInNs::from(ModuleDef::from(trait_)));
383     Some(match (segment_import == original_item_candidate, trait_item_to_import) {
384         (true, Some(_)) => {
385             // FIXME we should be able to import both the trait and the segment,
386             // but it's unclear what to do with overlapping edits (merge imports?)
387             // especially in case of lazy completion edit resolutions.
388             return None;
389         }
390         (false, Some(trait_to_import)) => LocatedImport::new(
391             mod_path(trait_to_import)?,
392             trait_to_import,
393             original_item,
394             mod_path(original_item),
395         ),
396         (true, None) => LocatedImport::new(
397             import_path_candidate,
398             original_item_candidate,
399             original_item,
400             mod_path(original_item),
401         ),
402         (false, None) => LocatedImport::new(
403             mod_path(segment_import)?,
404             segment_import,
405             original_item,
406             mod_path(original_item),
407         ),
408     })
409 }
410
411 pub fn item_for_path_search(db: &RootDatabase, item: ItemInNs) -> Option<ItemInNs> {
412     Some(match item {
413         ItemInNs::Types(_) | ItemInNs::Values(_) => match item_as_assoc(db, item) {
414             Some(assoc_item) => match assoc_item.container(db) {
415                 AssocItemContainer::Trait(trait_) => ItemInNs::from(ModuleDef::from(trait_)),
416                 AssocItemContainer::Impl(impl_) => {
417                     ItemInNs::from(ModuleDef::from(impl_.self_ty(db).as_adt()?))
418                 }
419             },
420             None => item,
421         },
422         ItemInNs::Macros(_) => item,
423     })
424 }
425
426 fn find_import_for_segment(
427     db: &RootDatabase,
428     original_item: ItemInNs,
429     unresolved_first_segment: &str,
430 ) -> Option<ItemInNs> {
431     let segment_is_name = item_name(db, original_item)
432         .map(|name| name.to_smol_str() == unresolved_first_segment)
433         .unwrap_or(false);
434
435     Some(if segment_is_name {
436         original_item
437     } else {
438         let matching_module =
439             module_with_segment_name(db, unresolved_first_segment, original_item)?;
440         ItemInNs::from(ModuleDef::from(matching_module))
441     })
442 }
443
444 fn module_with_segment_name(
445     db: &RootDatabase,
446     segment_name: &str,
447     candidate: ItemInNs,
448 ) -> Option<Module> {
449     let mut current_module = match candidate {
450         ItemInNs::Types(module_def_id) => ModuleDef::from(module_def_id).module(db),
451         ItemInNs::Values(module_def_id) => ModuleDef::from(module_def_id).module(db),
452         ItemInNs::Macros(macro_def_id) => MacroDef::from(macro_def_id).module(db),
453     };
454     while let Some(module) = current_module {
455         if let Some(module_name) = module.name(db) {
456             if module_name.to_smol_str() == segment_name {
457                 return Some(module);
458             }
459         }
460         current_module = module.parent(db);
461     }
462     None
463 }
464
465 fn trait_applicable_items(
466     sema: &Semantics<RootDatabase>,
467     current_crate: Crate,
468     trait_candidate: &TraitImportCandidate,
469     trait_assoc_item: bool,
470     mod_path: impl Fn(ItemInNs) -> Option<ModPath>,
471 ) -> FxHashSet<LocatedImport> {
472     let _p = profile::span("import_assets::trait_applicable_items");
473
474     let db = sema.db;
475
476     let inherent_traits = trait_candidate.receiver_ty.applicable_inherent_traits(db);
477     let env_traits = trait_candidate.receiver_ty.env_traits(db);
478     let related_traits = inherent_traits.chain(env_traits).collect::<FxHashSet<_>>();
479
480     let mut required_assoc_items = FxHashSet::default();
481     let trait_candidates = items_locator::items_with_name(
482         sema,
483         current_crate,
484         trait_candidate.assoc_item_name.clone(),
485         AssocItemSearch::AssocItemsOnly,
486         Some(DEFAULT_QUERY_SEARCH_LIMIT.inner()),
487     )
488     .filter_map(|input| item_as_assoc(db, input))
489     .filter_map(|assoc| {
490         let assoc_item_trait = assoc.containing_trait(db)?;
491         if related_traits.contains(&assoc_item_trait) {
492             None
493         } else {
494             required_assoc_items.insert(assoc);
495             Some(assoc_item_trait.into())
496         }
497     })
498     .collect();
499
500     let mut located_imports = FxHashSet::default();
501
502     if trait_assoc_item {
503         trait_candidate.receiver_ty.iterate_path_candidates(
504             db,
505             current_crate,
506             &trait_candidates,
507             None,
508             None,
509             |_, assoc| {
510                 if required_assoc_items.contains(&assoc) {
511                     if let AssocItem::Function(f) = assoc {
512                         if f.self_param(db).is_some() {
513                             return None;
514                         }
515                     }
516                     let located_trait = assoc.containing_trait(db)?;
517                     let trait_item = ItemInNs::from(ModuleDef::from(located_trait));
518                     let original_item = assoc_to_item(assoc);
519                     located_imports.insert(LocatedImport::new(
520                         mod_path(trait_item)?,
521                         trait_item,
522                         original_item,
523                         mod_path(original_item),
524                     ));
525                 }
526                 None::<()>
527             },
528         )
529     } else {
530         trait_candidate.receiver_ty.iterate_method_candidates(
531             db,
532             current_crate,
533             &trait_candidates,
534             None,
535             None,
536             |_, function| {
537                 let assoc = function.as_assoc_item(db)?;
538                 if required_assoc_items.contains(&assoc) {
539                     let located_trait = assoc.containing_trait(db)?;
540                     let trait_item = ItemInNs::from(ModuleDef::from(located_trait));
541                     let original_item = assoc_to_item(assoc);
542                     located_imports.insert(LocatedImport::new(
543                         mod_path(trait_item)?,
544                         trait_item,
545                         original_item,
546                         mod_path(original_item),
547                     ));
548                 }
549                 None::<()>
550             },
551         )
552     };
553
554     located_imports
555 }
556
557 fn assoc_to_item(assoc: AssocItem) -> ItemInNs {
558     match assoc {
559         AssocItem::Function(f) => ItemInNs::from(ModuleDef::from(f)),
560         AssocItem::Const(c) => ItemInNs::from(ModuleDef::from(c)),
561         AssocItem::TypeAlias(t) => ItemInNs::from(ModuleDef::from(t)),
562     }
563 }
564
565 fn get_mod_path(
566     db: &RootDatabase,
567     item_to_search: ItemInNs,
568     module_with_candidate: &Module,
569     prefixed: Option<PrefixKind>,
570 ) -> Option<ModPath> {
571     if let Some(prefix_kind) = prefixed {
572         module_with_candidate.find_use_path_prefixed(db, item_to_search, prefix_kind)
573     } else {
574         module_with_candidate.find_use_path(db, item_to_search)
575     }
576 }
577
578 impl ImportCandidate {
579     fn for_method_call(
580         sema: &Semantics<RootDatabase>,
581         method_call: &ast::MethodCallExpr,
582     ) -> Option<Self> {
583         match sema.resolve_method_call(method_call) {
584             Some(_) => None,
585             None => Some(Self::TraitMethod(TraitImportCandidate {
586                 receiver_ty: sema.type_of_expr(&method_call.receiver()?)?.adjusted(),
587                 assoc_item_name: NameToImport::exact_case_sensitive(
588                     method_call.name_ref()?.to_string(),
589                 ),
590             })),
591         }
592     }
593
594     fn for_regular_path(sema: &Semantics<RootDatabase>, path: &ast::Path) -> Option<Self> {
595         if sema.resolve_path(path).is_some() {
596             return None;
597         }
598         path_import_candidate(
599             sema,
600             path.qualifier(),
601             NameToImport::exact_case_sensitive(path.segment()?.name_ref()?.to_string()),
602         )
603     }
604
605     fn for_name(sema: &Semantics<RootDatabase>, name: &ast::Name) -> Option<Self> {
606         if sema
607             .scope(name.syntax())
608             .speculative_resolve(&ast::make::ext::ident_path(&name.text()))
609             .is_some()
610         {
611             return None;
612         }
613         Some(ImportCandidate::Path(PathImportCandidate {
614             qualifier: None,
615             name: NameToImport::exact_case_sensitive(name.to_string()),
616         }))
617     }
618
619     fn for_fuzzy_path(
620         qualifier: Option<ast::Path>,
621         fuzzy_name: String,
622         sema: &Semantics<RootDatabase>,
623     ) -> Option<Self> {
624         path_import_candidate(sema, qualifier, NameToImport::Fuzzy(fuzzy_name))
625     }
626 }
627
628 fn path_import_candidate(
629     sema: &Semantics<RootDatabase>,
630     qualifier: Option<ast::Path>,
631     name: NameToImport,
632 ) -> Option<ImportCandidate> {
633     Some(match qualifier {
634         Some(qualifier) => match sema.resolve_path(&qualifier) {
635             None => {
636                 let qualifier_start =
637                     qualifier.syntax().descendants().find_map(ast::NameRef::cast)?;
638                 let qualifier_start_path =
639                     qualifier_start.syntax().ancestors().find_map(ast::Path::cast)?;
640                 if sema.resolve_path(&qualifier_start_path).is_none() {
641                     ImportCandidate::Path(PathImportCandidate {
642                         qualifier: Some(FirstSegmentUnresolved {
643                             fist_segment: qualifier_start,
644                             full_qualifier: qualifier,
645                         }),
646                         name,
647                     })
648                 } else {
649                     return None;
650                 }
651             }
652             Some(PathResolution::Def(ModuleDef::Adt(assoc_item_path))) => {
653                 ImportCandidate::TraitAssocItem(TraitImportCandidate {
654                     receiver_ty: assoc_item_path.ty(sema.db),
655                     assoc_item_name: name,
656                 })
657             }
658             Some(_) => return None,
659         },
660         None => ImportCandidate::Path(PathImportCandidate { qualifier: None, name }),
661     })
662 }
663
664 fn item_as_assoc(db: &RootDatabase, item: ItemInNs) -> Option<AssocItem> {
665     item.as_module_def().and_then(|module_def| module_def.as_assoc_item(db))
666 }