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