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