1 //! Logic for rendering the different hover messages
5 use hir::{AsAssocItem, AttributeTemplate, HasAttrs, HasSource, HirDisplay, Semantics, TypeInfo};
7 base_db::SourceDatabase,
10 generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES},
15 use itertools::Itertools;
19 display::{fn_as_proc_macro_label, macro_label},
20 match_ast, AstNode, Direction,
21 SyntaxKind::{CONDITION, LET_STMT},
26 doc_links::{remove_links, rewrite_links},
27 hover::walk_and_push_ty,
28 markdown_remove::remove_markdown,
29 HoverAction, HoverConfig, HoverResult, Markup,
32 pub(super) fn type_info(
33 sema: &Semantics<RootDatabase>,
35 expr_or_pat: &Either<ast::Expr, ast::Pat>,
36 ) -> Option<HoverResult> {
37 let TypeInfo { original, adjusted } = match expr_or_pat {
38 Either::Left(expr) => sema.type_of_expr(expr)?,
39 Either::Right(pat) => sema.type_of_pat(pat)?,
42 let mut res = HoverResult::default();
43 let mut targets: Vec<hir::ModuleDef> = Vec::new();
44 let mut push_new_def = |item: hir::ModuleDef| {
45 if !targets.contains(&item) {
49 walk_and_push_ty(sema.db, &original, &mut push_new_def);
51 res.markup = if let Some(adjusted_ty) = adjusted {
52 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
53 let original = original.display(sema.db).to_string();
54 let adjusted = adjusted_ty.display(sema.db).to_string();
55 let static_text_diff_len = "Coerced to: ".len() - "Type: ".len();
57 "{bt_start}Type: {:>apad$}\nCoerced to: {:>opad$}\n{bt_end}",
60 apad = static_text_diff_len + adjusted.len().max(original.len()),
61 opad = original.len(),
62 bt_start = if config.markdown() { "```text\n" } else { "" },
63 bt_end = if config.markdown() { "```\n" } else { "" }
67 if config.markdown() {
68 Markup::fenced_block(&original.display(sema.db))
70 original.display(sema.db).to_string().into()
73 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
77 pub(super) fn try_expr(
78 sema: &Semantics<RootDatabase>,
80 try_expr: &ast::TryExpr,
81 ) -> Option<HoverResult> {
82 let inner_ty = sema.type_of_expr(&try_expr.expr()?)?.original;
83 let mut ancestors = try_expr.syntax().ancestors();
84 let mut body_ty = loop {
85 let next = ancestors.next()?;
88 ast::Fn(fn_) => sema.to_def(&fn_)?.ret_type(sema.db),
89 ast::Item(__) => return None,
90 ast::ClosureExpr(closure) => sema.type_of_expr(&closure.body()?)?.original,
91 ast::BlockExpr(block_expr) => if matches!(block_expr.modifier(), Some(ast::BlockModifier::Async(_) | ast::BlockModifier::Try(_)| ast::BlockModifier::Const(_))) {
92 sema.type_of_expr(&block_expr.into())?.original
101 if inner_ty == body_ty {
105 let mut inner_ty = inner_ty;
106 let mut s = "Try Target".to_owned();
108 let adts = inner_ty.as_adt().zip(body_ty.as_adt());
109 if let Some((hir::Adt::Enum(inner), hir::Adt::Enum(body))) = adts {
110 let famous_defs = FamousDefs(sema, sema.scope(&try_expr.syntax()).krate());
111 // special case for two options, there is no value in showing them
112 if let Some(option_enum) = famous_defs.core_option_Option() {
113 if inner == option_enum && body == option_enum {
114 cov_mark::hit!(hover_try_expr_opt_opt);
119 // special case two results to show the error variants only
120 if let Some(result_enum) = famous_defs.core_result_Result() {
121 if inner == result_enum && body == result_enum {
122 let error_type_args =
123 inner_ty.type_arguments().nth(1).zip(body_ty.type_arguments().nth(1));
124 if let Some((inner, body)) = error_type_args {
127 s = "Try Error".to_owned();
133 let mut res = HoverResult::default();
135 let mut targets: Vec<hir::ModuleDef> = Vec::new();
136 let mut push_new_def = |item: hir::ModuleDef| {
137 if !targets.contains(&item) {
141 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
142 walk_and_push_ty(sema.db, &body_ty, &mut push_new_def);
143 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
145 let inner_ty = inner_ty.display(sema.db).to_string();
146 let body_ty = body_ty.display(sema.db).to_string();
147 let ty_len_max = inner_ty.len().max(body_ty.len());
149 let l = "Propagated as: ".len() - " Type: ".len();
150 let static_text_len_diff = l as isize - s.len() as isize;
151 let tpad = static_text_len_diff.max(0) as usize;
152 let ppad = static_text_len_diff.min(0).abs() as usize;
154 res.markup = format!(
155 "{bt_start}{} Type: {:>pad0$}\nPropagated as: {:>pad1$}\n{bt_end}",
159 pad0 = ty_len_max + tpad,
160 pad1 = ty_len_max + ppad,
161 bt_start = if config.markdown() { "```text\n" } else { "" },
162 bt_end = if config.markdown() { "```\n" } else { "" }
168 pub(super) fn deref_expr(
169 sema: &Semantics<RootDatabase>,
170 config: &HoverConfig,
171 deref_expr: &ast::PrefixExpr,
172 ) -> Option<HoverResult> {
173 let inner_ty = sema.type_of_expr(&deref_expr.expr()?)?.original;
174 let TypeInfo { original, adjusted } =
175 sema.type_of_expr(&ast::Expr::from(deref_expr.clone()))?;
177 let mut res = HoverResult::default();
178 let mut targets: Vec<hir::ModuleDef> = Vec::new();
179 let mut push_new_def = |item: hir::ModuleDef| {
180 if !targets.contains(&item) {
184 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
185 walk_and_push_ty(sema.db, &original, &mut push_new_def);
187 res.markup = if let Some(adjusted_ty) = adjusted {
188 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
189 let original = original.display(sema.db).to_string();
190 let adjusted = adjusted_ty.display(sema.db).to_string();
191 let inner = inner_ty.display(sema.db).to_string();
192 let type_len = "To type: ".len();
193 let coerced_len = "Coerced to: ".len();
194 let deref_len = "Dereferenced from: ".len();
195 let max_len = (original.len() + type_len)
196 .max(adjusted.len() + coerced_len)
197 .max(inner.len() + deref_len);
199 "{bt_start}Dereferenced from: {:>ipad$}\nTo type: {:>apad$}\nCoerced to: {:>opad$}\n{bt_end}",
203 ipad = max_len - deref_len,
204 apad = max_len - type_len,
205 opad = max_len - coerced_len,
206 bt_start = if config.markdown() { "```text\n" } else { "" },
207 bt_end = if config.markdown() { "```\n" } else { "" }
211 let original = original.display(sema.db).to_string();
212 let inner = inner_ty.display(sema.db).to_string();
213 let type_len = "To type: ".len();
214 let deref_len = "Dereferenced from: ".len();
215 let max_len = (original.len() + type_len).max(inner.len() + deref_len);
217 "{bt_start}Dereferenced from: {:>ipad$}\nTo type: {:>apad$}\n{bt_end}",
220 ipad = max_len - deref_len,
221 apad = max_len - type_len,
222 bt_start = if config.markdown() { "```text\n" } else { "" },
223 bt_end = if config.markdown() { "```\n" } else { "" }
227 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
232 pub(super) fn keyword(
233 sema: &Semantics<RootDatabase>,
234 config: &HoverConfig,
236 ) -> Option<HoverResult> {
237 if !token.kind().is_keyword() || !config.documentation.is_some() {
240 let parent = token.parent()?;
241 let famous_defs = FamousDefs(sema, sema.scope(&parent).krate());
243 // some keywords get fancy type tooltips if they are apart of an expression, which require some extra work
244 // panic safety: we just checked that token is a keyword, and we have it's parent in scope, so it must have a parent
245 let KeywordHint { description, documentation, actions } = keyword_hints(sema, token);
247 let doc_owner = find_std_module(&famous_defs, &documentation)?;
248 let docs = doc_owner.attrs(sema.db).docs()?;
249 let markup = process_markup(
251 Definition::Module(doc_owner),
252 &markup(Some(docs.into()), description, None)?,
255 Some(HoverResult { markup, actions })
258 pub(super) fn try_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option<HoverResult> {
259 let (path, tt) = attr.as_simple_call()?;
260 if !tt.syntax().text_range().contains(token.text_range().start()) {
263 let (is_clippy, lints) = match &*path {
264 "feature" => (false, FEATURES),
265 "allow" | "deny" | "forbid" | "warn" => {
266 let is_clippy = algo::non_trivia_sibling(token.clone().into(), Direction::Prev)
267 .filter(|t| t.kind() == T![:])
268 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
269 .filter(|t| t.kind() == T![:])
270 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
272 t.kind() == T![ident] && t.into_token().map_or(false, |t| t.text() == "clippy")
277 (false, DEFAULT_LINTS)
284 let needle = if is_clippy {
285 tmp = format!("clippy::{}", token.text());
292 lints.binary_search_by_key(&needle, |lint| lint.label).ok().map(|idx| &lints[idx])?;
294 markup: Markup::from(format!("```\n{}\n```\n___\n\n{}", lint.label, lint.description)),
299 pub(super) fn process_markup(
303 config: &HoverConfig,
305 let markup = markup.as_str();
306 let markup = if !config.markdown() {
307 remove_markdown(markup)
308 } else if config.links_in_hover {
309 rewrite_links(db, markup, def)
316 fn definition_owner_name(db: &RootDatabase, def: &Definition) -> Option<String> {
318 Definition::Field(f) => Some(f.parent_def(db).name(db)),
319 Definition::Local(l) => l.parent(db).name(db),
320 Definition::Function(f) => match f.as_assoc_item(db)?.container(db) {
321 hir::AssocItemContainer::Trait(t) => Some(t.name(db)),
322 hir::AssocItemContainer::Impl(i) => i.self_ty(db).as_adt().map(|adt| adt.name(db)),
324 Definition::Variant(e) => Some(e.parent_enum(db).name(db)),
327 .map(|name| name.to_string())
330 pub(super) fn path(db: &RootDatabase, module: hir::Module, item_name: Option<String>) -> String {
332 db.crate_graph()[module.krate().into()].display_name.as_ref().map(|it| it.to_string());
333 let module_path = module
337 .flat_map(|it| it.name(db).map(|name| name.to_string()));
338 crate_name.into_iter().chain(module_path).chain(item_name).join("::")
341 pub(super) fn definition(
344 famous_defs: Option<&FamousDefs>,
345 config: &HoverConfig,
346 ) -> Option<Markup> {
347 let mod_path = definition_mod_path(db, &def);
348 let (label, docs) = match def {
349 Definition::Macro(it) => (
350 match &it.source(db)?.value {
351 Either::Left(mac) => macro_label(mac),
352 Either::Right(mac_fn) => fn_as_proc_macro_label(mac_fn),
356 Definition::Field(def) => label_and_docs(db, def),
357 Definition::Module(it) => label_and_docs(db, it),
358 Definition::Function(it) => label_and_docs(db, it),
359 Definition::Adt(it) => label_and_docs(db, it),
360 Definition::Variant(it) => label_and_docs(db, it),
361 Definition::Const(it) => label_value_and_docs(db, it, |it| {
362 let body = it.eval(db);
364 Ok(x) => Some(format!("{}", x)),
365 Err(_) => it.value(db).map(|x| format!("{}", x)),
368 Definition::Static(it) => label_value_and_docs(db, it, |it| it.value(db)),
369 Definition::Trait(it) => label_and_docs(db, it),
370 Definition::TypeAlias(it) => label_and_docs(db, it),
371 Definition::BuiltinType(it) => {
373 .and_then(|fd| builtin(fd, it))
374 .or_else(|| Some(Markup::fenced_block(&it.name())))
376 Definition::Local(it) => return local(db, it),
377 Definition::SelfType(impl_def) => {
378 impl_def.self_ty(db).as_adt().map(|adt| label_and_docs(db, adt))?
380 Definition::GenericParam(it) => label_and_docs(db, it),
381 Definition::Label(it) => return Some(Markup::fenced_block(&it.name(db))),
382 // FIXME: We should be able to show more info about these
383 Definition::BuiltinAttr(it) => return render_builtin_attr(db, it),
384 Definition::ToolModule(it) => return Some(Markup::fenced_block(&it.name(db))),
387 markup(docs.filter(|_| config.documentation.is_some()).map(Into::into), label, mod_path)
390 fn render_builtin_attr(db: &RootDatabase, attr: hir::BuiltinAttr) -> Option<Markup> {
391 let name = attr.name(db);
392 let desc = format!("#[{}]", name);
394 let AttributeTemplate { word, list, name_value_str } = match attr.template(db) {
395 Some(template) => template,
396 None => return Some(Markup::fenced_block(&attr.name(db))),
398 let mut docs = "Valid forms are:".to_owned();
400 format_to!(docs, "\n - #\\[{}]", name);
402 if let Some(list) = list {
403 format_to!(docs, "\n - #\\[{}({})]", name, list);
405 if let Some(name_value_str) = name_value_str {
406 format_to!(docs, "\n - #\\[{} = {}]", name, name_value_str);
408 markup(Some(docs.replace('*', "\\*")), desc, None)
411 fn label_and_docs<D>(db: &RootDatabase, def: D) -> (String, Option<hir::Documentation>)
413 D: HasAttrs + HirDisplay,
415 let label = def.display(db).to_string();
416 let docs = def.attrs(db).docs();
420 fn label_value_and_docs<D, E, V>(
424 ) -> (String, Option<hir::Documentation>)
426 D: HasAttrs + HirDisplay,
427 E: Fn(&D) -> Option<V>,
430 let label = if let Some(value) = value_extractor(&def) {
431 format!("{} = {}", def.display(db), value)
433 def.display(db).to_string()
435 let docs = def.attrs(db).docs();
439 fn definition_mod_path(db: &RootDatabase, def: &Definition) -> Option<String> {
440 if let Definition::GenericParam(_) = def {
443 def.module(db).map(|module| path(db, module, definition_owner_name(db, def)))
446 fn markup(docs: Option<String>, desc: String, mod_path: Option<String>) -> Option<Markup> {
447 let mut buf = String::new();
449 if let Some(mod_path) = mod_path {
450 if !mod_path.is_empty() {
451 format_to!(buf, "```rust\n{}\n```\n\n", mod_path);
454 format_to!(buf, "```rust\n{}\n```", desc);
456 if let Some(doc) = docs {
457 format_to!(buf, "\n___\n\n{}", doc);
462 fn builtin(famous_defs: &FamousDefs, builtin: hir::BuiltinType) -> Option<Markup> {
463 // std exposes prim_{} modules with docstrings on the root to document the builtins
464 let primitive_mod = format!("prim_{}", builtin.name());
465 let doc_owner = find_std_module(famous_defs, &primitive_mod)?;
466 let docs = doc_owner.attrs(famous_defs.0.db).docs()?;
467 markup(Some(docs.into()), builtin.name().to_string(), None)
470 fn find_std_module(famous_defs: &FamousDefs, name: &str) -> Option<hir::Module> {
471 let db = famous_defs.0.db;
472 let std_crate = famous_defs.std()?;
473 let std_root_module = std_crate.root_module(db);
476 .find(|module| module.name(db).map_or(false, |module| module.to_string() == name))
479 fn local(db: &RootDatabase, it: hir::Local) -> Option<Markup> {
481 let ty = ty.display_truncated(db, None);
482 let is_mut = if it.is_mut(db) { "mut " } else { "" };
483 let desc = match it.source(db).value {
484 Either::Left(ident) => {
485 let name = it.name(db).unwrap();
486 let let_kw = if ident
489 .map_or(false, |p| p.kind() == LET_STMT || p.kind() == CONDITION)
495 format!("{}{}{}: {}", let_kw, is_mut, name, ty)
497 Either::Right(_) => format!("{}self: {}", is_mut, ty),
499 markup(None, desc, None)
504 documentation: String,
505 actions: Vec<HoverAction>,
509 fn new(description: String, documentation: String) -> Self {
510 Self { description, documentation, actions: Vec::default() }
516 /// `token` is assumed to:
517 /// - have a parent, and
519 fn keyword_hints<'t>(sema: &Semantics<RootDatabase>, token: &'t SyntaxToken) -> KeywordHint {
520 let parent = token.parent().expect("token was assumed to have a parent, but had none");
522 macro_rules! create_hint {
523 ($ty_info:expr, $doc:expr) => {{
524 let documentation = $doc;
527 let mut targets: Vec<hir::ModuleDef> = Vec::new();
528 let mut push_new_def = |item: hir::ModuleDef| {
529 if !targets.contains(&item) {
533 walk_and_push_ty(sema.db, &ty.original, &mut push_new_def);
535 let ty = ty.adjusted();
536 let description = format!("{}: {}", token.text(), ty.display(sema.db));
541 actions: vec![HoverAction::goto_type_from_targets(sema.db, targets)],
544 None => KeywordHint {
545 description: token.text().to_string(),
554 T![await] | T![loop] | T![match] | T![unsafe] => {
555 let ty = ast::Expr::cast(parent).and_then(|site| sema.type_of_expr(&site));
556 create_hint!(ty, format!("{}_keyword", token.text()))
559 T![if] | T![else] => {
560 fn if_has_else(site: &ast::IfExpr) -> bool {
561 match site.else_branch() {
562 Some(ast::ElseBranch::IfExpr(inner)) => if_has_else(&inner),
563 Some(ast::ElseBranch::Block(_)) => true,
568 // only include the type if there is an else branch; it isn't worth annotating
569 // an expression that always returns `()`, is it?
570 let ty = ast::IfExpr::cast(parent)
571 .and_then(|site| if_has_else(&site).then(|| site))
572 .and_then(|site| sema.type_of_expr(&ast::Expr::IfExpr(site)));
573 create_hint!(ty, format!("{}_keyword", token.text()))
577 let module = match ast::FnPtrType::cast(parent) {
578 // treat fn keyword inside function pointer type as primitive
579 Some(_) => format!("prim_{}", token.text()),
580 None => format!("{}_keyword", token.text()),
582 KeywordHint::new(token.text().to_string(), module)
585 kind if kind.is_keyword() => {
586 KeywordHint::new(token.text().to_string(), format!("{}_keyword", token.text()))
589 _ => panic!("{} was assumed to be a keyword, but it wasn't", token),