9 use hir::{HasSource, Semantics};
12 defs::{Definition, IdentClass, OperatorClass},
13 famous_defs::FamousDefs,
14 helpers::pick_best_token,
15 FxIndexSet, RootDatabase,
17 use itertools::Itertools;
18 use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxNode, SyntaxToken, T};
21 doc_links::token_as_doc_comment,
23 runnables::{runnable_fn, runnable_mod},
24 FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, TryToNav,
26 #[derive(Clone, Debug, PartialEq, Eq)]
27 pub struct HoverConfig {
28 pub links_in_hover: bool,
29 pub documentation: Option<HoverDocFormat>,
34 fn markdown(&self) -> bool {
35 matches!(self.documentation, Some(HoverDocFormat::Markdown))
39 #[derive(Clone, Debug, PartialEq, Eq)]
40 pub enum HoverDocFormat {
45 #[derive(Debug, Clone)]
46 pub enum HoverAction {
48 Implementation(FilePosition),
49 Reference(FilePosition),
50 GoToType(Vec<HoverGotoTypeData>),
54 fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
58 Some(HoverGotoTypeData {
59 mod_path: render::path(
62 it.name(db).map(|name| name.to_string()),
64 nav: it.try_to_nav(db)?,
68 HoverAction::GoToType(targets)
72 #[derive(Debug, Clone, Eq, PartialEq, Hash)]
73 pub struct HoverGotoTypeData {
75 pub nav: NavigationTarget,
78 /// Contains the results when hovering over an item
79 #[derive(Debug, Default)]
80 pub struct HoverResult {
82 pub actions: Vec<HoverAction>,
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.
90 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
93 FileRange { file_id, range }: FileRange,
95 ) -> Option<RangeInfo<HoverResult>> {
96 let sema = &hir::Semantics::new(db);
97 let file = sema.parse(file_id).syntax().clone();
99 if !range.is_empty() {
100 return hover_ranged(&file, range, sema, config);
102 let offset = range.start();
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,
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))
122 let in_attr = original_token
124 .filter_map(ast::Item::cast)
125 .any(|item| sema.is_attr_macro_call(&item))
127 original_token.parent().and_then(ast::TokenTree::cast),
128 Some(tt) if tt.syntax().ancestors().any(|it| ast::Meta::can_cast(it.kind()))
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()
136 sema.descend_into_macros_with_same_text(original_token.clone())
140 let result = descended
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)
147 // try item definitions
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
159 Some(class.definitions().into_iter().zip(iter::once(node).cycle()))
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));
171 .or_else(|| descended.iter().find_map(|token| render::keyword(sema, config, token)))
172 // try rest item hover
174 descended.iter().find_map(|token| {
175 if token.kind() != DOT2 {
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)?;
184 record_pat_field_list.syntax().parent().and_then(ast::RecordPat::cast)?;
186 Some(render::struct_rest_pat(sema, config, &record_pat))
191 .map(|mut res: HoverResult| {
192 res.actions = dedupe_or_merge_hover_actions(res.actions);
193 RangeInfo::new(original_token.text_range(), res)
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
198 descended.iter().find_map(|token| hover_type_fallback(sema, config, token, token))
202 pub(crate) fn hover_for_definition(
203 sema: &Semantics<'_, RootDatabase>,
205 definition: Definition,
207 config: &HoverConfig,
208 ) -> Option<HoverResult> {
209 let famous_defs = match &definition {
210 Definition::BuiltinType(_) => Some(FamousDefs(sema, sema.scope(node)?.krate())),
213 render::definition(sema.db, definition, famous_defs.as_ref(), config).map(|markup| {
215 markup: render::process_markup(sema.db, definition, &markup, config),
216 actions: show_implementations_action(sema.db, definition)
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))
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| {
236 ast::Expr(expr) => Some(Either::Left(expr)),
237 ast::Pat(pat) => Some(Either::Right(pat)),
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) =>
247 render::deref_expr(sema, config, prefix_expr)
251 let res = res.or_else(|| render::type_info(sema, config, &expr_or_pat));
253 let range = match expr_or_pat {
254 Either::Left(it) => it.syntax().text_range(),
255 Either::Right(it) => it.syntax().text_range(),
257 RangeInfo::new(range, it)
261 fn hover_type_fallback(
262 sema: &Semantics<'_, RootDatabase>,
263 config: &HoverConfig,
265 original_token: &SyntaxToken,
266 ) -> Option<RangeInfo<HoverResult>> {
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())
274 let expr_or_pat = match_ast! {
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,
285 let res = render::type_info(sema, config, &expr_or_pat)?;
288 .original_range_opt(&node)
289 .map(|frange| frange.range)
290 .unwrap_or_else(|| original_token.text_range());
291 Some(RangeInfo::new(range, res))
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(),
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(),
308 adt.try_to_nav(db).map(to_action)
311 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
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(),
324 sema: &hir::Semantics<'_, RootDatabase>,
327 ) -> Option<HoverAction> {
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);
338 runnable_fn(sema, func).map(HoverAction::Runnable)
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) {
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()));
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),
363 walk_and_push_ty(db, &ty, &mut push_new_def);
366 Some(HoverAction::goto_type_from_targets(db, targets))
372 push_new_def: &mut dyn FnMut(hir::ModuleDef),
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());
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();
391 let mut seen_implementation = false;
392 let mut seen_reference = false;
393 let mut seen_runnable = false;
394 for action in actions {
396 HoverAction::GoToType(targets) => {
397 go_to_type_targets.extend(targets);
399 HoverAction::Implementation(..) => {
400 if !seen_implementation {
401 seen_implementation = true;
402 deduped_actions.push(action);
405 HoverAction::Reference(..) => {
407 seen_reference = true;
408 deduped_actions.push(action);
411 HoverAction::Runnable(..) => {
413 seen_runnable = true;
414 deduped_actions.push(action);
420 if !go_to_type_targets.is_empty() {
421 deduped_actions.push(HoverAction::GoToType(go_to_type_targets.into_iter().collect()));