]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/hover.rs
Merge #10387
[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     RootDatabase,
15 };
16 use itertools::Itertools;
17 use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxNode, SyntaxToken, T};
18
19 use crate::{
20     display::TryToNav,
21     doc_links::token_as_doc_comment,
22     markup::Markup,
23     runnables::{runnable_fn, runnable_mod},
24     FileId, FilePosition, NavigationTarget, RangeInfo, Runnable,
25 };
26
27 #[derive(Clone, Debug, PartialEq, Eq)]
28 pub struct HoverConfig {
29     pub links_in_hover: bool,
30     pub documentation: Option<HoverDocFormat>,
31 }
32
33 impl HoverConfig {
34     fn markdown(&self) -> bool {
35         matches!(self.documentation, Some(HoverDocFormat::Markdown))
36     }
37 }
38
39 #[derive(Clone, Debug, PartialEq, Eq)]
40 pub enum HoverDocFormat {
41     Markdown,
42     PlainText,
43 }
44
45 #[derive(Debug, Clone)]
46 pub enum HoverAction {
47     Runnable(Runnable),
48     Implementation(FilePosition),
49     Reference(FilePosition),
50     GoToType(Vec<HoverGotoTypeData>),
51 }
52
53 impl HoverAction {
54     fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
55         let targets = targets
56             .into_iter()
57             .filter_map(|it| {
58                 Some(HoverGotoTypeData {
59                     mod_path: render::path(
60                         db,
61                         it.module(db)?,
62                         it.name(db).map(|name| name.to_string()),
63                     ),
64                     nav: it.try_to_nav(db)?,
65                 })
66             })
67             .collect();
68         HoverAction::GoToType(targets)
69     }
70 }
71
72 #[derive(Debug, Clone, Eq, PartialEq)]
73 pub struct HoverGotoTypeData {
74     pub mod_path: String,
75     pub nav: NavigationTarget,
76 }
77
78 /// Contains the results when hovering over an item
79 #[derive(Debug, Default)]
80 pub struct HoverResult {
81     pub markup: Markup,
82     pub actions: Vec<HoverAction>,
83 }
84
85 // Feature: Hover
86 //
87 // Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
88 // Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
89 //
90 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
91 pub(crate) fn hover(
92     db: &RootDatabase,
93     FileRange { file_id, range }: FileRange,
94     config: &HoverConfig,
95 ) -> Option<RangeInfo<HoverResult>> {
96     let sema = &hir::Semantics::new(db);
97     let file = sema.parse(file_id).syntax().clone();
98
99     if !range.is_empty() {
100         return hover_ranged(&file, range, sema, config);
101     }
102     let offset = range.start();
103
104     let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
105         IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] => 3,
106         T!['('] | T![')'] => 2,
107         kind if kind.is_trivia() => 0,
108         _ => 1,
109     })?;
110
111     if let Some(doc_comment) = token_as_doc_comment(&original_token) {
112         cov_mark::hit!(no_highlight_on_comment_hover);
113         return doc_comment.get_definition_with_descend_at(sema, offset, |def, node, range| {
114             let res = hover_for_definition(sema, file_id, def, &node, config)?;
115             Some(RangeInfo::new(range, res))
116         });
117     }
118
119     let descended = sema.descend_into_macros(original_token.clone());
120
121     // FIXME: Definition should include known lints and the like instead of having this special case here
122     if let Some(res) = descended.iter().find_map(|token| {
123         let attr = token.ancestors().find_map(ast::Attr::cast)?;
124         render::try_for_lint(&attr, token)
125     }) {
126         return Some(RangeInfo::new(original_token.text_range(), res));
127     }
128
129     let result = descended
130         .iter()
131         .filter_map(|token| {
132             let node = token.parent()?;
133             let defs = Definition::from_token(sema, token);
134             Some(defs.into_iter().zip(iter::once(node).cycle()))
135         })
136         .flatten()
137         .unique_by(|&(def, _)| def)
138         .filter_map(|(def, node)| hover_for_definition(sema, file_id, def, &node, config))
139         .reduce(|mut acc, HoverResult { markup, actions }| {
140             acc.actions.extend(actions);
141             acc.markup = Markup::from(format!("{}\n---\n{}", acc.markup, markup));
142             acc
143         });
144     if result.is_none() {
145         // fallbacks, show keywords or types
146         if let Some(res) = render::keyword(sema, config, &original_token) {
147             return Some(RangeInfo::new(original_token.text_range(), res));
148         }
149         if let res @ Some(_) =
150             descended.iter().find_map(|token| hover_type_fallback(sema, config, token))
151         {
152             return res;
153         }
154     }
155     result.map(|res| RangeInfo::new(original_token.text_range(), res))
156 }
157
158 pub(crate) fn hover_for_definition(
159     sema: &Semantics<RootDatabase>,
160     file_id: FileId,
161     definition: Definition,
162     node: &SyntaxNode,
163     config: &HoverConfig,
164 ) -> Option<HoverResult> {
165     let famous_defs = match &definition {
166         Definition::ModuleDef(hir::ModuleDef::BuiltinType(_)) => {
167             Some(FamousDefs(sema, sema.scope(node).krate()))
168         }
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::ModuleDef(hir::ModuleDef::Trait(it)) => {
264             return it.try_to_nav(db).map(to_action)
265         }
266         Definition::ModuleDef(hir::ModuleDef::Adt(it)) => Some(it),
267         Definition::SelfType(it) => it.self_ty(db).as_adt(),
268         _ => None,
269     }?;
270     adt.try_to_nav(db).map(to_action)
271 }
272
273 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
274     match def {
275         Definition::ModuleDef(hir::ModuleDef::Function(it)) => {
276             it.try_to_nav(db).map(|nav_target| {
277                 HoverAction::Reference(FilePosition {
278                     file_id: nav_target.file_id,
279                     offset: nav_target.focus_or_full_range().start(),
280                 })
281             })
282         }
283         _ => None,
284     }
285 }
286
287 fn runnable_action(
288     sema: &hir::Semantics<RootDatabase>,
289     def: Definition,
290     file_id: FileId,
291 ) -> Option<HoverAction> {
292     match def {
293         Definition::ModuleDef(it) => match it {
294             hir::ModuleDef::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
295             hir::ModuleDef::Function(func) => {
296                 let src = func.source(sema.db)?;
297                 if src.file_id != file_id.into() {
298                     cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
299                     cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
300                     return None;
301                 }
302
303                 runnable_fn(sema, func).map(HoverAction::Runnable)
304             }
305             _ => None,
306         },
307         _ => None,
308     }
309 }
310
311 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
312     let mut targets: Vec<hir::ModuleDef> = Vec::new();
313     let mut push_new_def = |item: hir::ModuleDef| {
314         if !targets.contains(&item) {
315             targets.push(item);
316         }
317     };
318
319     if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
320         it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
321     } else {
322         let ty = match def {
323             Definition::Local(it) => it.ty(db),
324             Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
325             Definition::Field(field) => field.ty(db),
326             _ => return None,
327         };
328
329         walk_and_push_ty(db, &ty, &mut push_new_def);
330     }
331
332     Some(HoverAction::goto_type_from_targets(db, targets))
333 }
334
335 fn walk_and_push_ty(
336     db: &RootDatabase,
337     ty: &hir::Type,
338     push_new_def: &mut dyn FnMut(hir::ModuleDef),
339 ) {
340     ty.walk(db, |t| {
341         if let Some(adt) = t.as_adt() {
342             push_new_def(adt.into());
343         } else if let Some(trait_) = t.as_dyn_trait() {
344             push_new_def(trait_.into());
345         } else if let Some(traits) = t.as_impl_traits(db) {
346             traits.into_iter().for_each(|it| push_new_def(it.into()));
347         } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
348             push_new_def(trait_.into());
349         }
350     });
351 }