1 //! Logic for rendering the different hover messages
5 use hir::{AsAssocItem, AttributeTemplate, HasAttrs, HirDisplay, Semantics, TypeInfo};
7 base_db::SourceDatabase,
9 famous_defs::FamousDefs,
10 generated::lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES},
13 use itertools::Itertools;
16 algo, ast, match_ast, AstNode, Direction,
17 SyntaxKind::{LET_EXPR, LET_STMT},
22 doc_links::{remove_links, rewrite_links},
23 hover::walk_and_push_ty,
24 markdown_remove::remove_markdown,
25 HoverAction, HoverConfig, HoverResult, Markup,
28 pub(super) fn type_info(
29 sema: &Semantics<'_, RootDatabase>,
31 expr_or_pat: &Either<ast::Expr, ast::Pat>,
32 ) -> Option<HoverResult> {
33 let TypeInfo { original, adjusted } = match expr_or_pat {
34 Either::Left(expr) => sema.type_of_expr(expr)?,
35 Either::Right(pat) => sema.type_of_pat(pat)?,
38 let mut res = HoverResult::default();
39 let mut targets: Vec<hir::ModuleDef> = Vec::new();
40 let mut push_new_def = |item: hir::ModuleDef| {
41 if !targets.contains(&item) {
45 walk_and_push_ty(sema.db, &original, &mut push_new_def);
47 res.markup = if let Some(adjusted_ty) = adjusted {
48 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
49 let original = original.display(sema.db).to_string();
50 let adjusted = adjusted_ty.display(sema.db).to_string();
51 let static_text_diff_len = "Coerced to: ".len() - "Type: ".len();
53 "{bt_start}Type: {:>apad$}\nCoerced to: {:>opad$}\n{bt_end}",
56 apad = static_text_diff_len + adjusted.len().max(original.len()),
57 opad = original.len(),
58 bt_start = if config.markdown() { "```text\n" } else { "" },
59 bt_end = if config.markdown() { "```\n" } else { "" }
63 if config.markdown() {
64 Markup::fenced_block(&original.display(sema.db))
66 original.display(sema.db).to_string().into()
69 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
73 pub(super) fn try_expr(
74 sema: &Semantics<'_, RootDatabase>,
76 try_expr: &ast::TryExpr,
77 ) -> Option<HoverResult> {
78 let inner_ty = sema.type_of_expr(&try_expr.expr()?)?.original;
79 let mut ancestors = try_expr.syntax().ancestors();
80 let mut body_ty = loop {
81 let next = ancestors.next()?;
84 ast::Fn(fn_) => sema.to_def(&fn_)?.ret_type(sema.db),
85 ast::Item(__) => return None,
86 ast::ClosureExpr(closure) => sema.type_of_expr(&closure.body()?)?.original,
87 ast::BlockExpr(block_expr) => if matches!(block_expr.modifier(), Some(ast::BlockModifier::Async(_) | ast::BlockModifier::Try(_)| ast::BlockModifier::Const(_))) {
88 sema.type_of_expr(&block_expr.into())?.original
97 if inner_ty == body_ty {
101 let mut inner_ty = inner_ty;
102 let mut s = "Try Target".to_owned();
104 let adts = inner_ty.as_adt().zip(body_ty.as_adt());
105 if let Some((hir::Adt::Enum(inner), hir::Adt::Enum(body))) = adts {
106 let famous_defs = FamousDefs(sema, sema.scope(try_expr.syntax())?.krate());
107 // special case for two options, there is no value in showing them
108 if let Some(option_enum) = famous_defs.core_option_Option() {
109 if inner == option_enum && body == option_enum {
110 cov_mark::hit!(hover_try_expr_opt_opt);
115 // special case two results to show the error variants only
116 if let Some(result_enum) = famous_defs.core_result_Result() {
117 if inner == result_enum && body == result_enum {
118 let error_type_args =
119 inner_ty.type_arguments().nth(1).zip(body_ty.type_arguments().nth(1));
120 if let Some((inner, body)) = error_type_args {
123 s = "Try Error".to_owned();
129 let mut res = HoverResult::default();
131 let mut targets: Vec<hir::ModuleDef> = Vec::new();
132 let mut push_new_def = |item: hir::ModuleDef| {
133 if !targets.contains(&item) {
137 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
138 walk_and_push_ty(sema.db, &body_ty, &mut push_new_def);
139 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
141 let inner_ty = inner_ty.display(sema.db).to_string();
142 let body_ty = body_ty.display(sema.db).to_string();
143 let ty_len_max = inner_ty.len().max(body_ty.len());
145 let l = "Propagated as: ".len() - " Type: ".len();
146 let static_text_len_diff = l as isize - s.len() as isize;
147 let tpad = static_text_len_diff.max(0) as usize;
148 let ppad = static_text_len_diff.min(0).abs() as usize;
150 res.markup = format!(
151 "{bt_start}{} Type: {:>pad0$}\nPropagated as: {:>pad1$}\n{bt_end}",
155 pad0 = ty_len_max + tpad,
156 pad1 = ty_len_max + ppad,
157 bt_start = if config.markdown() { "```text\n" } else { "" },
158 bt_end = if config.markdown() { "```\n" } else { "" }
164 pub(super) fn deref_expr(
165 sema: &Semantics<'_, RootDatabase>,
166 config: &HoverConfig,
167 deref_expr: &ast::PrefixExpr,
168 ) -> Option<HoverResult> {
169 let inner_ty = sema.type_of_expr(&deref_expr.expr()?)?.original;
170 let TypeInfo { original, adjusted } =
171 sema.type_of_expr(&ast::Expr::from(deref_expr.clone()))?;
173 let mut res = HoverResult::default();
174 let mut targets: Vec<hir::ModuleDef> = Vec::new();
175 let mut push_new_def = |item: hir::ModuleDef| {
176 if !targets.contains(&item) {
180 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
181 walk_and_push_ty(sema.db, &original, &mut push_new_def);
183 res.markup = if let Some(adjusted_ty) = adjusted {
184 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
185 let original = original.display(sema.db).to_string();
186 let adjusted = adjusted_ty.display(sema.db).to_string();
187 let inner = inner_ty.display(sema.db).to_string();
188 let type_len = "To type: ".len();
189 let coerced_len = "Coerced to: ".len();
190 let deref_len = "Dereferenced from: ".len();
191 let max_len = (original.len() + type_len)
192 .max(adjusted.len() + coerced_len)
193 .max(inner.len() + deref_len);
195 "{bt_start}Dereferenced from: {:>ipad$}\nTo type: {:>apad$}\nCoerced to: {:>opad$}\n{bt_end}",
199 ipad = max_len - deref_len,
200 apad = max_len - type_len,
201 opad = max_len - coerced_len,
202 bt_start = if config.markdown() { "```text\n" } else { "" },
203 bt_end = if config.markdown() { "```\n" } else { "" }
207 let original = original.display(sema.db).to_string();
208 let inner = inner_ty.display(sema.db).to_string();
209 let type_len = "To type: ".len();
210 let deref_len = "Dereferenced from: ".len();
211 let max_len = (original.len() + type_len).max(inner.len() + deref_len);
213 "{bt_start}Dereferenced from: {:>ipad$}\nTo type: {:>apad$}\n{bt_end}",
216 ipad = max_len - deref_len,
217 apad = max_len - type_len,
218 bt_start = if config.markdown() { "```text\n" } else { "" },
219 bt_end = if config.markdown() { "```\n" } else { "" }
223 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
228 pub(super) fn keyword(
229 sema: &Semantics<'_, RootDatabase>,
230 config: &HoverConfig,
232 ) -> Option<HoverResult> {
233 if !token.kind().is_keyword() || !config.documentation.is_some() || !config.keywords {
236 let parent = token.parent()?;
237 let famous_defs = FamousDefs(sema, sema.scope(&parent)?.krate());
239 let KeywordHint { description, keyword_mod, actions } = keyword_hints(sema, token, parent);
241 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?;
242 let docs = doc_owner.attrs(sema.db).docs()?;
243 let markup = process_markup(
245 Definition::Module(doc_owner),
246 &markup(Some(docs.into()), description, None)?,
249 Some(HoverResult { markup, actions })
252 pub(super) fn try_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option<HoverResult> {
253 let (path, tt) = attr.as_simple_call()?;
254 if !tt.syntax().text_range().contains(token.text_range().start()) {
257 let (is_clippy, lints) = match &*path {
258 "feature" => (false, FEATURES),
259 "allow" | "deny" | "forbid" | "warn" => {
260 let is_clippy = algo::non_trivia_sibling(token.clone().into(), Direction::Prev)
261 .filter(|t| t.kind() == T![:])
262 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
263 .filter(|t| t.kind() == T![:])
264 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
266 t.kind() == T![ident] && t.into_token().map_or(false, |t| t.text() == "clippy")
271 (false, DEFAULT_LINTS)
278 let needle = if is_clippy {
279 tmp = format!("clippy::{}", token.text());
286 lints.binary_search_by_key(&needle, |lint| lint.label).ok().map(|idx| &lints[idx])?;
288 markup: Markup::from(format!("```\n{}\n```\n___\n\n{}", lint.label, lint.description)),
293 pub(super) fn process_markup(
297 config: &HoverConfig,
299 let markup = markup.as_str();
300 let markup = if !config.markdown() {
301 remove_markdown(markup)
302 } else if config.links_in_hover {
303 rewrite_links(db, markup, def)
310 fn definition_owner_name(db: &RootDatabase, def: &Definition) -> Option<String> {
312 Definition::Field(f) => Some(f.parent_def(db).name(db)),
313 Definition::Local(l) => l.parent(db).name(db),
314 Definition::Function(f) => match f.as_assoc_item(db)?.container(db) {
315 hir::AssocItemContainer::Trait(t) => Some(t.name(db)),
316 hir::AssocItemContainer::Impl(i) => i.self_ty(db).as_adt().map(|adt| adt.name(db)),
318 Definition::Variant(e) => Some(e.parent_enum(db).name(db)),
321 .map(|name| name.to_string())
324 pub(super) fn path(db: &RootDatabase, module: hir::Module, item_name: Option<String>) -> String {
326 db.crate_graph()[module.krate().into()].display_name.as_ref().map(|it| it.to_string());
327 let module_path = module
331 .flat_map(|it| it.name(db).map(|name| name.to_string()));
332 crate_name.into_iter().chain(module_path).chain(item_name).join("::")
335 pub(super) fn definition(
338 famous_defs: Option<&FamousDefs<'_, '_>>,
339 config: &HoverConfig,
340 ) -> Option<Markup> {
341 let mod_path = definition_mod_path(db, &def);
342 let (label, docs) = match def {
343 Definition::Macro(it) => label_and_docs(db, it),
344 Definition::Field(it) => label_and_docs(db, it),
345 Definition::Module(it) => label_and_docs(db, it),
346 Definition::Function(it) => label_and_docs(db, it),
347 Definition::Adt(it) => label_and_docs(db, it),
348 Definition::Variant(it) => label_and_docs(db, it),
349 Definition::Const(it) => label_value_and_docs(db, it, |it| {
350 let body = it.eval(db);
352 Ok(x) => Some(format!("{}", x)),
353 Err(_) => it.value(db).map(|x| format!("{}", x)),
356 Definition::Static(it) => label_value_and_docs(db, it, |it| it.value(db)),
357 Definition::Trait(it) => label_and_docs(db, it),
358 Definition::TypeAlias(it) => label_and_docs(db, it),
359 Definition::BuiltinType(it) => {
361 .and_then(|fd| builtin(fd, it))
362 .or_else(|| Some(Markup::fenced_block(&it.name())))
364 Definition::Local(it) => return local(db, it),
365 Definition::SelfType(impl_def) => {
366 impl_def.self_ty(db).as_adt().map(|adt| label_and_docs(db, adt))?
368 Definition::GenericParam(it) => label_and_docs(db, it),
369 Definition::Label(it) => return Some(Markup::fenced_block(&it.name(db))),
370 // FIXME: We should be able to show more info about these
371 Definition::BuiltinAttr(it) => return render_builtin_attr(db, it),
372 Definition::ToolModule(it) => return Some(Markup::fenced_block(&it.name(db))),
373 Definition::DeriveHelper(it) => (format!("derive_helper {}", it.name(db)), None),
376 let docs = match config.documentation {
377 Some(_) => docs.or_else(|| {
378 // docs are missing, for assoc items of trait impls try to fall back to the docs of the
379 // original item of the trait
380 let assoc = def.as_assoc_item(db)?;
381 let trait_ = assoc.containing_trait_impl(db)?;
382 let name = Some(assoc.name(db)?);
383 let item = trait_.items(db).into_iter().find(|it| it.name(db) == name)?;
388 let docs = docs.filter(|_| config.documentation.is_some()).map(Into::into);
389 markup(docs, label, mod_path)
392 fn render_builtin_attr(db: &RootDatabase, attr: hir::BuiltinAttr) -> Option<Markup> {
393 let name = attr.name(db);
394 let desc = format!("#[{}]", name);
396 let AttributeTemplate { word, list, name_value_str } = match attr.template(db) {
397 Some(template) => template,
398 None => return Some(Markup::fenced_block(&attr.name(db))),
400 let mut docs = "Valid forms are:".to_owned();
402 format_to!(docs, "\n - #\\[{}]", name);
404 if let Some(list) = list {
405 format_to!(docs, "\n - #\\[{}({})]", name, list);
407 if let Some(name_value_str) = name_value_str {
408 format_to!(docs, "\n - #\\[{} = {}]", name, name_value_str);
410 markup(Some(docs.replace('*', "\\*")), desc, None)
413 fn label_and_docs<D>(db: &RootDatabase, def: D) -> (String, Option<hir::Documentation>)
415 D: HasAttrs + HirDisplay,
417 let label = def.display(db).to_string();
418 let docs = def.attrs(db).docs();
422 fn label_value_and_docs<D, E, V>(
426 ) -> (String, Option<hir::Documentation>)
428 D: HasAttrs + HirDisplay,
429 E: Fn(&D) -> Option<V>,
432 let label = if let Some(value) = value_extractor(&def) {
433 format!("{} = {}", def.display(db), value)
435 def.display(db).to_string()
437 let docs = def.attrs(db).docs();
441 fn definition_mod_path(db: &RootDatabase, def: &Definition) -> Option<String> {
442 if let Definition::GenericParam(_) = def {
445 def.module(db).map(|module| path(db, module, definition_owner_name(db, def)))
448 fn markup(docs: Option<String>, desc: String, mod_path: Option<String>) -> Option<Markup> {
449 let mut buf = String::new();
451 if let Some(mod_path) = mod_path {
452 if !mod_path.is_empty() {
453 format_to!(buf, "```rust\n{}\n```\n\n", mod_path);
456 format_to!(buf, "```rust\n{}\n```", desc);
458 if let Some(doc) = docs {
459 format_to!(buf, "\n___\n\n{}", doc);
464 fn builtin(famous_defs: &FamousDefs<'_, '_>, builtin: hir::BuiltinType) -> Option<Markup> {
465 // std exposes prim_{} modules with docstrings on the root to document the builtins
466 let primitive_mod = format!("prim_{}", builtin.name());
467 let doc_owner = find_std_module(famous_defs, &primitive_mod)?;
468 let docs = doc_owner.attrs(famous_defs.0.db).docs()?;
469 markup(Some(docs.into()), builtin.name().to_string(), None)
472 fn find_std_module(famous_defs: &FamousDefs<'_, '_>, name: &str) -> Option<hir::Module> {
473 let db = famous_defs.0.db;
474 let std_crate = famous_defs.std()?;
475 let std_root_module = std_crate.root_module(db);
478 .find(|module| module.name(db).map_or(false, |module| module.to_string() == name))
481 fn local(db: &RootDatabase, it: hir::Local) -> Option<Markup> {
483 let ty = ty.display_truncated(db, None);
484 let is_mut = if it.is_mut(db) { "mut " } else { "" };
485 let desc = match it.source(db).value {
486 Either::Left(ident) => {
487 let name = it.name(db);
488 let let_kw = if ident
491 .map_or(false, |p| p.kind() == LET_STMT || p.kind() == LET_EXPR)
497 format!("{}{}{}: {}", let_kw, is_mut, name, ty)
499 Either::Right(_) => format!("{}self: {}", is_mut, ty),
501 markup(None, desc, None)
507 actions: Vec<HoverAction>,
511 fn new(description: String, keyword_mod: String) -> Self {
512 Self { description, keyword_mod, actions: Vec::default() }
517 sema: &Semantics<'_, RootDatabase>,
519 parent: syntax::SyntaxNode,
522 T![await] | T![loop] | T![match] | T![unsafe] | T![as] | T![try] | T![if] | T![else] => {
523 let keyword_mod = format!("{}_keyword", token.text());
525 match ast::Expr::cast(parent).and_then(|site| sema.type_of_expr(&site)) {
526 // ignore the unit type ()
527 Some(ty) if !ty.adjusted.as_ref().unwrap_or(&ty.original).is_unit() => {
528 let mut targets: Vec<hir::ModuleDef> = Vec::new();
529 let mut push_new_def = |item: hir::ModuleDef| {
530 if !targets.contains(&item) {
534 walk_and_push_ty(sema.db, &ty.original, &mut push_new_def);
536 let ty = ty.adjusted();
537 let description = format!("{}: {}", token.text(), ty.display(sema.db));
542 actions: vec![HoverAction::goto_type_from_targets(sema.db, targets)],
546 description: token.text().to_string(),
553 let module = match ast::FnPtrType::cast(parent) {
554 // treat fn keyword inside function pointer type as primitive
555 Some(_) => format!("prim_{}", token.text()),
556 None => format!("{}_keyword", token.text()),
558 KeywordHint::new(token.text().to_string(), module)
560 T![Self] => KeywordHint::new(token.text().to_string(), "self_upper_keyword".into()),
561 _ => KeywordHint::new(token.text().to_string(), format!("{}_keyword", token.text())),