]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/hover.rs
Merge #11424
[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, IdentClass},
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     let hovered_lint = descended.iter().find_map(|token| {
121         let attr = token.ancestors().find_map(ast::Attr::cast)?;
122         render::try_for_lint(&attr, token)
123     });
124     if let Some(res) = hovered_lint {
125         return Some(RangeInfo::new(original_token.text_range(), res));
126     }
127
128     let result = descended
129         .iter()
130         .filter_map(|token| {
131             let node = token.parent()?;
132             let class = IdentClass::classify_token(sema, token)?;
133             Some(class.definitions().into_iter().zip(iter::once(node).cycle()))
134         })
135         .flatten()
136         .unique_by(|&(def, _)| def)
137         .filter_map(|(def, node)| hover_for_definition(sema, file_id, def, &node, config))
138         .reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
139             acc.actions.extend(actions);
140             acc.markup = Markup::from(format!("{}\n---\n{}", acc.markup, markup));
141             acc
142         });
143
144     if result.is_none() {
145         // fallbacks, show keywords or types
146
147         let res = descended.iter().find_map(|token| render::keyword(sema, config, &token));
148         if let Some(res) = res {
149             return Some(RangeInfo::new(original_token.text_range(), res));
150         }
151         let res = descended
152             .iter()
153             .find_map(|token| hover_type_fallback(sema, config, token, &original_token));
154         if let res @ Some(_) = res {
155             return res;
156         }
157     }
158     result.map(|mut res: HoverResult| {
159         res.actions = dedupe_or_merge_hover_actions(res.actions);
160         RangeInfo::new(original_token.text_range(), res)
161     })
162 }
163
164 pub(crate) fn hover_for_definition(
165     sema: &Semantics<RootDatabase>,
166     file_id: FileId,
167     definition: Definition,
168     node: &SyntaxNode,
169     config: &HoverConfig,
170 ) -> Option<HoverResult> {
171     let famous_defs = match &definition {
172         Definition::BuiltinType(_) => Some(FamousDefs(sema, sema.scope(node).krate())),
173         _ => None,
174     };
175     if let Some(markup) = render::definition(sema.db, definition, famous_defs.as_ref(), config) {
176         let mut res = HoverResult::default();
177         res.markup = render::process_markup(sema.db, definition, &markup, config);
178         if let Some(action) = show_implementations_action(sema.db, definition) {
179             res.actions.push(action);
180         }
181
182         if let Some(action) = show_fn_references_action(sema.db, definition) {
183             res.actions.push(action);
184         }
185
186         if let Some(action) = runnable_action(sema, definition, file_id) {
187             res.actions.push(action);
188         }
189
190         if let Some(action) = goto_type_action_for_def(sema.db, definition) {
191             res.actions.push(action);
192         }
193         return Some(res);
194     }
195     None
196 }
197
198 fn hover_ranged(
199     file: &SyntaxNode,
200     range: syntax::TextRange,
201     sema: &Semantics<RootDatabase>,
202     config: &HoverConfig,
203 ) -> Option<RangeInfo<HoverResult>> {
204     // FIXME: make this work in attributes
205     let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
206         match_ast! {
207             match it {
208                 ast::Expr(expr) => Some(Either::Left(expr)),
209                 ast::Pat(pat) => Some(Either::Right(pat)),
210                 _ => None,
211             }
212         }
213     })?;
214     let res = match &expr_or_pat {
215         Either::Left(ast::Expr::TryExpr(try_expr)) => render::try_expr(sema, config, try_expr),
216         Either::Left(ast::Expr::PrefixExpr(prefix_expr))
217             if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
218         {
219             render::deref_expr(sema, config, prefix_expr)
220         }
221         _ => None,
222     };
223     let res = res.or_else(|| render::type_info(sema, config, &expr_or_pat));
224     res.map(|it| {
225         let range = match expr_or_pat {
226             Either::Left(it) => it.syntax().text_range(),
227             Either::Right(it) => it.syntax().text_range(),
228         };
229         RangeInfo::new(range, it)
230     })
231 }
232
233 fn hover_type_fallback(
234     sema: &Semantics<RootDatabase>,
235     config: &HoverConfig,
236     token: &SyntaxToken,
237     original_token: &SyntaxToken,
238 ) -> Option<RangeInfo<HoverResult>> {
239     let node = token
240         .ancestors()
241         .take_while(|it| !ast::Item::can_cast(it.kind()))
242         .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
243
244     let expr_or_pat = match_ast! {
245         match node {
246             ast::Expr(it) => Either::Left(it),
247             ast::Pat(it) => Either::Right(it),
248             // If this node is a MACRO_CALL, it means that `descend_into_macros_many` failed to resolve.
249             // (e.g expanding a builtin macro). So we give up here.
250             ast::MacroCall(_it) => return None,
251             _ => return None,
252         }
253     };
254
255     let res = render::type_info(sema, config, &expr_or_pat)?;
256     let range = sema
257         .original_range_opt(&node)
258         .map(|frange| frange.range)
259         .unwrap_or_else(|| original_token.text_range());
260     Some(RangeInfo::new(range, res))
261 }
262
263 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
264     fn to_action(nav_target: NavigationTarget) -> HoverAction {
265         HoverAction::Implementation(FilePosition {
266             file_id: nav_target.file_id,
267             offset: nav_target.focus_or_full_range().start(),
268         })
269     }
270
271     let adt = match def {
272         Definition::Trait(it) => return it.try_to_nav(db).map(to_action),
273         Definition::Adt(it) => Some(it),
274         Definition::SelfType(it) => it.self_ty(db).as_adt(),
275         _ => None,
276     }?;
277     adt.try_to_nav(db).map(to_action)
278 }
279
280 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
281     match def {
282         Definition::Function(it) => it.try_to_nav(db).map(|nav_target| {
283             HoverAction::Reference(FilePosition {
284                 file_id: nav_target.file_id,
285                 offset: nav_target.focus_or_full_range().start(),
286             })
287         }),
288         _ => None,
289     }
290 }
291
292 fn runnable_action(
293     sema: &hir::Semantics<RootDatabase>,
294     def: Definition,
295     file_id: FileId,
296 ) -> Option<HoverAction> {
297     match def {
298         Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
299         Definition::Function(func) => {
300             let src = func.source(sema.db)?;
301             if src.file_id != file_id.into() {
302                 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
303                 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
304                 return None;
305             }
306
307             runnable_fn(sema, func).map(HoverAction::Runnable)
308         }
309         _ => None,
310     }
311 }
312
313 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
314     let mut targets: Vec<hir::ModuleDef> = Vec::new();
315     let mut push_new_def = |item: hir::ModuleDef| {
316         if !targets.contains(&item) {
317             targets.push(item);
318         }
319     };
320
321     if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
322         it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
323     } else {
324         let ty = match def {
325             Definition::Local(it) => it.ty(db),
326             Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
327             Definition::Field(field) => field.ty(db),
328             Definition::Function(function) => function.ret_type(db),
329             _ => return None,
330         };
331
332         walk_and_push_ty(db, &ty, &mut push_new_def);
333     }
334
335     Some(HoverAction::goto_type_from_targets(db, targets))
336 }
337
338 fn walk_and_push_ty(
339     db: &RootDatabase,
340     ty: &hir::Type,
341     push_new_def: &mut dyn FnMut(hir::ModuleDef),
342 ) {
343     ty.walk(db, |t| {
344         if let Some(adt) = t.as_adt() {
345             push_new_def(adt.into());
346         } else if let Some(trait_) = t.as_dyn_trait() {
347             push_new_def(trait_.into());
348         } else if let Some(traits) = t.as_impl_traits(db) {
349             traits.for_each(|it| push_new_def(it.into()));
350         } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
351             push_new_def(trait_.into());
352         }
353     });
354 }
355
356 fn dedupe_or_merge_hover_actions(actions: Vec<HoverAction>) -> Vec<HoverAction> {
357     let mut deduped_actions = Vec::with_capacity(actions.len());
358     let mut go_to_type_targets = FxIndexSet::default();
359
360     let mut seen_implementation = false;
361     let mut seen_reference = false;
362     let mut seen_runnable = false;
363     for action in actions {
364         match action {
365             HoverAction::GoToType(targets) => {
366                 go_to_type_targets.extend(targets);
367             }
368             HoverAction::Implementation(..) => {
369                 if !seen_implementation {
370                     seen_implementation = true;
371                     deduped_actions.push(action);
372                 }
373             }
374             HoverAction::Reference(..) => {
375                 if !seen_reference {
376                     seen_reference = true;
377                     deduped_actions.push(action);
378                 }
379             }
380             HoverAction::Runnable(..) => {
381                 if !seen_runnable {
382                     seen_runnable = true;
383                     deduped_actions.push(action);
384                 }
385             }
386         };
387     }
388
389     if !go_to_type_targets.is_empty() {
390         deduped_actions.push(HoverAction::GoToType(go_to_type_targets.into_iter().collect()));
391     }
392
393     deduped_actions
394 }