]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/attribute/derive.rs
Replace more Name::to_string usages with Name::to_smol_str
[rust.git] / crates / ide_completion / src / completions / attribute / derive.rs
1 //! Completion for derives
2 use hir::{HasAttrs, MacroDef, MacroKind};
3 use ide_db::helpers::{import_assets::ImportAssets, insert_use::ImportScope, FamousDefs};
4 use itertools::Itertools;
5 use rustc_hash::FxHashSet;
6 use syntax::{ast, SyntaxKind};
7
8 use crate::{
9     completions::flyimport::compute_fuzzy_completion_order_key,
10     context::CompletionContext,
11     item::{CompletionItem, CompletionItemKind},
12     Completions, ImportEdit,
13 };
14
15 pub(super) fn complete_derive(
16     acc: &mut Completions,
17     ctx: &CompletionContext,
18     existing_derives: &[ast::Path],
19 ) {
20     let core = FamousDefs(&ctx.sema, ctx.krate).core();
21     let existing_derives: FxHashSet<_> = existing_derives
22         .into_iter()
23         .filter_map(|path| ctx.scope.speculative_resolve_as_mac(&path))
24         .filter(|mac| mac.kind() == MacroKind::Derive)
25         .collect();
26
27     for (name, mac) in get_derives_in_scope(ctx) {
28         if existing_derives.contains(&mac) {
29             continue;
30         }
31
32         let name = name.to_smol_str();
33         let label;
34         let (label, lookup) = match core.zip(mac.module(ctx.db).map(|it| it.krate())) {
35             // show derive dependencies for `core`/`std` derives
36             Some((core, mac_krate)) if core == mac_krate => {
37                 if let Some(derive_completion) = DEFAULT_DERIVE_DEPENDENCIES
38                     .iter()
39                     .find(|derive_completion| derive_completion.label == name)
40                 {
41                     let mut components = vec![derive_completion.label];
42                     components.extend(derive_completion.dependencies.iter().filter(
43                         |&&dependency| {
44                             !existing_derives
45                                 .iter()
46                                 .filter_map(|it| it.name(ctx.db))
47                                 .any(|it| it.to_smol_str() == dependency)
48                         },
49                     ));
50                     let lookup = components.join(", ");
51                     label = components.iter().rev().join(", ");
52                     (label.as_str(), Some(lookup))
53                 } else {
54                     (&*name, None)
55                 }
56             }
57             _ => (&*name, None),
58         };
59
60         let mut item =
61             CompletionItem::new(CompletionItemKind::Attribute, ctx.source_range(), label);
62         if let Some(docs) = mac.docs(ctx.db) {
63             item.documentation(docs);
64         }
65         if let Some(lookup) = lookup {
66             item.lookup_by(lookup);
67         }
68         item.add_to(acc);
69     }
70
71     flyimport_attribute(ctx, acc);
72 }
73
74 fn get_derives_in_scope(ctx: &CompletionContext) -> Vec<(hir::Name, MacroDef)> {
75     let mut result = Vec::default();
76     ctx.process_all_names(&mut |name, scope_def| {
77         if let hir::ScopeDef::MacroDef(mac) = scope_def {
78             if mac.kind() == hir::MacroKind::Derive {
79                 result.push((name, mac));
80             }
81         }
82     });
83     result
84 }
85
86 fn flyimport_attribute(ctx: &CompletionContext, acc: &mut Completions) -> Option<()> {
87     if ctx.token.kind() != SyntaxKind::IDENT {
88         return None;
89     };
90     let potential_import_name = ctx.token.to_string();
91     let module = ctx.scope.module()?;
92     let parent = ctx.token.parent()?;
93     let user_input_lowercased = potential_import_name.to_lowercase();
94     let import_assets = ImportAssets::for_fuzzy_path(
95         module,
96         None,
97         potential_import_name,
98         &ctx.sema,
99         parent.clone(),
100     )?;
101     let import_scope = ImportScope::find_insert_use_container(&parent, &ctx.sema)?;
102     acc.add_all(
103         import_assets
104             .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind)
105             .into_iter()
106             .filter_map(|import| match import.original_item {
107                 hir::ItemInNs::Macros(mac) => Some((import, mac)),
108                 _ => None,
109             })
110             .filter(|&(_, mac)| !ctx.is_item_hidden(&hir::ItemInNs::Macros(mac)))
111             .sorted_by_key(|(import, _)| {
112                 compute_fuzzy_completion_order_key(&import.import_path, &user_input_lowercased)
113             })
114             .filter_map(|(import, mac)| {
115                 let mut item = CompletionItem::new(
116                     CompletionItemKind::Attribute,
117                     ctx.source_range(),
118                     mac.name(ctx.db)?.to_string(),
119                 );
120                 item.add_import(ImportEdit { import, scope: import_scope.clone() });
121                 if let Some(docs) = mac.docs(ctx.db) {
122                     item.documentation(docs);
123                 }
124                 Some(item.build())
125             }),
126     );
127     Some(())
128 }
129
130 struct DeriveDependencies {
131     label: &'static str,
132     dependencies: &'static [&'static str],
133 }
134
135 /// Standard Rust derives that have dependencies
136 /// (the dependencies are needed so that the main derive don't break the compilation when added)
137 const DEFAULT_DERIVE_DEPENDENCIES: &[DeriveDependencies] = &[
138     DeriveDependencies { label: "Copy", dependencies: &["Clone"] },
139     DeriveDependencies { label: "Eq", dependencies: &["PartialEq"] },
140     DeriveDependencies { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] },
141     DeriveDependencies { label: "PartialOrd", dependencies: &["PartialEq"] },
142 ];