]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide/src/hover.rs
Rollup merge of #100228 - luqmana:suggestion-ice, r=estebank
[rust.git] / src / tools / rust-analyzer / crates / ide / src / hover.rs
1 mod render;
2
3 #[cfg(test)]
4 mod tests;
5
6 use std::iter;
7
8 use either::Either;
9 use hir::{HasSource, Semantics};
10 use ide_db::{
11     base_db::FileRange,
12     defs::{Definition, IdentClass, OperatorClass},
13     famous_defs::FamousDefs,
14     helpers::pick_best_token,
15     FxIndexSet, RootDatabase,
16 };
17 use itertools::Itertools;
18 use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxNode, SyntaxToken, T};
19
20 use crate::{
21     doc_links::token_as_doc_comment,
22     markup::Markup,
23     runnables::{runnable_fn, runnable_mod},
24     FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, TryToNav,
25 };
26 #[derive(Clone, Debug, PartialEq, Eq)]
27 pub struct HoverConfig {
28     pub links_in_hover: bool,
29     pub documentation: Option<HoverDocFormat>,
30 }
31
32 impl HoverConfig {
33     fn markdown(&self) -> bool {
34         matches!(self.documentation, Some(HoverDocFormat::Markdown))
35     }
36 }
37
38 #[derive(Clone, Debug, PartialEq, Eq)]
39 pub enum HoverDocFormat {
40     Markdown,
41     PlainText,
42 }
43
44 #[derive(Debug, Clone)]
45 pub enum HoverAction {
46     Runnable(Runnable),
47     Implementation(FilePosition),
48     Reference(FilePosition),
49     GoToType(Vec<HoverGotoTypeData>),
50 }
51
52 impl HoverAction {
53     fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
54         let targets = targets
55             .into_iter()
56             .filter_map(|it| {
57                 Some(HoverGotoTypeData {
58                     mod_path: render::path(
59                         db,
60                         it.module(db)?,
61                         it.name(db).map(|name| name.to_string()),
62                     ),
63                     nav: it.try_to_nav(db)?,
64                 })
65             })
66             .collect();
67         HoverAction::GoToType(targets)
68     }
69 }
70
71 #[derive(Debug, Clone, Eq, PartialEq, Hash)]
72 pub struct HoverGotoTypeData {
73     pub mod_path: String,
74     pub nav: NavigationTarget,
75 }
76
77 /// Contains the results when hovering over an item
78 #[derive(Debug, Default)]
79 pub struct HoverResult {
80     pub markup: Markup,
81     pub actions: Vec<HoverAction>,
82 }
83
84 // Feature: Hover
85 //
86 // Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
87 // Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
88 //
89 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
90 pub(crate) fn hover(
91     db: &RootDatabase,
92     FileRange { file_id, range }: FileRange,
93     config: &HoverConfig,
94 ) -> Option<RangeInfo<HoverResult>> {
95     let sema = &hir::Semantics::new(db);
96     let file = sema.parse(file_id).syntax().clone();
97
98     if !range.is_empty() {
99         return hover_ranged(&file, range, sema, config);
100     }
101     let offset = range.start();
102
103     let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
104         IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] | T![Self] => 4,
105         // index and prefix ops
106         T!['['] | T![']'] | T![?] | T![*] | T![-] | T![!] => 3,
107         kind if kind.is_keyword() => 2,
108         T!['('] | T![')'] => 2,
109         kind if kind.is_trivia() => 0,
110         _ => 1,
111     })?;
112
113     if let Some(doc_comment) = token_as_doc_comment(&original_token) {
114         cov_mark::hit!(no_highlight_on_comment_hover);
115         return doc_comment.get_definition_with_descend_at(sema, offset, |def, node, range| {
116             let res = hover_for_definition(sema, file_id, def, &node, config)?;
117             Some(RangeInfo::new(range, res))
118         });
119     }
120
121     let in_attr = matches!(original_token.parent().and_then(ast::TokenTree::cast), Some(tt) if tt.syntax().ancestors().any(|it| ast::Meta::can_cast(it.kind())));
122     let descended = if in_attr {
123         [sema.descend_into_macros_with_kind_preference(original_token.clone())].into()
124     } else {
125         sema.descend_into_macros_with_same_text(original_token.clone())
126     };
127
128     // FIXME: Definition should include known lints and the like instead of having this special case here
129     let hovered_lint = descended.iter().find_map(|token| {
130         let attr = token.parent_ancestors().find_map(ast::Attr::cast)?;
131         render::try_for_lint(&attr, token)
132     });
133     if let Some(res) = hovered_lint {
134         return Some(RangeInfo::new(original_token.text_range(), res));
135     }
136
137     let result = descended
138         .iter()
139         .filter_map(|token| {
140             let node = token.parent()?;
141             let class = IdentClass::classify_token(sema, token)?;
142             if let IdentClass::Operator(OperatorClass::Await(_)) = class {
143                 // It's better for us to fall back to the keyword hover here,
144                 // rendering poll is very confusing
145                 return None;
146             }
147             Some(class.definitions().into_iter().zip(iter::once(node).cycle()))
148         })
149         .flatten()
150         .unique_by(|&(def, _)| def)
151         .filter_map(|(def, node)| hover_for_definition(sema, file_id, def, &node, config))
152         .reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
153             acc.actions.extend(actions);
154             acc.markup = Markup::from(format!("{}\n---\n{}", acc.markup, markup));
155             acc
156         });
157
158     if result.is_none() {
159         // fallbacks, show keywords or types
160
161         let res = descended.iter().find_map(|token| render::keyword(sema, config, token));
162         if let Some(res) = res {
163             return Some(RangeInfo::new(original_token.text_range(), res));
164         }
165         let res = descended
166             .iter()
167             .find_map(|token| hover_type_fallback(sema, config, token, &original_token));
168         if let Some(_) = res {
169             return res;
170         }
171     }
172     result.map(|mut res: HoverResult| {
173         res.actions = dedupe_or_merge_hover_actions(res.actions);
174         RangeInfo::new(original_token.text_range(), res)
175     })
176 }
177
178 pub(crate) fn hover_for_definition(
179     sema: &Semantics<'_, RootDatabase>,
180     file_id: FileId,
181     definition: Definition,
182     node: &SyntaxNode,
183     config: &HoverConfig,
184 ) -> Option<HoverResult> {
185     let famous_defs = match &definition {
186         Definition::BuiltinType(_) => Some(FamousDefs(sema, sema.scope(node)?.krate())),
187         _ => None,
188     };
189     render::definition(sema.db, definition, famous_defs.as_ref(), config).map(|markup| {
190         HoverResult {
191             markup: render::process_markup(sema.db, definition, &markup, config),
192             actions: show_implementations_action(sema.db, definition)
193                 .into_iter()
194                 .chain(show_fn_references_action(sema.db, definition))
195                 .chain(runnable_action(sema, definition, file_id))
196                 .chain(goto_type_action_for_def(sema.db, definition))
197                 .collect(),
198         }
199     })
200 }
201
202 fn hover_ranged(
203     file: &SyntaxNode,
204     range: syntax::TextRange,
205     sema: &Semantics<'_, RootDatabase>,
206     config: &HoverConfig,
207 ) -> Option<RangeInfo<HoverResult>> {
208     // FIXME: make this work in attributes
209     let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
210         match_ast! {
211             match it {
212                 ast::Expr(expr) => Some(Either::Left(expr)),
213                 ast::Pat(pat) => Some(Either::Right(pat)),
214                 _ => None,
215             }
216         }
217     })?;
218     let res = match &expr_or_pat {
219         Either::Left(ast::Expr::TryExpr(try_expr)) => render::try_expr(sema, config, try_expr),
220         Either::Left(ast::Expr::PrefixExpr(prefix_expr))
221             if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
222         {
223             render::deref_expr(sema, config, prefix_expr)
224         }
225         _ => None,
226     };
227     let res = res.or_else(|| render::type_info(sema, config, &expr_or_pat));
228     res.map(|it| {
229         let range = match expr_or_pat {
230             Either::Left(it) => it.syntax().text_range(),
231             Either::Right(it) => it.syntax().text_range(),
232         };
233         RangeInfo::new(range, it)
234     })
235 }
236
237 fn hover_type_fallback(
238     sema: &Semantics<'_, RootDatabase>,
239     config: &HoverConfig,
240     token: &SyntaxToken,
241     original_token: &SyntaxToken,
242 ) -> Option<RangeInfo<HoverResult>> {
243     let node =
244         token.parent_ancestors().take_while(|it| !ast::Item::can_cast(it.kind())).find(|n| {
245             ast::Expr::can_cast(n.kind())
246                 || ast::Pat::can_cast(n.kind())
247                 || ast::Type::can_cast(n.kind())
248         })?;
249
250     let expr_or_pat = match_ast! {
251         match node {
252             ast::Expr(it) => Either::Left(it),
253             ast::Pat(it) => Either::Right(it),
254             // If this node is a MACRO_CALL, it means that `descend_into_macros_many` failed to resolve.
255             // (e.g expanding a builtin macro). So we give up here.
256             ast::MacroCall(_it) => return None,
257             _ => return None,
258         }
259     };
260
261     let res = render::type_info(sema, config, &expr_or_pat)?;
262     let range = sema
263         .original_range_opt(&node)
264         .map(|frange| frange.range)
265         .unwrap_or_else(|| original_token.text_range());
266     Some(RangeInfo::new(range, res))
267 }
268
269 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
270     fn to_action(nav_target: NavigationTarget) -> HoverAction {
271         HoverAction::Implementation(FilePosition {
272             file_id: nav_target.file_id,
273             offset: nav_target.focus_or_full_range().start(),
274         })
275     }
276
277     let adt = match def {
278         Definition::Trait(it) => return it.try_to_nav(db).map(to_action),
279         Definition::Adt(it) => Some(it),
280         Definition::SelfType(it) => it.self_ty(db).as_adt(),
281         _ => None,
282     }?;
283     adt.try_to_nav(db).map(to_action)
284 }
285
286 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
287     match def {
288         Definition::Function(it) => it.try_to_nav(db).map(|nav_target| {
289             HoverAction::Reference(FilePosition {
290                 file_id: nav_target.file_id,
291                 offset: nav_target.focus_or_full_range().start(),
292             })
293         }),
294         _ => None,
295     }
296 }
297
298 fn runnable_action(
299     sema: &hir::Semantics<'_, RootDatabase>,
300     def: Definition,
301     file_id: FileId,
302 ) -> Option<HoverAction> {
303     match def {
304         Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
305         Definition::Function(func) => {
306             let src = func.source(sema.db)?;
307             if src.file_id != file_id.into() {
308                 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
309                 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
310                 return None;
311             }
312
313             runnable_fn(sema, func).map(HoverAction::Runnable)
314         }
315         _ => None,
316     }
317 }
318
319 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
320     let mut targets: Vec<hir::ModuleDef> = Vec::new();
321     let mut push_new_def = |item: hir::ModuleDef| {
322         if !targets.contains(&item) {
323             targets.push(item);
324         }
325     };
326
327     if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
328         it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
329     } else {
330         let ty = match def {
331             Definition::Local(it) => it.ty(db),
332             Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
333             Definition::Field(field) => field.ty(db),
334             Definition::Function(function) => function.ret_type(db),
335             _ => return None,
336         };
337
338         walk_and_push_ty(db, &ty, &mut push_new_def);
339     }
340
341     Some(HoverAction::goto_type_from_targets(db, targets))
342 }
343
344 fn walk_and_push_ty(
345     db: &RootDatabase,
346     ty: &hir::Type,
347     push_new_def: &mut dyn FnMut(hir::ModuleDef),
348 ) {
349     ty.walk(db, |t| {
350         if let Some(adt) = t.as_adt() {
351             push_new_def(adt.into());
352         } else if let Some(trait_) = t.as_dyn_trait() {
353             push_new_def(trait_.into());
354         } else if let Some(traits) = t.as_impl_traits(db) {
355             traits.for_each(|it| push_new_def(it.into()));
356         } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
357             push_new_def(trait_.into());
358         }
359     });
360 }
361
362 fn dedupe_or_merge_hover_actions(actions: Vec<HoverAction>) -> Vec<HoverAction> {
363     let mut deduped_actions = Vec::with_capacity(actions.len());
364     let mut go_to_type_targets = FxIndexSet::default();
365
366     let mut seen_implementation = false;
367     let mut seen_reference = false;
368     let mut seen_runnable = false;
369     for action in actions {
370         match action {
371             HoverAction::GoToType(targets) => {
372                 go_to_type_targets.extend(targets);
373             }
374             HoverAction::Implementation(..) => {
375                 if !seen_implementation {
376                     seen_implementation = true;
377                     deduped_actions.push(action);
378                 }
379             }
380             HoverAction::Reference(..) => {
381                 if !seen_reference {
382                     seen_reference = true;
383                     deduped_actions.push(action);
384                 }
385             }
386             HoverAction::Runnable(..) => {
387                 if !seen_runnable {
388                     seen_runnable = true;
389                     deduped_actions.push(action);
390                 }
391             }
392         };
393     }
394
395     if !go_to_type_targets.is_empty() {
396         deduped_actions.push(HoverAction::GoToType(go_to_type_targets.into_iter().collect()));
397     }
398
399     deduped_actions
400 }