9 use hir::{HasSource, Semantics};
12 defs::{Definition, IdentClass},
13 helpers::{pick_best_token, FamousDefs},
14 FxIndexSet, RootDatabase,
16 use itertools::Itertools;
17 use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxNode, SyntaxToken, T};
20 doc_links::token_as_doc_comment,
22 runnables::{runnable_fn, runnable_mod},
23 FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, TryToNav,
25 #[derive(Clone, Debug, PartialEq, Eq)]
26 pub struct HoverConfig {
27 pub links_in_hover: bool,
28 pub documentation: Option<HoverDocFormat>,
32 fn markdown(&self) -> bool {
33 matches!(self.documentation, Some(HoverDocFormat::Markdown))
37 #[derive(Clone, Debug, PartialEq, Eq)]
38 pub enum HoverDocFormat {
43 #[derive(Debug, Clone)]
44 pub enum HoverAction {
46 Implementation(FilePosition),
47 Reference(FilePosition),
48 GoToType(Vec<HoverGotoTypeData>),
52 fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
56 Some(HoverGotoTypeData {
57 mod_path: render::path(
60 it.name(db).map(|name| name.to_string()),
62 nav: it.try_to_nav(db)?,
66 HoverAction::GoToType(targets)
70 #[derive(Debug, Clone, Eq, PartialEq, Hash)]
71 pub struct HoverGotoTypeData {
73 pub nav: NavigationTarget,
76 /// Contains the results when hovering over an item
77 #[derive(Debug, Default)]
78 pub struct HoverResult {
80 pub actions: Vec<HoverAction>,
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.
88 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
91 FileRange { file_id, range }: FileRange,
93 ) -> Option<RangeInfo<HoverResult>> {
94 let sema = &hir::Semantics::new(db);
95 let file = sema.parse(file_id).syntax().clone();
97 if !range.is_empty() {
98 return hover_ranged(&file, range, sema, config);
100 let offset = range.start();
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,
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))
117 let descended = sema.descend_into_macros(original_token.clone());
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)
124 if let Some(res) = hovered_lint {
125 return Some(RangeInfo::new(original_token.text_range(), res));
128 let result = descended
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()))
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));
144 if result.is_none() {
145 // fallbacks, show keywords or types
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));
153 .find_map(|token| hover_type_fallback(sema, config, token, &original_token));
154 if let res @ Some(_) = res {
158 result.map(|mut res: HoverResult| {
159 res.actions = dedupe_or_merge_hover_actions(res.actions);
160 RangeInfo::new(original_token.text_range(), res)
164 pub(crate) fn hover_for_definition(
165 sema: &Semantics<RootDatabase>,
167 definition: Definition,
169 config: &HoverConfig,
170 ) -> Option<HoverResult> {
171 let famous_defs = match &definition {
172 Definition::BuiltinType(_) => Some(FamousDefs(sema, sema.scope(node).krate())),
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);
182 if let Some(action) = show_fn_references_action(sema.db, definition) {
183 res.actions.push(action);
186 if let Some(action) = runnable_action(sema, definition, file_id) {
187 res.actions.push(action);
190 if let Some(action) = goto_type_action_for_def(sema.db, definition) {
191 res.actions.push(action);
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| {
208 ast::Expr(expr) => Some(Either::Left(expr)),
209 ast::Pat(pat) => Some(Either::Right(pat)),
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) =>
219 render::deref_expr(sema, config, prefix_expr)
223 let res = res.or_else(|| render::type_info(sema, config, &expr_or_pat));
225 let range = match expr_or_pat {
226 Either::Left(it) => it.syntax().text_range(),
227 Either::Right(it) => it.syntax().text_range(),
229 RangeInfo::new(range, it)
233 fn hover_type_fallback(
234 sema: &Semantics<RootDatabase>,
235 config: &HoverConfig,
237 original_token: &SyntaxToken,
238 ) -> Option<RangeInfo<HoverResult>> {
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()))?;
244 let expr_or_pat = match_ast! {
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,
255 let res = render::type_info(sema, config, &expr_or_pat)?;
257 .original_range_opt(&node)
258 .map(|frange| frange.range)
259 .unwrap_or_else(|| original_token.text_range());
260 Some(RangeInfo::new(range, res))
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(),
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(),
277 adt.try_to_nav(db).map(to_action)
280 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
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(),
293 sema: &hir::Semantics<RootDatabase>,
296 ) -> Option<HoverAction> {
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);
307 runnable_fn(sema, func).map(HoverAction::Runnable)
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) {
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()));
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),
332 walk_and_push_ty(db, &ty, &mut push_new_def);
335 Some(HoverAction::goto_type_from_targets(db, targets))
341 push_new_def: &mut dyn FnMut(hir::ModuleDef),
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());
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();
360 let mut seen_implementation = false;
361 let mut seen_reference = false;
362 let mut seen_runnable = false;
363 for action in actions {
365 HoverAction::GoToType(targets) => {
366 go_to_type_targets.extend(targets);
368 HoverAction::Implementation(..) => {
369 if !seen_implementation {
370 seen_implementation = true;
371 deduped_actions.push(action);
374 HoverAction::Reference(..) => {
376 seen_reference = true;
377 deduped_actions.push(action);
380 HoverAction::Runnable(..) => {
382 seen_runnable = true;
383 deduped_actions.push(action);
389 if !go_to_type_targets.is_empty() {
390 deduped_actions.push(HoverAction::GoToType(go_to_type_targets.into_iter().collect()));