]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/hover.rs
2ebf46b56499d49cf1ed94e2003fdb78a672871b
[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::BuiltinType(_) => Some(FamousDefs(sema, sema.scope(node).krate())),
167         _ => None,
168     };
169     if let Some(markup) = render::definition(sema.db, definition, famous_defs.as_ref(), config) {
170         let mut res = HoverResult::default();
171         res.markup = render::process_markup(sema.db, definition, &markup, config);
172         if let Some(action) = show_implementations_action(sema.db, definition) {
173             res.actions.push(action);
174         }
175
176         if let Some(action) = show_fn_references_action(sema.db, definition) {
177             res.actions.push(action);
178         }
179
180         if let Some(action) = runnable_action(sema, definition, file_id) {
181             res.actions.push(action);
182         }
183
184         if let Some(action) = goto_type_action_for_def(sema.db, definition) {
185             res.actions.push(action);
186         }
187         return Some(res);
188     }
189     None
190 }
191
192 fn hover_ranged(
193     file: &SyntaxNode,
194     range: syntax::TextRange,
195     sema: &Semantics<RootDatabase>,
196     config: &HoverConfig,
197 ) -> Option<RangeInfo<HoverResult>> {
198     let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
199         match_ast! {
200             match it {
201                 ast::Expr(expr) => Some(Either::Left(expr)),
202                 ast::Pat(pat) => Some(Either::Right(pat)),
203                 _ => None,
204             }
205         }
206     })?;
207     let res = match &expr_or_pat {
208         Either::Left(ast::Expr::TryExpr(try_expr)) => render::try_expr(sema, config, try_expr),
209         Either::Left(ast::Expr::PrefixExpr(prefix_expr))
210             if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
211         {
212             render::deref_expr(sema, config, prefix_expr)
213         }
214         _ => None,
215     };
216     let res = res.or_else(|| render::type_info(sema, config, &expr_or_pat));
217     res.map(|it| {
218         let range = match expr_or_pat {
219             Either::Left(it) => it.syntax().text_range(),
220             Either::Right(it) => it.syntax().text_range(),
221         };
222         RangeInfo::new(range, it)
223     })
224 }
225
226 fn hover_type_fallback(
227     sema: &Semantics<RootDatabase>,
228     config: &HoverConfig,
229     token: &SyntaxToken,
230 ) -> Option<RangeInfo<HoverResult>> {
231     let node = token
232         .ancestors()
233         .take_while(|it| !ast::Item::can_cast(it.kind()))
234         .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
235
236     let expr_or_pat = match_ast! {
237         match node {
238             ast::Expr(it) => Either::Left(it),
239             ast::Pat(it) => Either::Right(it),
240             // If this node is a MACRO_CALL, it means that `descend_into_macros_many` failed to resolve.
241             // (e.g expanding a builtin macro). So we give up here.
242             ast::MacroCall(_it) => return None,
243             _ => return None,
244         }
245     };
246
247     let res = render::type_info(sema, config, &expr_or_pat)?;
248     let range = sema.original_range(&node).range;
249     Some(RangeInfo::new(range, res))
250 }
251
252 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
253     fn to_action(nav_target: NavigationTarget) -> HoverAction {
254         HoverAction::Implementation(FilePosition {
255             file_id: nav_target.file_id,
256             offset: nav_target.focus_or_full_range().start(),
257         })
258     }
259
260     let adt = match def {
261         Definition::Trait(it) => return it.try_to_nav(db).map(to_action),
262         Definition::Adt(it) => Some(it),
263         Definition::SelfType(it) => it.self_ty(db).as_adt(),
264         _ => None,
265     }?;
266     adt.try_to_nav(db).map(to_action)
267 }
268
269 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
270     match def {
271         Definition::Function(it) => it.try_to_nav(db).map(|nav_target| {
272             HoverAction::Reference(FilePosition {
273                 file_id: nav_target.file_id,
274                 offset: nav_target.focus_or_full_range().start(),
275             })
276         }),
277         _ => None,
278     }
279 }
280
281 fn runnable_action(
282     sema: &hir::Semantics<RootDatabase>,
283     def: Definition,
284     file_id: FileId,
285 ) -> Option<HoverAction> {
286     match def {
287         Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
288         Definition::Function(func) => {
289             let src = func.source(sema.db)?;
290             if src.file_id != file_id.into() {
291                 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
292                 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
293                 return None;
294             }
295
296             runnable_fn(sema, func).map(HoverAction::Runnable)
297         }
298         _ => None,
299     }
300 }
301
302 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
303     let mut targets: Vec<hir::ModuleDef> = Vec::new();
304     let mut push_new_def = |item: hir::ModuleDef| {
305         if !targets.contains(&item) {
306             targets.push(item);
307         }
308     };
309
310     if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
311         it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
312     } else {
313         let ty = match def {
314             Definition::Local(it) => it.ty(db),
315             Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
316             Definition::Field(field) => field.ty(db),
317             Definition::Function(function) => function.ret_type(db),
318             _ => return None,
319         };
320
321         walk_and_push_ty(db, &ty, &mut push_new_def);
322     }
323
324     Some(HoverAction::goto_type_from_targets(db, targets))
325 }
326
327 fn walk_and_push_ty(
328     db: &RootDatabase,
329     ty: &hir::Type,
330     push_new_def: &mut dyn FnMut(hir::ModuleDef),
331 ) {
332     ty.walk(db, |t| {
333         if let Some(adt) = t.as_adt() {
334             push_new_def(adt.into());
335         } else if let Some(trait_) = t.as_dyn_trait() {
336             push_new_def(trait_.into());
337         } else if let Some(traits) = t.as_impl_traits(db) {
338             traits.into_iter().for_each(|it| push_new_def(it.into()));
339         } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
340             push_new_def(trait_.into());
341         }
342     });
343 }