]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide/src/hover.rs
Auto merge of #107843 - bjorn3:sync_cg_clif-2023-02-09, r=bjorn3
[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     pub keywords: bool,
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, Hash)]
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] | T![Self] => 4,
106         // index and prefix ops
107         T!['['] | T![']'] | T![?] | T![*] | T![-] | T![!] => 3,
108         kind if kind.is_keyword() => 2,
109         T!['('] | T![')'] => 2,
110         kind if kind.is_trivia() => 0,
111         _ => 1,
112     })?;
113
114     if let Some(doc_comment) = token_as_doc_comment(&original_token) {
115         cov_mark::hit!(no_highlight_on_comment_hover);
116         return doc_comment.get_definition_with_descend_at(sema, offset, |def, node, range| {
117             let res = hover_for_definition(sema, file_id, def, &node, config)?;
118             Some(RangeInfo::new(range, res))
119         });
120     }
121
122     let in_attr = original_token
123         .parent_ancestors()
124         .filter_map(ast::Item::cast)
125         .any(|item| sema.is_attr_macro_call(&item))
126         && !matches!(
127             original_token.parent().and_then(ast::TokenTree::cast),
128             Some(tt) if tt.syntax().ancestors().any(|it| ast::Meta::can_cast(it.kind()))
129         );
130
131     // prefer descending the same token kind in attribute expansions, in normal macros text
132     // equivalency is more important
133     let descended = if in_attr {
134         [sema.descend_into_macros_with_kind_preference(original_token.clone())].into()
135     } else {
136         sema.descend_into_macros_with_same_text(original_token.clone())
137     };
138
139     // try lint hover
140     let result = descended
141         .iter()
142         .find_map(|token| {
143             // FIXME: Definition should include known lints and the like instead of having this special case here
144             let attr = token.parent_ancestors().find_map(ast::Attr::cast)?;
145             render::try_for_lint(&attr, token)
146         })
147         // try item definitions
148         .or_else(|| {
149             descended
150                 .iter()
151                 .filter_map(|token| {
152                     let node = token.parent()?;
153                     let class = IdentClass::classify_token(sema, token)?;
154                     if let IdentClass::Operator(OperatorClass::Await(_)) = class {
155                         // It's better for us to fall back to the keyword hover here,
156                         // rendering poll is very confusing
157                         return None;
158                     }
159                     Some(class.definitions().into_iter().zip(iter::once(node).cycle()))
160                 })
161                 .flatten()
162                 .unique_by(|&(def, _)| def)
163                 .filter_map(|(def, node)| hover_for_definition(sema, file_id, def, &node, config))
164                 .reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
165                     acc.actions.extend(actions);
166                     acc.markup = Markup::from(format!("{}\n---\n{markup}", acc.markup));
167                     acc
168                 })
169         })
170         // try keywords
171         .or_else(|| descended.iter().find_map(|token| render::keyword(sema, config, token)))
172         // try rest item hover
173         .or_else(|| {
174             descended.iter().find_map(|token| {
175                 if token.kind() != DOT2 {
176                     return None;
177                 }
178
179                 let rest_pat = token.parent().and_then(ast::RestPat::cast)?;
180                 let record_pat_field_list =
181                     rest_pat.syntax().parent().and_then(ast::RecordPatFieldList::cast)?;
182
183                 let record_pat =
184                     record_pat_field_list.syntax().parent().and_then(ast::RecordPat::cast)?;
185
186                 Some(render::struct_rest_pat(sema, config, &record_pat))
187             })
188         });
189
190     result
191         .map(|mut res: HoverResult| {
192             res.actions = dedupe_or_merge_hover_actions(res.actions);
193             RangeInfo::new(original_token.text_range(), res)
194         })
195         // fallback to type hover if there aren't any other suggestions
196         // this finds its own range instead of using the closest token's range
197         .or_else(|| {
198             descended.iter().find_map(|token| hover_type_fallback(sema, config, token, token))
199         })
200 }
201
202 pub(crate) fn hover_for_definition(
203     sema: &Semantics<'_, RootDatabase>,
204     file_id: FileId,
205     definition: Definition,
206     node: &SyntaxNode,
207     config: &HoverConfig,
208 ) -> Option<HoverResult> {
209     let famous_defs = match &definition {
210         Definition::BuiltinType(_) => Some(FamousDefs(sema, sema.scope(node)?.krate())),
211         _ => None,
212     };
213     render::definition(sema.db, definition, famous_defs.as_ref(), config).map(|markup| {
214         HoverResult {
215             markup: render::process_markup(sema.db, definition, &markup, config),
216             actions: show_implementations_action(sema.db, definition)
217                 .into_iter()
218                 .chain(show_fn_references_action(sema.db, definition))
219                 .chain(runnable_action(sema, definition, file_id))
220                 .chain(goto_type_action_for_def(sema.db, definition))
221                 .collect(),
222         }
223     })
224 }
225
226 fn hover_ranged(
227     file: &SyntaxNode,
228     range: syntax::TextRange,
229     sema: &Semantics<'_, RootDatabase>,
230     config: &HoverConfig,
231 ) -> Option<RangeInfo<HoverResult>> {
232     // FIXME: make this work in attributes
233     let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
234         match_ast! {
235             match it {
236                 ast::Expr(expr) => Some(Either::Left(expr)),
237                 ast::Pat(pat) => Some(Either::Right(pat)),
238                 _ => None,
239             }
240         }
241     })?;
242     let res = match &expr_or_pat {
243         Either::Left(ast::Expr::TryExpr(try_expr)) => render::try_expr(sema, config, try_expr),
244         Either::Left(ast::Expr::PrefixExpr(prefix_expr))
245             if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
246         {
247             render::deref_expr(sema, config, prefix_expr)
248         }
249         _ => None,
250     };
251     let res = res.or_else(|| render::type_info(sema, config, &expr_or_pat));
252     res.map(|it| {
253         let range = match expr_or_pat {
254             Either::Left(it) => it.syntax().text_range(),
255             Either::Right(it) => it.syntax().text_range(),
256         };
257         RangeInfo::new(range, it)
258     })
259 }
260
261 fn hover_type_fallback(
262     sema: &Semantics<'_, RootDatabase>,
263     config: &HoverConfig,
264     token: &SyntaxToken,
265     original_token: &SyntaxToken,
266 ) -> Option<RangeInfo<HoverResult>> {
267     let node =
268         token.parent_ancestors().take_while(|it| !ast::Item::can_cast(it.kind())).find(|n| {
269             ast::Expr::can_cast(n.kind())
270                 || ast::Pat::can_cast(n.kind())
271                 || ast::Type::can_cast(n.kind())
272         })?;
273
274     let expr_or_pat = match_ast! {
275         match node {
276             ast::Expr(it) => Either::Left(it),
277             ast::Pat(it) => Either::Right(it),
278             // If this node is a MACRO_CALL, it means that `descend_into_macros_many` failed to resolve.
279             // (e.g expanding a builtin macro). So we give up here.
280             ast::MacroCall(_it) => return None,
281             _ => return None,
282         }
283     };
284
285     let res = render::type_info(sema, config, &expr_or_pat)?;
286
287     let range = sema
288         .original_range_opt(&node)
289         .map(|frange| frange.range)
290         .unwrap_or_else(|| original_token.text_range());
291     Some(RangeInfo::new(range, res))
292 }
293
294 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
295     fn to_action(nav_target: NavigationTarget) -> HoverAction {
296         HoverAction::Implementation(FilePosition {
297             file_id: nav_target.file_id,
298             offset: nav_target.focus_or_full_range().start(),
299         })
300     }
301
302     let adt = match def {
303         Definition::Trait(it) => return it.try_to_nav(db).map(to_action),
304         Definition::Adt(it) => Some(it),
305         Definition::SelfType(it) => it.self_ty(db).as_adt(),
306         _ => None,
307     }?;
308     adt.try_to_nav(db).map(to_action)
309 }
310
311 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
312     match def {
313         Definition::Function(it) => it.try_to_nav(db).map(|nav_target| {
314             HoverAction::Reference(FilePosition {
315                 file_id: nav_target.file_id,
316                 offset: nav_target.focus_or_full_range().start(),
317             })
318         }),
319         _ => None,
320     }
321 }
322
323 fn runnable_action(
324     sema: &hir::Semantics<'_, RootDatabase>,
325     def: Definition,
326     file_id: FileId,
327 ) -> Option<HoverAction> {
328     match def {
329         Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
330         Definition::Function(func) => {
331             let src = func.source(sema.db)?;
332             if src.file_id != file_id.into() {
333                 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
334                 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
335                 return None;
336             }
337
338             runnable_fn(sema, func).map(HoverAction::Runnable)
339         }
340         _ => None,
341     }
342 }
343
344 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
345     let mut targets: Vec<hir::ModuleDef> = Vec::new();
346     let mut push_new_def = |item: hir::ModuleDef| {
347         if !targets.contains(&item) {
348             targets.push(item);
349         }
350     };
351
352     if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
353         it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
354     } else {
355         let ty = match def {
356             Definition::Local(it) => it.ty(db),
357             Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
358             Definition::Field(field) => field.ty(db),
359             Definition::Function(function) => function.ret_type(db),
360             _ => return None,
361         };
362
363         walk_and_push_ty(db, &ty, &mut push_new_def);
364     }
365
366     Some(HoverAction::goto_type_from_targets(db, targets))
367 }
368
369 fn walk_and_push_ty(
370     db: &RootDatabase,
371     ty: &hir::Type,
372     push_new_def: &mut dyn FnMut(hir::ModuleDef),
373 ) {
374     ty.walk(db, |t| {
375         if let Some(adt) = t.as_adt() {
376             push_new_def(adt.into());
377         } else if let Some(trait_) = t.as_dyn_trait() {
378             push_new_def(trait_.into());
379         } else if let Some(traits) = t.as_impl_traits(db) {
380             traits.for_each(|it| push_new_def(it.into()));
381         } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
382             push_new_def(trait_.into());
383         }
384     });
385 }
386
387 fn dedupe_or_merge_hover_actions(actions: Vec<HoverAction>) -> Vec<HoverAction> {
388     let mut deduped_actions = Vec::with_capacity(actions.len());
389     let mut go_to_type_targets = FxIndexSet::default();
390
391     let mut seen_implementation = false;
392     let mut seen_reference = false;
393     let mut seen_runnable = false;
394     for action in actions {
395         match action {
396             HoverAction::GoToType(targets) => {
397                 go_to_type_targets.extend(targets);
398             }
399             HoverAction::Implementation(..) => {
400                 if !seen_implementation {
401                     seen_implementation = true;
402                     deduped_actions.push(action);
403                 }
404             }
405             HoverAction::Reference(..) => {
406                 if !seen_reference {
407                     seen_reference = true;
408                     deduped_actions.push(action);
409                 }
410             }
411             HoverAction::Runnable(..) => {
412                 if !seen_runnable {
413                     seen_runnable = true;
414                     deduped_actions.push(action);
415                 }
416             }
417         };
418     }
419
420     if !go_to_type_targets.is_empty() {
421         deduped_actions.push(HoverAction::GoToType(go_to_type_targets.into_iter().collect()));
422     }
423
424     deduped_actions
425 }