9 use hir::{HasSource, Semantics};
12 defs::{Definition, IdentClass},
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>,
33 fn markdown(&self) -> bool {
34 matches!(self.documentation, Some(HoverDocFormat::Markdown))
38 #[derive(Clone, Debug, PartialEq, Eq)]
39 pub enum HoverDocFormat {
44 #[derive(Debug, Clone)]
45 pub enum HoverAction {
47 Implementation(FilePosition),
48 Reference(FilePosition),
49 GoToType(Vec<HoverGotoTypeData>),
53 fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
57 Some(HoverGotoTypeData {
58 mod_path: render::path(
61 it.name(db).map(|name| name.to_string()),
63 nav: it.try_to_nav(db)?,
67 HoverAction::GoToType(targets)
71 #[derive(Debug, Clone, Eq, PartialEq, Hash)]
72 pub struct HoverGotoTypeData {
74 pub nav: NavigationTarget,
77 /// Contains the results when hovering over an item
78 #[derive(Debug, Default)]
79 pub struct HoverResult {
81 pub actions: Vec<HoverAction>,
86 // Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
87 // Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
89 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
92 FileRange { file_id, range }: FileRange,
94 ) -> Option<RangeInfo<HoverResult>> {
95 let sema = &hir::Semantics::new(db);
96 let file = sema.parse(file_id).syntax().clone();
98 if !range.is_empty() {
99 return hover_ranged(&file, range, sema, config);
101 let offset = range.start();
103 let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
104 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] | T![Self] => 3,
105 T!['('] | T![')'] => 2,
106 kind if kind.is_trivia() => 0,
110 if let Some(doc_comment) = token_as_doc_comment(&original_token) {
111 cov_mark::hit!(no_highlight_on_comment_hover);
112 return doc_comment.get_definition_with_descend_at(sema, offset, |def, node, range| {
113 let res = hover_for_definition(sema, file_id, def, &node, config)?;
114 Some(RangeInfo::new(range, res))
118 let in_attr = matches!(original_token.parent().and_then(ast::TokenTree::cast), Some(tt) if tt.syntax().ancestors().any(|it| ast::Meta::can_cast(it.kind())));
119 let descended = if in_attr {
120 [sema.descend_into_macros_with_kind_preference(original_token.clone())].into()
122 sema.descend_into_macros_with_same_text(original_token.clone())
125 // FIXME: Definition should include known lints and the like instead of having this special case here
126 let hovered_lint = descended.iter().find_map(|token| {
127 let attr = token.parent_ancestors().find_map(ast::Attr::cast)?;
128 render::try_for_lint(&attr, token)
130 if let Some(res) = hovered_lint {
131 return Some(RangeInfo::new(original_token.text_range(), res));
134 let result = descended
136 .filter_map(|token| {
137 let node = token.parent()?;
138 let class = IdentClass::classify_token(sema, token)?;
139 Some(class.definitions().into_iter().zip(iter::once(node).cycle()))
142 .unique_by(|&(def, _)| def)
143 .filter_map(|(def, node)| hover_for_definition(sema, file_id, def, &node, config))
144 .reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
145 acc.actions.extend(actions);
146 acc.markup = Markup::from(format!("{}\n---\n{}", acc.markup, markup));
150 if result.is_none() {
151 // fallbacks, show keywords or types
153 let res = descended.iter().find_map(|token| render::keyword(sema, config, token));
154 if let Some(res) = res {
155 return Some(RangeInfo::new(original_token.text_range(), res));
159 .find_map(|token| hover_type_fallback(sema, config, token, &original_token));
160 if let Some(_) = res {
164 result.map(|mut res: HoverResult| {
165 res.actions = dedupe_or_merge_hover_actions(res.actions);
166 RangeInfo::new(original_token.text_range(), res)
170 pub(crate) fn hover_for_definition(
171 sema: &Semantics<'_, RootDatabase>,
173 definition: Definition,
175 config: &HoverConfig,
176 ) -> Option<HoverResult> {
177 let famous_defs = match &definition {
178 Definition::BuiltinType(_) => Some(FamousDefs(sema, sema.scope(node)?.krate())),
181 render::definition(sema.db, definition, famous_defs.as_ref(), config).map(|markup| {
183 markup: render::process_markup(sema.db, definition, &markup, config),
184 actions: show_implementations_action(sema.db, definition)
186 .chain(show_fn_references_action(sema.db, definition))
187 .chain(runnable_action(sema, definition, file_id))
188 .chain(goto_type_action_for_def(sema.db, definition))
196 range: syntax::TextRange,
197 sema: &Semantics<'_, RootDatabase>,
198 config: &HoverConfig,
199 ) -> Option<RangeInfo<HoverResult>> {
200 // FIXME: make this work in attributes
201 let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
204 ast::Expr(expr) => Some(Either::Left(expr)),
205 ast::Pat(pat) => Some(Either::Right(pat)),
210 let res = match &expr_or_pat {
211 Either::Left(ast::Expr::TryExpr(try_expr)) => render::try_expr(sema, config, try_expr),
212 Either::Left(ast::Expr::PrefixExpr(prefix_expr))
213 if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
215 render::deref_expr(sema, config, prefix_expr)
219 let res = res.or_else(|| render::type_info(sema, config, &expr_or_pat));
221 let range = match expr_or_pat {
222 Either::Left(it) => it.syntax().text_range(),
223 Either::Right(it) => it.syntax().text_range(),
225 RangeInfo::new(range, it)
229 fn hover_type_fallback(
230 sema: &Semantics<'_, RootDatabase>,
231 config: &HoverConfig,
233 original_token: &SyntaxToken,
234 ) -> Option<RangeInfo<HoverResult>> {
237 .take_while(|it| !ast::Item::can_cast(it.kind()))
238 .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
240 let expr_or_pat = match_ast! {
242 ast::Expr(it) => Either::Left(it),
243 ast::Pat(it) => Either::Right(it),
244 // If this node is a MACRO_CALL, it means that `descend_into_macros_many` failed to resolve.
245 // (e.g expanding a builtin macro). So we give up here.
246 ast::MacroCall(_it) => return None,
251 let res = render::type_info(sema, config, &expr_or_pat)?;
253 .original_range_opt(&node)
254 .map(|frange| frange.range)
255 .unwrap_or_else(|| original_token.text_range());
256 Some(RangeInfo::new(range, res))
259 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
260 fn to_action(nav_target: NavigationTarget) -> HoverAction {
261 HoverAction::Implementation(FilePosition {
262 file_id: nav_target.file_id,
263 offset: nav_target.focus_or_full_range().start(),
267 let adt = match def {
268 Definition::Trait(it) => return it.try_to_nav(db).map(to_action),
269 Definition::Adt(it) => Some(it),
270 Definition::SelfType(it) => it.self_ty(db).as_adt(),
273 adt.try_to_nav(db).map(to_action)
276 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
278 Definition::Function(it) => it.try_to_nav(db).map(|nav_target| {
279 HoverAction::Reference(FilePosition {
280 file_id: nav_target.file_id,
281 offset: nav_target.focus_or_full_range().start(),
289 sema: &hir::Semantics<'_, RootDatabase>,
292 ) -> Option<HoverAction> {
294 Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
295 Definition::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);
303 runnable_fn(sema, func).map(HoverAction::Runnable)
309 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
310 let mut targets: Vec<hir::ModuleDef> = Vec::new();
311 let mut push_new_def = |item: hir::ModuleDef| {
312 if !targets.contains(&item) {
317 if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
318 it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
321 Definition::Local(it) => it.ty(db),
322 Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
323 Definition::Field(field) => field.ty(db),
324 Definition::Function(function) => function.ret_type(db),
328 walk_and_push_ty(db, &ty, &mut push_new_def);
331 Some(HoverAction::goto_type_from_targets(db, targets))
337 push_new_def: &mut dyn FnMut(hir::ModuleDef),
340 if let Some(adt) = t.as_adt() {
341 push_new_def(adt.into());
342 } else if let Some(trait_) = t.as_dyn_trait() {
343 push_new_def(trait_.into());
344 } else if let Some(traits) = t.as_impl_traits(db) {
345 traits.for_each(|it| push_new_def(it.into()));
346 } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
347 push_new_def(trait_.into());
352 fn dedupe_or_merge_hover_actions(actions: Vec<HoverAction>) -> Vec<HoverAction> {
353 let mut deduped_actions = Vec::with_capacity(actions.len());
354 let mut go_to_type_targets = FxIndexSet::default();
356 let mut seen_implementation = false;
357 let mut seen_reference = false;
358 let mut seen_runnable = false;
359 for action in actions {
361 HoverAction::GoToType(targets) => {
362 go_to_type_targets.extend(targets);
364 HoverAction::Implementation(..) => {
365 if !seen_implementation {
366 seen_implementation = true;
367 deduped_actions.push(action);
370 HoverAction::Reference(..) => {
372 seen_reference = true;
373 deduped_actions.push(action);
376 HoverAction::Runnable(..) => {
378 seen_runnable = true;
379 deduped_actions.push(action);
385 if !go_to_type_targets.is_empty() {
386 deduped_actions.push(HoverAction::GoToType(go_to_type_targets.into_iter().collect()));