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