1 use std::{collections::HashSet, ops::ControlFlow};
4 use hir::{AsAssocItem, HasAttrs, HasSource, HirDisplay, Semantics, TypeInfo};
6 base_db::{FileRange, SourceDatabase},
7 defs::{Definition, NameClass, NameRefClass},
9 generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES},
10 pick_best_token, try_resolve_derive_input_at, FamousDefs,
14 use itertools::Itertools;
17 algo, ast, display::fn_as_proc_macro_label, match_ast, AstNode, Direction, SyntaxKind::*,
18 SyntaxNode, SyntaxToken, TextRange, TextSize, T,
22 display::{macro_label, TryToNav},
24 doc_attributes, extract_definitions_from_docs, remove_links, resolve_doc_path_for_def,
27 markdown_remove::remove_markdown,
29 runnables::{runnable_fn, runnable_mod},
30 FileId, FilePosition, NavigationTarget, RangeInfo, Runnable,
33 #[derive(Clone, Debug, PartialEq, Eq)]
34 pub struct HoverConfig {
35 pub links_in_hover: bool,
36 pub documentation: Option<HoverDocFormat>,
40 fn markdown(&self) -> bool {
41 matches!(self.documentation, Some(HoverDocFormat::Markdown))
45 #[derive(Clone, Debug, PartialEq, Eq)]
46 pub enum HoverDocFormat {
51 #[derive(Debug, Clone)]
52 pub enum HoverAction {
54 Implementation(FilePosition),
55 Reference(FilePosition),
56 GoToType(Vec<HoverGotoTypeData>),
60 fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
64 Some(HoverGotoTypeData {
65 mod_path: render_path(
68 it.name(db).map(|name| name.to_string()),
70 nav: it.try_to_nav(db)?,
74 HoverAction::GoToType(targets)
78 #[derive(Debug, Clone, Eq, PartialEq)]
79 pub struct HoverGotoTypeData {
81 pub nav: NavigationTarget,
84 /// Contains the results when hovering over an item
85 #[derive(Debug, Default)]
86 pub struct HoverResult {
88 pub actions: Vec<HoverAction>,
93 // Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
94 // Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
96 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
99 FileRange { file_id, range }: FileRange,
100 config: &HoverConfig,
101 ) -> Option<RangeInfo<HoverResult>> {
102 let sema = hir::Semantics::new(db);
103 let file = sema.parse(file_id).syntax().clone();
105 if !range.is_empty() {
106 return hover_ranged(&file, range, &sema, config);
108 let offset = range.start();
110 let token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
111 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] => 3,
112 T!['('] | T![')'] => 2,
113 kind if kind.is_trivia() => 0,
117 let mut seen = HashSet::default();
119 let mut fallback = None;
120 // attributes, require special machinery as they are mere ident tokens
122 let descend_macros = sema.descend_into_macros_many(token.clone());
124 for token in &descend_macros {
125 if token.kind() != COMMENT {
126 if let Some(attr) = token.ancestors().find_map(ast::Attr::cast) {
128 if let Some(res) = try_hover_for_lint(&attr, &token) {
133 try_resolve_derive_input_at(&sema, &attr, &token).map(Definition::Macro);
134 if let Some(def) = def {
135 if let Some(hover) = hover_for_definition(
139 &token.parent().unwrap(),
142 return Some(RangeInfo::new(token.text_range(), hover));
152 .filter_map(|token| match token.parent() {
154 match find_hover_result(&sema, file_id, offset, config, token, &node, &mut seen) {
155 Some(res) => match res {
156 ControlFlow::Break(inner) => Some(inner),
157 ControlFlow::Continue(_) => {
158 if fallback.is_none() {
159 // FIXME we're only taking the first fallback into account that's not `None`
160 fallback = hover_for_keyword(&sema, config, &token)
161 .or(type_hover(&sema, config, &token));
171 // reduce all descends into a single `RangeInfo`
172 // that spans from the earliest start to the latest end (fishy/FIXME),
173 // concatenates all `Markup`s with `\n---\n`,
174 // and accumulates all actions into its `actions` vector.
175 .reduce(|mut acc, RangeInfo { range, mut info }| {
176 let start = acc.range.start().min(range.start());
177 let end = acc.range.end().max(range.end());
179 acc.range = TextRange::new(start, end);
180 acc.info.actions.append(&mut info.actions);
181 acc.info.markup = Markup::from(format!("{}\n---\n{}", acc.info.markup, info.markup));
187 fn find_hover_result(
188 sema: &Semantics<RootDatabase>,
191 config: &HoverConfig,
194 seen: &mut HashSet<Definition>,
195 ) -> Option<ControlFlow<RangeInfo<HoverResult>>> {
196 let mut range_override = None;
198 // intra-doc links and attributes are special cased
199 // so don't add them to the `seen` duplicate check
200 let mut add_to_seen_definitions = true;
202 let definition = find_definition(sema, node).or_else(|| {
204 // FIXME: move comment + attribute special cases somewhere else to simplify control flow,
205 // hopefully simplifying the return type of this function in the process
206 // (the `Break`/`Continue` distinction is needed to decide whether to use fallback hovers)
208 // FIXME: hovering the intra doc link to `Foo` not working:
214 if token.kind() == COMMENT {
215 add_to_seen_definitions = false;
216 cov_mark::hit!(no_highlight_on_comment_hover);
217 let (attributes, def) = doc_attributes(sema, node)?;
218 let (docs, doc_mapping) = attributes.docs_with_rangemap(sema.db)?;
219 let (idl_range, link, ns) = extract_definitions_from_docs(&docs).into_iter().find_map(
220 |(range, link, ns)| {
221 let mapped = doc_mapping.map(range)?;
222 (mapped.file_id == file_id.into() && mapped.value.contains(offset))
223 .then(|| (mapped.value, link, ns))
226 range_override = Some(idl_range);
227 Some(match resolve_doc_path_for_def(sema.db, def, &link, ns)? {
228 Either::Left(it) => Definition::ModuleDef(it),
229 Either::Right(it) => Definition::Macro(it),
236 if let Some(definition) = definition {
238 if seen.contains(&definition) {
241 if add_to_seen_definitions {
242 seen.insert(definition);
244 if let Some(res) = hover_for_definition(sema, file_id, definition, &node, config) {
245 let range = range_override.unwrap_or_else(|| sema.original_range(&node).range);
246 return Some(ControlFlow::Break(RangeInfo::new(range, res)));
250 Some(ControlFlow::Continue(()))
254 sema: &Semantics<RootDatabase>,
255 config: &HoverConfig,
257 ) -> Option<RangeInfo<HoverResult>> {
258 if token.kind() == COMMENT {
263 .take_while(|it| !ast::Item::can_cast(it.kind()))
264 .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
266 let expr_or_pat = match_ast! {
268 ast::Expr(it) => Either::Left(it),
269 ast::Pat(it) => Either::Right(it),
270 // If this node is a MACRO_CALL, it means that `descend_into_macros_many` failed to resolve.
271 // (e.g expanding a builtin macro). So we give up here.
272 ast::MacroCall(_it) => return None,
277 let res = hover_type_info(&sema, config, &expr_or_pat)?;
278 let range = sema.original_range(&node).range;
279 Some(RangeInfo::new(range, res))
284 range: syntax::TextRange,
285 sema: &Semantics<RootDatabase>,
286 config: &HoverConfig,
287 ) -> Option<RangeInfo<HoverResult>> {
288 let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
291 ast::Expr(expr) => Some(Either::Left(expr)),
292 ast::Pat(pat) => Some(Either::Right(pat)),
297 let res = match &expr_or_pat {
298 Either::Left(ast::Expr::TryExpr(try_expr)) => hover_try_expr(sema, config, try_expr),
299 Either::Left(ast::Expr::PrefixExpr(prefix_expr))
300 if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
302 hover_deref_expr(sema, config, prefix_expr)
306 let res = res.or_else(|| hover_type_info(sema, config, &expr_or_pat));
308 let range = match expr_or_pat {
309 Either::Left(it) => it.syntax().text_range(),
310 Either::Right(it) => it.syntax().text_range(),
312 RangeInfo::new(range, it)
317 sema: &Semantics<RootDatabase>,
318 config: &HoverConfig,
319 try_expr: &ast::TryExpr,
320 ) -> Option<HoverResult> {
321 let inner_ty = sema.type_of_expr(&try_expr.expr()?)?.original;
322 let mut ancestors = try_expr.syntax().ancestors();
323 let mut body_ty = loop {
324 let next = ancestors.next()?;
327 ast::Fn(fn_) => sema.to_def(&fn_)?.ret_type(sema.db),
328 ast::Item(__) => return None,
329 ast::ClosureExpr(closure) => sema.type_of_expr(&closure.body()?)?.original,
330 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
331 sema.type_of_expr(&effect.block_expr()?.into())?.original
340 if inner_ty == body_ty {
344 let mut inner_ty = inner_ty;
345 let mut s = "Try Target".to_owned();
347 let adts = inner_ty.as_adt().zip(body_ty.as_adt());
348 if let Some((hir::Adt::Enum(inner), hir::Adt::Enum(body))) = adts {
349 let famous_defs = FamousDefs(sema, sema.scope(&try_expr.syntax()).krate());
350 // special case for two options, there is no value in showing them
351 if let Some(option_enum) = famous_defs.core_option_Option() {
352 if inner == option_enum && body == option_enum {
353 cov_mark::hit!(hover_try_expr_opt_opt);
358 // special case two results to show the error variants only
359 if let Some(result_enum) = famous_defs.core_result_Result() {
360 if inner == result_enum && body == result_enum {
361 let error_type_args =
362 inner_ty.type_arguments().nth(1).zip(body_ty.type_arguments().nth(1));
363 if let Some((inner, body)) = error_type_args {
366 s = "Try Error".to_owned();
372 let mut res = HoverResult::default();
374 let mut targets: Vec<hir::ModuleDef> = Vec::new();
375 let mut push_new_def = |item: hir::ModuleDef| {
376 if !targets.contains(&item) {
380 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
381 walk_and_push_ty(sema.db, &body_ty, &mut push_new_def);
382 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
384 let inner_ty = inner_ty.display(sema.db).to_string();
385 let body_ty = body_ty.display(sema.db).to_string();
386 let ty_len_max = inner_ty.len().max(body_ty.len());
388 let l = "Propagated as: ".len() - " Type: ".len();
389 let static_text_len_diff = l as isize - s.len() as isize;
390 let tpad = static_text_len_diff.max(0) as usize;
391 let ppad = static_text_len_diff.min(0).abs() as usize;
393 res.markup = format!(
394 "{bt_start}{} Type: {:>pad0$}\nPropagated as: {:>pad1$}\n{bt_end}",
398 pad0 = ty_len_max + tpad,
399 pad1 = ty_len_max + ppad,
400 bt_start = if config.markdown() { "```text\n" } else { "" },
401 bt_end = if config.markdown() { "```\n" } else { "" }
408 sema: &Semantics<RootDatabase>,
409 config: &HoverConfig,
410 deref_expr: &ast::PrefixExpr,
411 ) -> Option<HoverResult> {
412 let inner_ty = sema.type_of_expr(&deref_expr.expr()?)?.original;
413 let TypeInfo { original, adjusted } =
414 sema.type_of_expr(&ast::Expr::from(deref_expr.clone()))?;
416 let mut res = HoverResult::default();
417 let mut targets: Vec<hir::ModuleDef> = Vec::new();
418 let mut push_new_def = |item: hir::ModuleDef| {
419 if !targets.contains(&item) {
423 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
424 walk_and_push_ty(sema.db, &original, &mut push_new_def);
426 res.markup = if let Some(adjusted_ty) = adjusted {
427 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
428 let original = original.display(sema.db).to_string();
429 let adjusted = adjusted_ty.display(sema.db).to_string();
430 let inner = inner_ty.display(sema.db).to_string();
431 let type_len = "To type: ".len();
432 let coerced_len = "Coerced to: ".len();
433 let deref_len = "Dereferenced from: ".len();
434 let max_len = (original.len() + type_len)
435 .max(adjusted.len() + coerced_len)
436 .max(inner.len() + deref_len);
438 "{bt_start}Dereferenced from: {:>ipad$}\nTo type: {:>apad$}\nCoerced to: {:>opad$}\n{bt_end}",
442 ipad = max_len - deref_len,
443 apad = max_len - type_len,
444 opad = max_len - coerced_len,
445 bt_start = if config.markdown() { "```text\n" } else { "" },
446 bt_end = if config.markdown() { "```\n" } else { "" }
450 let original = original.display(sema.db).to_string();
451 let inner = inner_ty.display(sema.db).to_string();
452 let type_len = "To type: ".len();
453 let deref_len = "Dereferenced from: ".len();
454 let max_len = (original.len() + type_len).max(inner.len() + deref_len);
456 "{bt_start}Dereferenced from: {:>ipad$}\nTo type: {:>apad$}\n{bt_end}",
459 ipad = max_len - deref_len,
460 apad = max_len - type_len,
461 bt_start = if config.markdown() { "```text\n" } else { "" },
462 bt_end = if config.markdown() { "```\n" } else { "" }
466 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
472 sema: &Semantics<RootDatabase>,
473 config: &HoverConfig,
474 expr_or_pat: &Either<ast::Expr, ast::Pat>,
475 ) -> Option<HoverResult> {
476 let TypeInfo { original, adjusted } = match expr_or_pat {
477 Either::Left(expr) => sema.type_of_expr(expr)?,
478 Either::Right(pat) => sema.type_of_pat(pat)?,
481 let mut res = HoverResult::default();
482 let mut targets: Vec<hir::ModuleDef> = Vec::new();
483 let mut push_new_def = |item: hir::ModuleDef| {
484 if !targets.contains(&item) {
488 walk_and_push_ty(sema.db, &original, &mut push_new_def);
490 res.markup = if let Some(adjusted_ty) = adjusted {
491 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
492 let original = original.display(sema.db).to_string();
493 let adjusted = adjusted_ty.display(sema.db).to_string();
494 let static_text_diff_len = "Coerced to: ".len() - "Type: ".len();
496 "{bt_start}Type: {:>apad$}\nCoerced to: {:>opad$}\n{bt_end}",
499 apad = static_text_diff_len + adjusted.len().max(original.len()),
500 opad = original.len(),
501 bt_start = if config.markdown() { "```text\n" } else { "" },
502 bt_end = if config.markdown() { "```\n" } else { "" }
506 if config.markdown() {
507 Markup::fenced_block(&original.display(sema.db))
509 original.display(sema.db).to_string().into()
512 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
516 fn try_hover_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option<RangeInfo<HoverResult>> {
517 let (path, tt) = attr.as_simple_call()?;
518 if !tt.syntax().text_range().contains(token.text_range().start()) {
521 let (is_clippy, lints) = match &*path {
522 "feature" => (false, FEATURES),
523 "allow" | "deny" | "forbid" | "warn" => {
524 let is_clippy = algo::non_trivia_sibling(token.clone().into(), Direction::Prev)
525 .filter(|t| t.kind() == T![:])
526 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
527 .filter(|t| t.kind() == T![:])
528 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
530 t.kind() == T![ident] && t.into_token().map_or(false, |t| t.text() == "clippy")
535 (false, DEFAULT_LINTS)
542 let needle = if is_clippy {
543 tmp = format!("clippy::{}", token.text());
550 lints.binary_search_by_key(&needle, |lint| lint.label).ok().map(|idx| &lints[idx])?;
554 markup: Markup::from(format!("```\n{}\n```\n___\n\n{}", lint.label, lint.description)),
560 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
561 fn to_action(nav_target: NavigationTarget) -> HoverAction {
562 HoverAction::Implementation(FilePosition {
563 file_id: nav_target.file_id,
564 offset: nav_target.focus_or_full_range().start(),
568 let adt = match def {
569 Definition::ModuleDef(hir::ModuleDef::Trait(it)) => {
570 return it.try_to_nav(db).map(to_action)
572 Definition::ModuleDef(hir::ModuleDef::Adt(it)) => Some(it),
573 Definition::SelfType(it) => it.self_ty(db).as_adt(),
576 adt.try_to_nav(db).map(to_action)
579 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
581 Definition::ModuleDef(hir::ModuleDef::Function(it)) => {
582 it.try_to_nav(db).map(|nav_target| {
583 HoverAction::Reference(FilePosition {
584 file_id: nav_target.file_id,
585 offset: nav_target.focus_or_full_range().start(),
594 sema: &hir::Semantics<RootDatabase>,
597 ) -> Option<HoverAction> {
599 Definition::ModuleDef(it) => match it {
600 hir::ModuleDef::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
601 hir::ModuleDef::Function(func) => {
602 let src = func.source(sema.db)?;
603 if src.file_id != file_id.into() {
604 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
605 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
609 runnable_fn(sema, func).map(HoverAction::Runnable)
617 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
618 let mut targets: Vec<hir::ModuleDef> = Vec::new();
619 let mut push_new_def = |item: hir::ModuleDef| {
620 if !targets.contains(&item) {
625 if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
626 it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
629 Definition::Local(it) => it.ty(db),
630 Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
631 Definition::Field(field) => field.ty(db),
635 walk_and_push_ty(db, &ty, &mut push_new_def);
638 Some(HoverAction::goto_type_from_targets(db, targets))
644 push_new_def: &mut dyn FnMut(hir::ModuleDef),
647 if let Some(adt) = t.as_adt() {
648 push_new_def(adt.into());
649 } else if let Some(trait_) = t.as_dyn_trait() {
650 push_new_def(trait_.into());
651 } else if let Some(traits) = t.as_impl_traits(db) {
652 traits.into_iter().for_each(|it| push_new_def(it.into()));
653 } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
654 push_new_def(trait_.into());
659 fn hover_markup(docs: Option<String>, desc: String, mod_path: Option<String>) -> Option<Markup> {
660 let mut buf = String::new();
662 if let Some(mod_path) = mod_path {
663 if !mod_path.is_empty() {
664 format_to!(buf, "```rust\n{}\n```\n\n", mod_path);
667 format_to!(buf, "```rust\n{}\n```", desc);
669 if let Some(doc) = docs {
670 format_to!(buf, "\n___\n\n{}", doc);
679 config: &HoverConfig,
681 let markup = markup.as_str();
682 let markup = if !config.markdown() {
683 remove_markdown(markup)
684 } else if config.links_in_hover {
685 rewrite_links(db, markup, def)
692 fn definition_owner_name(db: &RootDatabase, def: &Definition) -> Option<String> {
694 Definition::Field(f) => Some(f.parent_def(db).name(db)),
695 Definition::Local(l) => l.parent(db).name(db),
696 Definition::ModuleDef(md) => match md {
697 hir::ModuleDef::Function(f) => match f.as_assoc_item(db)?.container(db) {
698 hir::AssocItemContainer::Trait(t) => Some(t.name(db)),
699 hir::AssocItemContainer::Impl(i) => i.self_ty(db).as_adt().map(|adt| adt.name(db)),
701 hir::ModuleDef::Variant(e) => Some(e.parent_enum(db).name(db)),
706 .map(|name| name.to_string())
709 fn render_path(db: &RootDatabase, module: hir::Module, item_name: Option<String>) -> String {
711 db.crate_graph()[module.krate().into()].display_name.as_ref().map(|it| it.to_string());
712 let module_path = module
716 .flat_map(|it| it.name(db).map(|name| name.to_string()));
717 crate_name.into_iter().chain(module_path).chain(item_name).join("::")
720 fn definition_mod_path(db: &RootDatabase, def: &Definition) -> Option<String> {
721 if let Definition::GenericParam(_) = def {
724 def.module(db).map(|module| render_path(db, module, definition_owner_name(db, def)))
727 pub(crate) fn find_definition(
728 sema: &Semantics<RootDatabase>,
730 ) -> Option<Definition> {
733 ast::Name(name) => NameClass::classify(sema, &name).map(|class| match class {
734 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
735 NameClass::PatFieldShorthand { local_def, field_ref: _ } => Definition::Local(local_def),
737 ast::NameRef(name_ref) => NameRefClass::classify(sema, &name_ref).map(|class| match class {
738 NameRefClass::Definition(def) => def,
739 NameRefClass::FieldShorthand { local_ref: _, field_ref } => {
740 Definition::Field(field_ref)
743 ast::Lifetime(lifetime) => NameClass::classify_lifetime(&sema, &lifetime).map_or_else(
745 NameRefClass::classify_lifetime(&sema, &lifetime).and_then(|class| match class {
746 NameRefClass::Definition(it) => Some(it),
757 pub(crate) fn hover_for_definition(
758 sema: &Semantics<RootDatabase>,
760 definition: Definition,
762 config: &HoverConfig,
763 ) -> Option<HoverResult> {
764 let famous_defs = match &definition {
765 Definition::ModuleDef(hir::ModuleDef::BuiltinType(_)) => {
766 Some(FamousDefs(&sema, sema.scope(&node).krate()))
770 if let Some(markup) = markup_for_definition(sema.db, definition, famous_defs.as_ref(), config) {
771 let mut res = HoverResult::default();
772 res.markup = process_markup(sema.db, definition, &markup, config);
773 if let Some(action) = show_implementations_action(sema.db, definition) {
774 res.actions.push(action);
777 if let Some(action) = show_fn_references_action(sema.db, definition) {
778 res.actions.push(action);
781 if let Some(action) = runnable_action(&sema, definition, file_id) {
782 res.actions.push(action);
785 if let Some(action) = goto_type_action_for_def(sema.db, definition) {
786 res.actions.push(action);
793 fn markup_for_definition(
796 famous_defs: Option<&FamousDefs>,
797 config: &HoverConfig,
798 ) -> Option<Markup> {
799 let mod_path = definition_mod_path(db, &def);
800 let (label, docs) = match def {
801 Definition::Macro(it) => (
802 match &it.source(db)?.value {
803 Either::Left(mac) => macro_label(mac),
804 Either::Right(mac_fn) => fn_as_proc_macro_label(mac_fn),
808 Definition::Field(def) => label_and_docs(db, def),
809 Definition::ModuleDef(it) => match it {
810 hir::ModuleDef::Module(it) => label_and_docs(db, it),
811 hir::ModuleDef::Function(it) => label_and_docs(db, it),
812 hir::ModuleDef::Adt(it) => label_and_docs(db, it),
813 hir::ModuleDef::Variant(it) => label_and_docs(db, it),
814 hir::ModuleDef::Const(it) => label_and_docs(db, it),
815 hir::ModuleDef::Static(it) => label_and_docs(db, it),
816 hir::ModuleDef::Trait(it) => label_and_docs(db, it),
817 hir::ModuleDef::TypeAlias(it) => label_and_docs(db, it),
818 hir::ModuleDef::BuiltinType(it) => {
820 .and_then(|fd| hover_for_builtin(fd, it))
821 .or_else(|| Some(Markup::fenced_block(&it.name())))
824 Definition::Local(it) => return hover_for_local(it, db),
825 Definition::SelfType(impl_def) => {
826 impl_def.self_ty(db).as_adt().map(|adt| label_and_docs(db, adt))?
828 Definition::GenericParam(it) => label_and_docs(db, it),
829 Definition::Label(it) => return Some(Markup::fenced_block(&it.name(db))),
833 docs.filter(|_| config.documentation.is_some()).map(Into::into),
838 fn label_and_docs<D>(db: &RootDatabase, def: D) -> (String, Option<hir::Documentation>)
840 D: HasAttrs + HirDisplay,
842 let label = def.display(db).to_string();
843 let docs = def.attrs(db).docs();
848 fn hover_for_local(it: hir::Local, db: &RootDatabase) -> Option<Markup> {
850 let ty = ty.display(db);
851 let is_mut = if it.is_mut(db) { "mut " } else { "" };
852 let desc = match it.source(db).value {
853 Either::Left(ident) => {
854 let name = it.name(db).unwrap();
855 let let_kw = if ident
858 .map_or(false, |p| p.kind() == LET_STMT || p.kind() == CONDITION)
864 format!("{}{}{}: {}", let_kw, is_mut, name, ty)
866 Either::Right(_) => format!("{}self: {}", is_mut, ty),
868 hover_markup(None, desc, None)
871 fn hover_for_keyword(
872 sema: &Semantics<RootDatabase>,
873 config: &HoverConfig,
875 ) -> Option<RangeInfo<HoverResult>> {
876 if !token.kind().is_keyword() || !config.documentation.is_some() {
879 let famous_defs = FamousDefs(sema, sema.scope(&token.parent()?).krate());
880 // std exposes {}_keyword modules with docstrings on the root to document keywords
881 let keyword_mod = format!("{}_keyword", token.text());
882 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?;
883 let docs = doc_owner.attrs(sema.db).docs()?;
884 let markup = process_markup(
886 Definition::ModuleDef(doc_owner.into()),
887 &hover_markup(Some(docs.into()), token.text().into(), None)?,
890 Some(RangeInfo::new(token.text_range(), HoverResult { markup, actions: Default::default() }))
893 fn hover_for_builtin(famous_defs: &FamousDefs, builtin: hir::BuiltinType) -> Option<Markup> {
894 // std exposes prim_{} modules with docstrings on the root to document the builtins
895 let primitive_mod = format!("prim_{}", builtin.name());
896 let doc_owner = find_std_module(famous_defs, &primitive_mod)?;
897 let docs = doc_owner.attrs(famous_defs.0.db).docs()?;
898 hover_markup(Some(docs.into()), builtin.name().to_string(), None)
901 fn find_std_module(famous_defs: &FamousDefs, name: &str) -> Option<hir::Module> {
902 let db = famous_defs.0.db;
903 let std_crate = famous_defs.std()?;
904 let std_root_module = std_crate.root_module(db);
907 .find(|module| module.name(db).map_or(false, |module| module.to_string() == name))
912 use expect_test::{expect, Expect};
913 use ide_db::base_db::{FileLoader, FileRange};
914 use syntax::TextRange;
916 use crate::{fixture, hover::HoverDocFormat, HoverConfig};
918 fn check_hover_no_result(ra_fixture: &str) {
919 let (analysis, position) = fixture::position(ra_fixture);
923 links_in_hover: true,
924 documentation: Some(HoverDocFormat::Markdown),
926 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
929 assert!(hover.is_none(), "hover not expected but found: {:?}", hover.unwrap());
932 fn check(ra_fixture: &str, expect: Expect) {
933 let (analysis, position) = fixture::position(ra_fixture);
937 links_in_hover: true,
938 documentation: Some(HoverDocFormat::Markdown),
940 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
945 let content = analysis.db.file_text(position.file_id);
946 let hovered_element = &content[hover.range];
948 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
949 expect.assert_eq(&actual)
952 fn check_hover_no_links(ra_fixture: &str, expect: Expect) {
953 let (analysis, position) = fixture::position(ra_fixture);
957 links_in_hover: false,
958 documentation: Some(HoverDocFormat::Markdown),
960 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
965 let content = analysis.db.file_text(position.file_id);
966 let hovered_element = &content[hover.range];
968 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
969 expect.assert_eq(&actual)
972 fn check_hover_no_markdown(ra_fixture: &str, expect: Expect) {
973 let (analysis, position) = fixture::position(ra_fixture);
977 links_in_hover: true,
978 documentation: Some(HoverDocFormat::PlainText),
980 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
985 let content = analysis.db.file_text(position.file_id);
986 let hovered_element = &content[hover.range];
988 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
989 expect.assert_eq(&actual)
992 fn check_actions(ra_fixture: &str, expect: Expect) {
993 let (analysis, file_id, position) = fixture::range_or_position(ra_fixture);
997 links_in_hover: true,
998 documentation: Some(HoverDocFormat::Markdown),
1000 FileRange { file_id, range: position.range_or_empty() },
1004 expect.assert_debug_eq(&hover.info.actions)
1007 fn check_hover_range(ra_fixture: &str, expect: Expect) {
1008 let (analysis, range) = fixture::range(ra_fixture);
1009 let hover = analysis
1012 links_in_hover: false,
1013 documentation: Some(HoverDocFormat::Markdown),
1019 expect.assert_eq(hover.info.markup.as_str())
1022 fn check_hover_range_no_results(ra_fixture: &str) {
1023 let (analysis, range) = fixture::range(ra_fixture);
1024 let hover = analysis
1027 links_in_hover: false,
1028 documentation: Some(HoverDocFormat::Markdown),
1033 assert!(hover.is_none());
1037 fn hover_descend_macros_avoids_duplicates() {
1040 macro_rules! dupe_use {
1064 fn hover_shows_all_macro_descends() {
1113 fn hover_shows_type_of_an_expression() {
1116 pub fn foo() -> u32 { 1 }
1119 let foo_test = foo()$0;
1132 fn hover_remove_markdown_if_configured() {
1133 check_hover_no_markdown(
1135 pub fn foo() -> u32 { 1 }
1138 let foo_test = foo()$0;
1149 fn hover_shows_long_type_of_an_expression() {
1152 struct Scan<A, B, C> { a: A, b: B, c: C }
1153 struct Iter<I> { inner: I }
1154 enum Option<T> { Some(T), None }
1156 struct OtherStruct<T> { i: T }
1158 fn scan<A, B, C>(a: A, b: B, c: C) -> Iter<Scan<OtherStruct<A>, B, C>> {
1159 Iter { inner: Scan { a, b, c } }
1164 let closure = |memo: &mut u32, value: &u32, _another: &mut u32| -> Option<u32> {
1165 Option::Some(*memo + value)
1168 let mut iter$0 = scan(OtherStruct { i: num }, closure, number);
1175 let mut iter: Iter<Scan<OtherStruct<OtherStruct<i32>>, |&mut u32, &u32, &mut u32| -> Option<u32>, u32>>
1182 fn hover_shows_fn_signature() {
1183 // Single file with result
1186 pub fn foo() -> u32 { 1 }
1188 fn main() { let foo_test = fo$0o(); }
1203 // Multiple candidates but results are ambiguous.
1207 pub fn foo() -> u32 { 1 }
1210 pub fn foo() -> &str { "" }
1213 pub fn foo(a: u32, b: u32) {}
1220 fn main() { let foo_test = fo$0o(); }
1230 // Use literal `crate` in path
1235 fn foo() -> crate::X { X }
1237 fn main() { f$0oo(); }
1247 fn foo() -> crate::X
1252 // Check `super` in path
1257 mod m { pub fn foo() -> super::X { super::X } }
1259 fn main() { m::f$0oo(); }
1269 pub fn foo() -> super::X
1276 fn hover_shows_fn_signature_with_type_params() {
1279 pub fn foo<'a, T: AsRef<str>>(b: &'a T) -> &'a str { }
1281 fn main() { let foo_test = fo$0o(); }
1291 pub fn foo<'a, T>(b: &'a T) -> &'a str
1300 fn hover_shows_fn_signature_on_fn_name() {
1303 pub fn foo$0(a: u32, b: u32) -> u32 {}
1315 pub fn foo(a: u32, b: u32) -> u32
1322 fn hover_shows_fn_doc() {
1327 /// # use std::path::Path;
1329 /// foo(Path::new("hello, world!"))
1331 pub fn foo$0(_: &Path) {}
1343 pub fn foo(_: &Path)
1351 # use std::path::Path;
1353 foo(Path::new("hello, world!"))
1360 fn hover_shows_fn_doc_attr_raw_string() {
1363 #[doc = r#"Raw string doc attr"#]
1364 pub fn foo$0(_: &Path) {}
1376 pub fn foo(_: &Path)
1387 fn hover_shows_struct_field_info() {
1388 // Hovering over the field when instantiating
1391 struct Foo { field_a: u32 }
1394 let foo = Foo { field_a$0: 0, };
1410 // Hovering over the field in the definition
1413 struct Foo { field_a$0: u32 }
1416 let foo = Foo { field_a: 0 };
1434 fn hover_const_static() {
1436 r#"const foo$0: u32 = 123;"#,
1450 r#"static foo$0: u32 = 456;"#,
1466 fn hover_default_generic_types() {
1469 struct Test<K, T = u8> { k: K, t: T }
1472 let zz$0 = Test { t: 23u8, k: 33 };
1478 let zz: Test<i32, u8>
1488 enum Option<T> { Some(T) }
1491 fn main() { So$0me(12); }
1508 enum Option<T> { Some(T) }
1511 fn main() { let b$0ar = Some(12); }
1517 let bar: Option<i32>
1524 fn hover_enum_variant() {
1528 /// The None variant
1552 /// The Some variant
1556 let s = Option::Som$0e(12);
1578 fn hover_for_local_variable() {
1580 r#"fn func(foo: i32) { fo$0o; }"#,
1592 fn hover_for_local_variable_pat() {
1594 r#"fn func(fo$0o: i32) {}"#,
1606 fn hover_local_var_edge() {
1608 r#"fn func(foo: i32) { if true { $0foo; }; }"#,
1620 fn hover_for_param_edge() {
1622 r#"fn func($0foo: i32) {}"#,
1634 fn hover_for_param_with_multiple_traits() {
1639 type Target: ?Sized;
1642 type Target: ?Sized;
1644 fn f(_x$0: impl Deref<Target=u8> + DerefMut<Target=u8>) {}"#,
1649 _x: impl Deref<Target = u8> + DerefMut<Target = u8>
1656 fn test_hover_infer_associated_method_result() {
1659 struct Thing { x: u32 }
1662 fn new() -> Thing { Thing { x: 0 } }
1665 fn main() { let foo_$0test = Thing::new(); }
1678 fn test_hover_infer_associated_method_exact() {
1682 struct Thing { x: u32 }
1685 fn new() -> Thing { Thing { x: 0 } }
1689 fn main() { let foo_test = wrapper::Thing::new$0(); }
1695 test::wrapper::Thing
1706 fn test_hover_infer_associated_const_in_pattern() {
1737 fn test_hover_self() {
1740 struct Thing { x: u32 }
1742 fn new() -> Self { Self$0 { x: 0 } }
1759 struct Thing { x: u32 }
1761 fn new() -> Self$0 { Self { x: 0 } }
1780 pub fn new() -> Self$0 { Thing::A }
1799 pub fn thing(a: Self$0) {}
1817 fn test_hover_shadowing_pat() {
1838 fn test_hover_macro_invocation() {
1841 macro_rules! foo { () => {} }
1843 fn f() { fo$0o!(); }
1860 fn test_hover_macro2_invocation() {
1868 fn f() { fo$0o!(); }
1891 fn test_hover_tuple_field() {
1893 r#"struct TS(String, i32$0);"#,
1905 fn test_hover_through_macro() {
1908 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1911 fn bar() { fo$0o(); }
1929 fn test_hover_through_attr() {
1932 //- proc_macros: identity
1933 #[proc_macros::identity]
1951 fn test_hover_through_expr_in_macro() {
1954 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1955 fn foo(bar:u32) { let a = id!(ba$0r); }
1968 fn test_hover_through_expr_in_macro_recursive() {
1971 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1972 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1973 fn foo(bar:u32) { let a = id!(ba$0r); }
1986 fn test_hover_through_func_in_macro_recursive() {
1989 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1990 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1991 fn bar() -> u32 { 0 }
1992 fn foo() { let a = id!([0u32, bar($0)] ); }
2004 fn test_hover_through_literal_string_in_macro() {
2007 macro_rules! arr { ($($tt:tt)*) => { [$($tt)*)] } }
2009 let mastered_for_itunes = "";
2010 let _ = arr!("Tr$0acks", &mastered_for_itunes);
2023 fn test_hover_through_assert_macro() {
2026 #[rustc_builtin_macro]
2027 macro_rules! assert {}
2029 fn bar() -> bool { true }
2049 fn test_hover_through_literal_string_in_builtin_macro() {
2050 check_hover_no_result(
2052 #[rustc_builtin_macro]
2053 macro_rules! format {}
2056 format!("hel$0lo {}", 0);
2063 fn test_hover_non_ascii_space_doc() {
2066 /// <- `\u{3000}` here
2069 fn bar() { fo$0o(); }
2090 fn test_hover_function_show_qualifiers() {
2092 r#"async fn foo$0() {}"#,
2106 r#"pub const unsafe fn foo$0() {}"#,
2115 pub const unsafe fn foo()
2119 // Top level `pub(crate)` will be displayed as no visibility.
2121 r#"mod m { pub(crate) async unsafe extern "C" fn foo$0() {} }"#,
2130 pub(crate) async unsafe extern "C" fn foo()
2137 fn test_hover_trait_show_qualifiers() {
2139 r"unsafe trait foo$0() {}",
2156 fn test_hover_extern_crate() {
2159 //- /main.rs crate:main deps:std
2161 //- /std/lib.rs crate:std
2162 //! Standard library for this test
2176 Standard library for this test
2184 //- /main.rs crate:main deps:std
2185 extern crate std as ab$0c;
2186 //- /std/lib.rs crate:std
2187 //! Standard library for this test
2201 Standard library for this test
2210 fn test_hover_mod_with_same_name_as_function() {
2213 use self::m$0y::Bar;
2214 mod my { pub struct Bar; }
2233 fn test_hover_struct_doc_comment() {
2236 /// This is an example
2244 /// assert_eq!(6, my_crate::add_one(5));
2248 fn foo() { let bar = Ba$0r; }
2271 assert_eq!(6, my_crate::add_one(5));
2278 fn test_hover_struct_doc_attr() {
2284 fn foo() { let bar = Ba$0r; }
2305 fn test_hover_struct_doc_attr_multiple_and_mixed() {
2309 #[doc = "bar docs 1"]
2310 #[doc = "bar docs 2"]
2313 fn foo() { let bar = Ba$0r; }
2336 fn test_hover_external_url() {
2340 /// [external](https://www.google.com)
2356 [external](https://www.google.com)
2361 // Check that we don't rewrite links which we can't identify
2363 fn test_hover_unknown_target() {
2389 fn test_hover_no_links() {
2390 check_hover_no_links(
2393 /// case 1. bare URL: https://www.example.com/
2394 /// case 2. inline URL with title: [example](https://www.example.com/)
2395 /// case 3. code reference: [`Result`]
2396 /// case 4. code reference but miss footnote: [`String`]
2397 /// case 5. autolink: <http://www.example.com/>
2398 /// case 6. email address: <test@example.com>
2399 /// case 7. reference: [example][example]
2400 /// case 8. collapsed link: [example][]
2401 /// case 9. shortcut link: [example]
2402 /// case 10. inline without URL: [example]()
2403 /// case 11. reference: [foo][foo]
2404 /// case 12. reference: [foo][bar]
2405 /// case 13. collapsed link: [foo][]
2406 /// case 14. shortcut link: [foo]
2407 /// case 15. inline without URL: [foo]()
2408 /// case 16. just escaped text: \[foo]
2409 /// case 17. inline link: [Foo](foo::Foo)
2411 /// [`Result`]: ../../std/result/enum.Result.html
2412 /// [^example]: https://www.example.com/
2429 case 1. bare URL: https://www.example.com/
2430 case 2. inline URL with title: [example](https://www.example.com/)
2431 case 3. code reference: `Result`
2432 case 4. code reference but miss footnote: `String`
2433 case 5. autolink: http://www.example.com/
2434 case 6. email address: test@example.com
2435 case 7. reference: example
2436 case 8. collapsed link: example
2437 case 9. shortcut link: example
2438 case 10. inline without URL: example
2439 case 11. reference: foo
2440 case 12. reference: foo
2441 case 13. collapsed link: foo
2442 case 14. shortcut link: foo
2443 case 15. inline without URL: foo
2444 case 16. just escaped text: \[foo\]
2445 case 17. inline link: Foo
2447 [^example]: https://www.example.com/
2453 fn test_hover_macro_generated_struct_fn_doc_comment() {
2454 cov_mark::check!(hover_macro_generated_struct_fn_doc_comment);
2470 fn foo() { let bar = Bar; bar.fo$0o(); }
2491 fn test_hover_macro_generated_struct_fn_doc_attr() {
2492 cov_mark::check!(hover_macro_generated_struct_fn_doc_attr);
2500 #[doc = "Do the foo"]
2508 fn foo() { let bar = Bar; bar.fo$0o(); }
2529 fn test_hover_trait_has_impl_action() {
2531 r#"trait foo$0() {}"#,
2548 fn test_hover_struct_has_impl_action() {
2550 r"struct foo$0() {}",
2567 fn test_hover_union_has_impl_action() {
2569 r#"union foo$0() {}"#,
2586 fn test_hover_enum_has_impl_action() {
2588 r"enum foo$0() { A, B }",
2605 fn test_hover_self_has_impl_action() {
2607 r#"struct foo where Self$0:;"#,
2624 fn test_hover_test_has_action() {
2642 use_name_in_title: false,
2643 nav: NavigationTarget {
2648 focus_range: 11..19,
2669 fn test_hover_test_mod_has_action() {
2681 use_name_in_title: false,
2682 nav: NavigationTarget {
2690 description: "mod tests",
2704 fn test_hover_struct_has_goto_type_action() {
2709 fn main() { let s$0t = S{ f1:0 }; }
2716 mod_path: "test::S",
2717 nav: NavigationTarget {
2725 description: "struct S",
2736 fn test_hover_generic_struct_has_goto_type_actions() {
2740 struct S<T>{ f1: T }
2742 fn main() { let s$0t = S{ f1:Arg(0) }; }
2749 mod_path: "test::S",
2750 nav: NavigationTarget {
2755 focus_range: 24..25,
2758 description: "struct S<T>",
2762 mod_path: "test::Arg",
2763 nav: NavigationTarget {
2771 description: "struct Arg",
2782 fn test_hover_generic_struct_has_flattened_goto_type_actions() {
2786 struct S<T>{ f1: T }
2788 fn main() { let s$0t = S{ f1: S{ f1: Arg(0) } }; }
2795 mod_path: "test::S",
2796 nav: NavigationTarget {
2801 focus_range: 24..25,
2804 description: "struct S<T>",
2808 mod_path: "test::Arg",
2809 nav: NavigationTarget {
2817 description: "struct Arg",
2828 fn test_hover_tuple_has_goto_type_actions() {
2837 fn main() { let s$0t = (A(1), B(2), M::C(3) ); }
2844 mod_path: "test::A",
2845 nav: NavigationTarget {
2853 description: "struct A",
2857 mod_path: "test::B",
2858 nav: NavigationTarget {
2863 focus_range: 22..23,
2866 description: "struct B",
2870 mod_path: "test::M::C",
2871 nav: NavigationTarget {
2876 focus_range: 53..54,
2879 description: "pub struct C",
2890 fn test_hover_return_impl_trait_has_goto_type_action() {
2894 fn foo() -> impl Foo {}
2896 fn main() { let s$0t = foo(); }
2903 mod_path: "test::Foo",
2904 nav: NavigationTarget {
2912 description: "trait Foo",
2923 fn test_hover_generic_return_impl_trait_has_goto_type_action() {
2928 fn foo() -> impl Foo<S> {}
2930 fn main() { let s$0t = foo(); }
2937 mod_path: "test::Foo",
2938 nav: NavigationTarget {
2946 description: "trait Foo<T>",
2950 mod_path: "test::S",
2951 nav: NavigationTarget {
2956 focus_range: 23..24,
2959 description: "struct S",
2970 fn test_hover_return_impl_traits_has_goto_type_action() {
2975 fn foo() -> impl Foo + Bar {}
2977 fn main() { let s$0t = foo(); }
2984 mod_path: "test::Foo",
2985 nav: NavigationTarget {
2993 description: "trait Foo",
2997 mod_path: "test::Bar",
2998 nav: NavigationTarget {
3003 focus_range: 19..22,
3006 description: "trait Bar",
3017 fn test_hover_generic_return_impl_traits_has_goto_type_action() {
3025 fn foo() -> impl Foo<S1> + Bar<S2> {}
3027 fn main() { let s$0t = foo(); }
3034 mod_path: "test::Foo",
3035 nav: NavigationTarget {
3043 description: "trait Foo<T>",
3047 mod_path: "test::Bar",
3048 nav: NavigationTarget {
3053 focus_range: 22..25,
3056 description: "trait Bar<T>",
3060 mod_path: "test::S1",
3061 nav: NavigationTarget {
3066 focus_range: 39..41,
3069 description: "struct S1",
3073 mod_path: "test::S2",
3074 nav: NavigationTarget {
3079 focus_range: 52..54,
3082 description: "struct S2",
3093 fn test_hover_arg_impl_trait_has_goto_type_action() {
3097 fn foo(ar$0g: &impl Foo) {}
3104 mod_path: "test::Foo",
3105 nav: NavigationTarget {
3113 description: "trait Foo",
3124 fn test_hover_arg_impl_traits_has_goto_type_action() {
3131 fn foo(ar$0g: &impl Foo + Bar<S>) {}
3138 mod_path: "test::Foo",
3139 nav: NavigationTarget {
3147 description: "trait Foo",
3151 mod_path: "test::Bar",
3152 nav: NavigationTarget {
3157 focus_range: 19..22,
3160 description: "trait Bar<T>",
3164 mod_path: "test::S",
3165 nav: NavigationTarget {
3170 focus_range: 36..37,
3173 description: "struct S",
3184 fn test_hover_async_block_impl_trait_has_goto_type_action() {
3187 //- minicore: future
3190 let fo$0o = async { S };
3198 mod_path: "core::future::Future",
3199 nav: NavigationTarget {
3203 full_range: 254..436,
3204 focus_range: 293..299,
3207 description: "pub trait Future",
3211 mod_path: "test::S",
3212 nav: NavigationTarget {
3220 description: "struct S",
3231 fn test_hover_arg_generic_impl_trait_has_goto_type_action() {
3236 fn foo(ar$0g: &impl Foo<S>) {}
3243 mod_path: "test::Foo",
3244 nav: NavigationTarget {
3252 description: "trait Foo<T>",
3256 mod_path: "test::S",
3257 nav: NavigationTarget {
3262 focus_range: 23..24,
3265 description: "struct S",
3276 fn test_hover_dyn_return_has_goto_type_action() {
3284 fn foo() -> B<dyn Foo> {}
3286 fn main() { let s$0t = foo(); }
3293 mod_path: "test::B",
3294 nav: NavigationTarget {
3299 focus_range: 49..50,
3302 description: "struct B<T>",
3306 mod_path: "test::Foo",
3307 nav: NavigationTarget {
3315 description: "trait Foo",
3326 fn test_hover_dyn_arg_has_goto_type_action() {
3330 fn foo(ar$0g: &dyn Foo) {}
3337 mod_path: "test::Foo",
3338 nav: NavigationTarget {
3346 description: "trait Foo",
3357 fn test_hover_generic_dyn_arg_has_goto_type_action() {
3362 fn foo(ar$0g: &dyn Foo<S>) {}
3369 mod_path: "test::Foo",
3370 nav: NavigationTarget {
3378 description: "trait Foo<T>",
3382 mod_path: "test::S",
3383 nav: NavigationTarget {
3388 focus_range: 23..24,
3391 description: "struct S",
3402 fn test_hover_goto_type_action_links_order() {
3405 trait ImplTrait<T> {}
3406 trait DynTrait<T> {}
3410 fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
3417 mod_path: "test::ImplTrait",
3418 nav: NavigationTarget {
3426 description: "trait ImplTrait<T>",
3430 mod_path: "test::B",
3431 nav: NavigationTarget {
3436 focus_range: 50..51,
3439 description: "struct B<T>",
3443 mod_path: "test::DynTrait",
3444 nav: NavigationTarget {
3449 focus_range: 28..36,
3452 description: "trait DynTrait<T>",
3456 mod_path: "test::S",
3457 nav: NavigationTarget {
3462 focus_range: 65..66,
3465 description: "struct S",
3476 fn test_hover_associated_type_has_goto_type_action() {
3481 fn get(self) -> Self::Item {}
3487 impl Foo for S { type Item = Bar; }
3489 fn test() -> impl Foo { S {} }
3491 fn main() { let s$0t = test().get(); }
3498 mod_path: "test::Foo",
3499 nav: NavigationTarget {
3507 description: "trait Foo",
3518 fn test_hover_const_param_has_goto_type_action() {
3522 struct Foo<const BAR: Bar>;
3524 impl<const BAR: Bar> Foo<BAR$0> {}
3531 mod_path: "test::Bar",
3532 nav: NavigationTarget {
3540 description: "struct Bar",
3551 fn test_hover_type_param_has_goto_type_action() {
3556 fn foo<T: Foo>(t: T$0){}
3563 mod_path: "test::Foo",
3564 nav: NavigationTarget {
3572 description: "trait Foo",
3583 fn test_hover_self_has_go_to_type() {
3596 mod_path: "test::Foo",
3597 nav: NavigationTarget {
3605 description: "struct Foo",
3616 fn hover_displays_normalized_crate_names() {
3619 //- /lib.rs crate:name-with-dashes
3621 pub struct Thing { x: u32 }
3624 pub fn new() -> Thing { Thing { x: 0 } }
3628 //- /main.rs crate:main deps:name-with-dashes
3629 fn main() { let foo_test = name_with_dashes::wrapper::Thing::new$0(); }
3635 name_with_dashes::wrapper::Thing
3639 pub fn new() -> Thing
3646 fn hover_field_pat_shorthand_ref_match_ergonomics() {
3669 fn hover_self_param_shows_type() {
3688 fn hover_self_param_shows_type_for_arbitrary_self_type() {
3694 fn bar(sel$0f: Arc<Foo>) {}
3708 fn hover_doc_outer_inner() {
3715 /// This comment belongs to the function
3739 fn hover_doc_outer_inner_attribue() {
3742 #[doc = "Be quick;"]
3744 #![doc = "time is mana"]
3746 #[doc = "This comment belongs to the function"]
3770 fn hover_doc_block_style_indentend() {
3804 fn hover_comments_dont_highlight_parent() {
3805 cov_mark::check!(no_highlight_on_comment_hover);
3806 check_hover_no_result(
3834 fn hover_lifetime() {
3836 r#"fn foo<'lifetime>(_: &'lifetime$0 ()) {}"#,
3848 fn hover_type_param() {
3855 impl<T: TraitA + TraitB> Foo<T$0> where T: Sized {}
3879 // lifetimes bounds arent being tracked yet
3884 impl<T: 'static> Foo<T$0> {}
3897 fn hover_type_param_sized_bounds() {
3898 // implicit `: Sized` bound
3904 impl<T: Trait> Foo<T$0> {}
3919 impl<T: Trait + ?Sized> Foo<T$0> {}
3931 mod type_param_sized_bounds {
3935 fn single_implicit() {
3952 fn single_explicit() {
3956 fn foo<T$0: Sized>() {}
3969 fn single_relaxed() {
3973 fn foo<T$0: ?Sized>() {}
3986 fn multiple_implicit() {
3991 fn foo<T$0: Trait>() {}
4004 fn multiple_explicit() {
4009 fn foo<T$0: Trait + Sized>() {}
4022 fn multiple_relaxed() {
4027 fn foo<T$0: Trait + ?Sized>() {}
4044 fn foo<T$0: ?Sized + Sized + Sized>() {}
4058 fn foo<T$0: Sized + ?Sized + Sized + Trait>() {}
4072 fn hover_const_param() {
4075 struct Foo<const LEN: usize>;
4076 impl<const LEN: usize> Foo<LEN$0> {}
4089 fn hover_const_pat() {
4093 const FOO: usize = 3;
4120 fn hover_mod_def() {
4147 fn hover_self_in_use() {
4150 //! This should not appear
4152 /// But this should appear
4155 use foo::bar::{self$0};
4170 But this should appear
4176 fn hover_keyword() {
4179 //- /main.rs crate:main deps:std
4180 fn f() { retur$0n; }
4181 //- /libstd.rs crate:std
4182 /// Docs for return_keyword
4183 mod return_keyword {}
4194 Docs for return_keyword
4200 fn hover_builtin() {
4203 //- /main.rs crate:main deps:std
4204 cosnt _: &str$0 = ""; }
4206 //- /libstd.rs crate:std
4207 /// Docs for prim_str
4225 fn hover_macro_expanded_function() {
4228 struct S<'a, T>(&'a T);
4232 fn bar<'t, T: Clone + 't>(s: &mut S<'t, T>, t: u32) -> *mut u32 where
4234 for<'a> T: Clone + 'a
4253 fn bar<'t, T>(s: &mut S<'t, T>, t: u32) -> *mut u32
4257 for<'a> T: Clone + 'a,
4264 fn hover_intra_doc_links() {
4269 /// This is the item. Cool!
4273 /// Gives you a [`TheItem$0`].
4275 /// [`TheItem`]: theitem::TheItem
4276 pub fn gimme() -> theitem::TheItem {
4293 This is the item. Cool!
4299 fn hover_generic_assoc() {
4302 fn foo<T: A>() where T::Assoc$0: {}
4322 let _: <T>::Assoc$0;
4362 fn string_shadowed_with_inner_items() {
4365 //- /main.rs crate:main deps:alloc
4367 /// Custom `String` type.
4376 //- /alloc.rs crate:alloc
4381 /// This is `alloc::String`.
4398 Custom `String` type.
4404 fn function_doesnt_shadow_crate_in_use_tree() {
4407 //- /main.rs crate:main deps:foo
4410 //- /foo.rs crate:foo
4424 fn hover_feature() {
4426 r#"#![feature(box_syntax$0)]"#,
4436 The tracking issue for this feature is: [#49733]
4438 [#49733]: https://github.com/rust-lang/rust/issues/49733
4440 See also [`box_patterns`](box-patterns.md)
4442 ------------------------
4444 Currently the only stable way to create a `Box` is via the `Box::new` method.
4445 Also it is not possible in stable Rust to destructure a `Box` in a match
4446 pattern. The unstable `box` keyword can be used to create a `Box`. An example
4450 #![feature(box_syntax)]
4464 r#"#![allow(arithmetic_overflow$0)]"#,
4466 *arithmetic_overflow*
4472 arithmetic operation overflows
4478 fn hover_clippy_lint() {
4480 r#"#![allow(clippy::almost_swapped$0)]"#,
4484 clippy::almost_swapped
4488 Checks for `foo = bar; bar = foo` sequences.
4494 fn hover_attr_path_qualifier() {
4495 cov_mark::check!(name_ref_classify_attr_path_qualifier);
4498 //- /foo.rs crate:foo
4500 //- /lib.rs crate:main.rs deps:foo
4531 use bar::{self as foo$0};
4573 // FIXME: wrong range in macros. `es! ` should be `Copy`
4575 fn hover_attribute_in_macro() {
4578 macro_rules! identity {
4583 #[rustc_builtin_macro]
4605 fn hover_derive_input() {
4608 #[rustc_builtin_macro]
4628 #[rustc_builtin_macro]
4631 #[derive(foo::Copy$0)]
4649 fn hover_range_math() {
4652 fn f() { let expr = $01 + 2 * 3$0 }
4662 fn f() { let expr = 1 $0+ 2 * $03 }
4672 fn f() { let expr = 1 + $02 * 3$0 }
4682 fn hover_range_arrays() {
4685 fn f() { let expr = $0[1, 2, 3, 4]$0 }
4695 fn f() { let expr = [1, 2, $03, 4]$0 }
4705 fn f() { let expr = [1, 2, $03$0, 4] }
4715 fn hover_range_functions() {
4718 fn f<T>(a: &[T]) { }
4719 fn b() { $0f$0(&[1, 2, 3, 4, 5]); }
4729 fn f<T>(a: &[T]) { }
4730 fn b() { f($0&[1, 2, 3, 4, 5]$0); }
4740 fn hover_range_shows_nothing_when_invalid() {
4741 check_hover_range_no_results(
4743 fn f<T>(a: &[T]) { }
4744 fn b()$0 { f(&[1, 2, 3, 4, 5]); }$0
4748 check_hover_range_no_results(
4750 fn f<T>$0(a: &[T]) { }
4751 fn b() { f(&[1, 2, 3,$0 4, 5]); }
4755 check_hover_range_no_results(
4757 fn $0f() { let expr = [1, 2, 3, 4]$0 }
4763 fn hover_range_shows_unit_for_statements() {
4766 fn f<T>(a: &[T]) { }
4767 fn b() { $0f(&[1, 2, 3, 4, 5]); }$0
4777 fn f() { let expr$0 = $0[1, 2, 3, 4] }
4787 fn hover_range_for_pat() {
4814 fn hover_range_shows_coercions_if_applicable_expr() {
4818 let x: &u32 = $0&&&&&0$0;
4831 let x: *const u32 = $0&0$0;
4837 Coerced to: *const u32
4844 fn hover_range_shows_type_actions() {
4849 let x: &Foo = $0&&&&&Foo$0;
4857 mod_path: "test::Foo",
4858 nav: NavigationTarget {
4866 description: "struct Foo",
4877 fn hover_try_expr_res() {
4883 fn foo() -> Result<(), FooError> {
4884 Ok($0Result::<(), FooError>::Ok(())?$0)
4898 fn foo() -> Result<(), FooError> {
4899 Ok($0Result::<(), BarError>::Ok(())?$0)
4904 Try Error Type: BarError
4905 Propagated as: FooError
4912 fn hover_try_expr() {
4915 struct NotResult<T, U>(T, U);
4919 fn foo() -> NotResult<(), Looooong> {
4920 $0NotResult((), Short)?$0;
4925 Try Target Type: NotResult<(), Short>
4926 Propagated as: NotResult<(), Looooong>
4932 struct NotResult<T, U>(T, U);
4936 fn foo() -> NotResult<(), Short> {
4937 $0NotResult((), Looooong)?$0;
4942 Try Target Type: NotResult<(), Looooong>
4943 Propagated as: NotResult<(), Short>
4950 fn hover_try_expr_option() {
4951 cov_mark::check!(hover_try_expr_opt_opt);
4954 //- minicore: option, try
4956 fn foo() -> Option<()> {
4963 <Option<i32> as Try>::Output
4969 fn hover_deref_expr() {
4973 use core::ops::Deref;
4975 struct DerefExample<T> {
4979 impl<T> Deref for DerefExample<T> {
4982 fn deref(&self) -> &Self::Target {
4988 let x = DerefExample { value: 0 };
4989 let y: i32 = $0*x$0;
4994 Dereferenced from: DerefExample<i32>
5002 fn hover_deref_expr_with_coercion() {
5006 use core::ops::Deref;
5008 struct DerefExample<T> {
5012 impl<T> Deref for DerefExample<T> {
5015 fn deref(&self) -> &Self::Target {
5021 let x = DerefExample { value: &&&&&0 };
5022 let y: &i32 = $0*x$0;
5027 Dereferenced from: DerefExample<&&&&&i32>