2 use hir::{AsAssocItem, HasAttrs, HasSource, HirDisplay, Semantics, TypeInfo};
4 base_db::{FileRange, SourceDatabase},
5 defs::{Definition, NameClass, NameRefClass},
7 generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES},
8 pick_best_token, try_resolve_derive_input_at, FamousDefs,
12 use itertools::Itertools;
15 algo, ast, display::fn_as_proc_macro_label, match_ast, AstNode, AstToken, Direction,
16 SyntaxKind::*, SyntaxNode, SyntaxToken, T,
20 display::{macro_label, TryToNav},
22 doc_attributes, extract_definitions_from_docs, remove_links, resolve_doc_path_for_def,
25 markdown_remove::remove_markdown,
27 runnables::{runnable_fn, runnable_mod},
28 FileId, FilePosition, NavigationTarget, RangeInfo, Runnable,
31 #[derive(Clone, Debug, PartialEq, Eq)]
32 pub struct HoverConfig {
33 pub links_in_hover: bool,
34 pub documentation: Option<HoverDocFormat>,
38 fn markdown(&self) -> bool {
39 matches!(self.documentation, Some(HoverDocFormat::Markdown))
43 #[derive(Clone, Debug, PartialEq, Eq)]
44 pub enum HoverDocFormat {
49 #[derive(Debug, Clone)]
50 pub enum HoverAction {
52 Implementation(FilePosition),
53 Reference(FilePosition),
54 GoToType(Vec<HoverGotoTypeData>),
58 fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
62 Some(HoverGotoTypeData {
63 mod_path: render_path(
66 it.name(db).map(|name| name.to_string()),
68 nav: it.try_to_nav(db)?,
72 HoverAction::GoToType(targets)
76 #[derive(Debug, Clone, Eq, PartialEq)]
77 pub struct HoverGotoTypeData {
79 pub nav: NavigationTarget,
82 /// Contains the results when hovering over an item
83 #[derive(Debug, Default)]
84 pub struct HoverResult {
86 pub actions: Vec<HoverAction>,
91 // Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
92 // Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
94 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
97 FileRange { file_id, range }: FileRange,
99 ) -> Option<RangeInfo<HoverResult>> {
100 let sema = hir::Semantics::new(db);
101 let file = sema.parse(file_id).syntax().clone();
103 if !range.is_empty() {
104 return hover_ranged(&file, range, &sema, config);
106 let offset = range.start();
108 let token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
109 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] => 3,
110 T!['('] | T![')'] => 2,
111 kind if kind.is_trivia() => 0,
114 let token = sema.descend_into_macros(token);
116 let mut range_override = None;
117 let node = token.parent()?;
118 let definition = match_ast! {
120 ast::Name(name) => NameClass::classify(&sema, &name).map(|class| match class {
121 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
122 NameClass::PatFieldShorthand { local_def, field_ref: _ } => Definition::Local(local_def),
124 ast::NameRef(name_ref) => NameRefClass::classify(&sema, &name_ref).map(|class| match class {
125 NameRefClass::Definition(def) => def,
126 NameRefClass::FieldShorthand { local_ref: _, field_ref } => {
127 Definition::Field(field_ref)
130 ast::Lifetime(lifetime) => NameClass::classify_lifetime(&sema, &lifetime).map_or_else(
132 NameRefClass::classify_lifetime(&sema, &lifetime).and_then(|class| match class {
133 NameRefClass::Definition(it) => Some(it),
141 if ast::Comment::cast(token.clone()).is_some() {
142 cov_mark::hit!(no_highlight_on_comment_hover);
143 let (attributes, def) = doc_attributes(&sema, &node)?;
144 let (docs, doc_mapping) = attributes.docs_with_rangemap(db)?;
145 let (idl_range, link, ns) =
146 extract_definitions_from_docs(&docs).into_iter().find_map(|(range, link, ns)| {
147 let mapped = doc_mapping.map(range)?;
148 (mapped.file_id == file_id.into() && mapped.value.contains(offset)).then(||(mapped.value, link, ns))
150 range_override = Some(idl_range);
151 Some(match resolve_doc_path_for_def(db,def, &link,ns)? {
152 Either::Left(it) => Definition::ModuleDef(it),
153 Either::Right(it) => Definition::Macro(it),
155 // attributes, require special machinery as they are mere ident tokens
156 } else if let Some(attr) = token.ancestors().find_map(ast::Attr::cast) {
158 if let res@Some(_) = try_hover_for_lint(&attr, &token) {
162 range_override = Some(token.text_range());
163 try_resolve_derive_input_at(&sema, &attr, &token).map(Definition::Macro)
172 if let Some(definition) = definition {
173 let famous_defs = match &definition {
174 Definition::ModuleDef(hir::ModuleDef::BuiltinType(_)) => {
175 Some(FamousDefs(&sema, sema.scope(&node).krate()))
179 if let Some(markup) = hover_for_definition(db, definition, famous_defs.as_ref(), config) {
180 let mut res = HoverResult::default();
181 res.markup = process_markup(sema.db, definition, &markup, config);
182 if let Some(action) = show_implementations_action(db, definition) {
183 res.actions.push(action);
186 if let Some(action) = show_fn_references_action(db, definition) {
187 res.actions.push(action);
190 if let Some(action) = runnable_action(&sema, definition, file_id) {
191 res.actions.push(action);
194 if let Some(action) = goto_type_action_for_def(db, definition) {
195 res.actions.push(action);
198 let range = range_override.unwrap_or_else(|| sema.original_range(&node).range);
199 return Some(RangeInfo::new(range, res));
203 if let res @ Some(_) = hover_for_keyword(&sema, config, &token) {
207 // No definition below cursor, fall back to showing type hovers.
211 .take_while(|it| !ast::Item::can_cast(it.kind()))
212 .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
214 let expr_or_pat = match_ast! {
216 ast::Expr(it) => Either::Left(it),
217 ast::Pat(it) => Either::Right(it),
218 // If this node is a MACRO_CALL, it means that `descend_into_macros` failed to resolve.
219 // (e.g expanding a builtin macro). So we give up here.
220 ast::MacroCall(_it) => return None,
225 let res = hover_type_info(&sema, config, &expr_or_pat)?;
226 let range = sema.original_range(&node).range;
227 Some(RangeInfo::new(range, res))
232 range: syntax::TextRange,
233 sema: &Semantics<RootDatabase>,
234 config: &HoverConfig,
235 ) -> Option<RangeInfo<HoverResult>> {
236 let expr = file.covering_element(range).ancestors().find_map(|it| {
239 ast::Expr(expr) => Some(Either::Left(expr)),
240 ast::Pat(pat) => Some(Either::Right(pat)),
245 hover_type_info(sema, config, &expr).map(|it| {
246 let range = match expr {
247 Either::Left(it) => it.syntax().text_range(),
248 Either::Right(it) => it.syntax().text_range(),
250 RangeInfo::new(range, it)
255 sema: &Semantics<RootDatabase>,
256 config: &HoverConfig,
257 expr_or_pat: &Either<ast::Expr, ast::Pat>,
258 ) -> Option<HoverResult> {
259 let TypeInfo { original, adjusted } = match expr_or_pat {
260 Either::Left(expr) => sema.type_of_expr(expr)?,
261 Either::Right(pat) => sema.type_of_pat(pat)?,
264 let mut res = HoverResult::default();
265 let mut targets: Vec<hir::ModuleDef> = Vec::new();
266 let mut push_new_def = |item: hir::ModuleDef| {
267 if !targets.contains(&item) {
271 walk_and_push_ty(sema.db, &original, &mut push_new_def);
273 res.markup = if let Some(adjusted_ty) = adjusted {
274 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
275 let original = original.display(sema.db).to_string();
276 let adjusted = adjusted_ty.display(sema.db).to_string();
278 "```text\nType: {:>apad$}\nCoerced to: {:>opad$}\n```\n",
279 uncoerced = original,
281 // 6 base padding for difference of length of the two text prefixes
282 apad = 6 + adjusted.len().max(original.len()),
283 opad = original.len(),
287 if config.markdown() {
288 Markup::fenced_block(&original.display(sema.db))
290 original.display(sema.db).to_string().into()
293 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
297 fn try_hover_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option<RangeInfo<HoverResult>> {
298 let (path, tt) = attr.as_simple_call()?;
299 if !tt.syntax().text_range().contains(token.text_range().start()) {
302 let (is_clippy, lints) = match &*path {
303 "feature" => (false, FEATURES),
304 "allow" | "deny" | "forbid" | "warn" => {
305 let is_clippy = algo::non_trivia_sibling(token.clone().into(), Direction::Prev)
306 .filter(|t| t.kind() == T![:])
307 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
308 .filter(|t| t.kind() == T![:])
309 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
311 t.kind() == T![ident] && t.into_token().map_or(false, |t| t.text() == "clippy")
316 (false, DEFAULT_LINTS)
323 let needle = if is_clippy {
324 tmp = format!("clippy::{}", token.text());
331 lints.binary_search_by_key(&needle, |lint| lint.label).ok().map(|idx| &lints[idx])?;
335 markup: Markup::from(format!("```\n{}\n```\n___\n\n{}", lint.label, lint.description)),
341 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
342 fn to_action(nav_target: NavigationTarget) -> HoverAction {
343 HoverAction::Implementation(FilePosition {
344 file_id: nav_target.file_id,
345 offset: nav_target.focus_or_full_range().start(),
349 let adt = match def {
350 Definition::ModuleDef(hir::ModuleDef::Trait(it)) => {
351 return it.try_to_nav(db).map(to_action)
353 Definition::ModuleDef(hir::ModuleDef::Adt(it)) => Some(it),
354 Definition::SelfType(it) => it.self_ty(db).as_adt(),
357 adt.try_to_nav(db).map(to_action)
360 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
362 Definition::ModuleDef(hir::ModuleDef::Function(it)) => {
363 it.try_to_nav(db).map(|nav_target| {
364 HoverAction::Reference(FilePosition {
365 file_id: nav_target.file_id,
366 offset: nav_target.focus_or_full_range().start(),
375 sema: &hir::Semantics<RootDatabase>,
378 ) -> Option<HoverAction> {
380 Definition::ModuleDef(it) => match it {
381 hir::ModuleDef::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
382 hir::ModuleDef::Function(func) => {
383 let src = func.source(sema.db)?;
384 if src.file_id != file_id.into() {
385 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
386 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
390 runnable_fn(sema, func).map(HoverAction::Runnable)
398 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
399 let mut targets: Vec<hir::ModuleDef> = Vec::new();
400 let mut push_new_def = |item: hir::ModuleDef| {
401 if !targets.contains(&item) {
406 if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
407 it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
410 Definition::Local(it) => it.ty(db),
411 Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
412 Definition::Field(field) => field.ty(db),
416 walk_and_push_ty(db, &ty, &mut push_new_def);
419 Some(HoverAction::goto_type_from_targets(db, targets))
425 push_new_def: &mut dyn FnMut(hir::ModuleDef),
428 if let Some(adt) = t.as_adt() {
429 push_new_def(adt.into());
430 } else if let Some(trait_) = t.as_dyn_trait() {
431 push_new_def(trait_.into());
432 } else if let Some(traits) = t.as_impl_traits(db) {
433 traits.into_iter().for_each(|it| push_new_def(it.into()));
434 } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
435 push_new_def(trait_.into());
440 fn hover_markup(docs: Option<String>, desc: String, mod_path: Option<String>) -> Option<Markup> {
441 let mut buf = String::new();
443 if let Some(mod_path) = mod_path {
444 if !mod_path.is_empty() {
445 format_to!(buf, "```rust\n{}\n```\n\n", mod_path);
448 format_to!(buf, "```rust\n{}\n```", desc);
450 if let Some(doc) = docs {
451 format_to!(buf, "\n___\n\n{}", doc);
460 config: &HoverConfig,
462 let markup = markup.as_str();
463 let markup = if !config.markdown() {
464 remove_markdown(markup)
465 } else if config.links_in_hover {
466 rewrite_links(db, markup, def)
473 fn definition_owner_name(db: &RootDatabase, def: &Definition) -> Option<String> {
475 Definition::Field(f) => Some(f.parent_def(db).name(db)),
476 Definition::Local(l) => l.parent(db).name(db),
477 Definition::ModuleDef(md) => match md {
478 hir::ModuleDef::Function(f) => match f.as_assoc_item(db)?.container(db) {
479 hir::AssocItemContainer::Trait(t) => Some(t.name(db)),
480 hir::AssocItemContainer::Impl(i) => i.self_ty(db).as_adt().map(|adt| adt.name(db)),
482 hir::ModuleDef::Variant(e) => Some(e.parent_enum(db).name(db)),
487 .map(|name| name.to_string())
490 fn render_path(db: &RootDatabase, module: hir::Module, item_name: Option<String>) -> String {
492 db.crate_graph()[module.krate().into()].display_name.as_ref().map(|it| it.to_string());
493 let module_path = module
497 .flat_map(|it| it.name(db).map(|name| name.to_string()));
498 crate_name.into_iter().chain(module_path).chain(item_name).join("::")
501 fn definition_mod_path(db: &RootDatabase, def: &Definition) -> Option<String> {
502 if let Definition::GenericParam(_) = def {
505 def.module(db).map(|module| render_path(db, module, definition_owner_name(db, def)))
508 fn hover_for_definition(
511 famous_defs: Option<&FamousDefs>,
512 config: &HoverConfig,
513 ) -> Option<Markup> {
514 let mod_path = definition_mod_path(db, &def);
515 let (label, docs) = match def {
516 Definition::Macro(it) => (
517 match &it.source(db)?.value {
518 Either::Left(mac) => macro_label(mac),
519 Either::Right(mac_fn) => fn_as_proc_macro_label(mac_fn),
523 Definition::Field(def) => label_and_docs(db, def),
524 Definition::ModuleDef(it) => match it {
525 hir::ModuleDef::Module(it) => label_and_docs(db, it),
526 hir::ModuleDef::Function(it) => label_and_docs(db, it),
527 hir::ModuleDef::Adt(it) => label_and_docs(db, it),
528 hir::ModuleDef::Variant(it) => label_and_docs(db, it),
529 hir::ModuleDef::Const(it) => label_and_docs(db, it),
530 hir::ModuleDef::Static(it) => label_and_docs(db, it),
531 hir::ModuleDef::Trait(it) => label_and_docs(db, it),
532 hir::ModuleDef::TypeAlias(it) => label_and_docs(db, it),
533 hir::ModuleDef::BuiltinType(it) => {
535 .and_then(|fd| hover_for_builtin(fd, it))
536 .or_else(|| Some(Markup::fenced_block(&it.name())))
539 Definition::Local(it) => return hover_for_local(it, db),
540 Definition::SelfType(impl_def) => {
541 impl_def.self_ty(db).as_adt().map(|adt| label_and_docs(db, adt))?
543 Definition::GenericParam(it) => label_and_docs(db, it),
544 Definition::Label(it) => return Some(Markup::fenced_block(&it.name(db))),
548 docs.filter(|_| config.documentation.is_some()).map(Into::into),
553 fn label_and_docs<D>(db: &RootDatabase, def: D) -> (String, Option<hir::Documentation>)
555 D: HasAttrs + HirDisplay,
557 let label = def.display(db).to_string();
558 let docs = def.attrs(db).docs();
563 fn hover_for_local(it: hir::Local, db: &RootDatabase) -> Option<Markup> {
565 let ty = ty.display(db);
566 let is_mut = if it.is_mut(db) { "mut " } else { "" };
567 let desc = match it.source(db).value {
568 Either::Left(ident) => {
569 let name = it.name(db).unwrap();
570 let let_kw = if ident
573 .map_or(false, |p| p.kind() == LET_STMT || p.kind() == CONDITION)
579 format!("{}{}{}: {}", let_kw, is_mut, name, ty)
581 Either::Right(_) => format!("{}self: {}", is_mut, ty),
583 hover_markup(None, desc, None)
586 fn hover_for_keyword(
587 sema: &Semantics<RootDatabase>,
588 config: &HoverConfig,
590 ) -> Option<RangeInfo<HoverResult>> {
591 if !token.kind().is_keyword() || !config.documentation.is_some() {
594 let famous_defs = FamousDefs(sema, sema.scope(&token.parent()?).krate());
595 // std exposes {}_keyword modules with docstrings on the root to document keywords
596 let keyword_mod = format!("{}_keyword", token.text());
597 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?;
598 let docs = doc_owner.attrs(sema.db).docs()?;
599 let markup = process_markup(
601 Definition::ModuleDef(doc_owner.into()),
602 &hover_markup(Some(docs.into()), token.text().into(), None)?,
605 Some(RangeInfo::new(token.text_range(), HoverResult { markup, actions: Default::default() }))
608 fn hover_for_builtin(famous_defs: &FamousDefs, builtin: hir::BuiltinType) -> Option<Markup> {
609 // std exposes prim_{} modules with docstrings on the root to document the builtins
610 let primitive_mod = format!("prim_{}", builtin.name());
611 let doc_owner = find_std_module(famous_defs, &primitive_mod)?;
612 let docs = doc_owner.attrs(famous_defs.0.db).docs()?;
613 hover_markup(Some(docs.into()), builtin.name().to_string(), None)
616 fn find_std_module(famous_defs: &FamousDefs, name: &str) -> Option<hir::Module> {
617 let db = famous_defs.0.db;
618 let std_crate = famous_defs.std()?;
619 let std_root_module = std_crate.root_module(db);
622 .find(|module| module.name(db).map_or(false, |module| module.to_string() == name))
627 use expect_test::{expect, Expect};
628 use ide_db::base_db::{FileLoader, FileRange};
629 use syntax::TextRange;
631 use crate::{fixture, hover::HoverDocFormat, HoverConfig};
633 fn check_hover_no_result(ra_fixture: &str) {
634 let (analysis, position) = fixture::position(ra_fixture);
638 links_in_hover: true,
639 documentation: Some(HoverDocFormat::Markdown),
641 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
644 assert!(hover.is_none());
647 fn check(ra_fixture: &str, expect: Expect) {
648 let (analysis, position) = fixture::position(ra_fixture);
652 links_in_hover: true,
653 documentation: Some(HoverDocFormat::Markdown),
655 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
660 let content = analysis.db.file_text(position.file_id);
661 let hovered_element = &content[hover.range];
663 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
664 expect.assert_eq(&actual)
667 fn check_hover_no_links(ra_fixture: &str, expect: Expect) {
668 let (analysis, position) = fixture::position(ra_fixture);
672 links_in_hover: false,
673 documentation: Some(HoverDocFormat::Markdown),
675 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
680 let content = analysis.db.file_text(position.file_id);
681 let hovered_element = &content[hover.range];
683 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
684 expect.assert_eq(&actual)
687 fn check_hover_no_markdown(ra_fixture: &str, expect: Expect) {
688 let (analysis, position) = fixture::position(ra_fixture);
692 links_in_hover: true,
693 documentation: Some(HoverDocFormat::PlainText),
695 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
700 let content = analysis.db.file_text(position.file_id);
701 let hovered_element = &content[hover.range];
703 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
704 expect.assert_eq(&actual)
707 fn check_actions(ra_fixture: &str, expect: Expect) {
708 let (analysis, file_id, position) = fixture::range_or_position(ra_fixture);
712 links_in_hover: true,
713 documentation: Some(HoverDocFormat::Markdown),
715 FileRange { file_id, range: position.range_or_empty() },
719 expect.assert_debug_eq(&hover.info.actions)
722 fn check_hover_range(ra_fixture: &str, expect: Expect) {
723 let (analysis, range) = fixture::range(ra_fixture);
727 links_in_hover: false,
728 documentation: Some(HoverDocFormat::Markdown),
734 expect.assert_eq(hover.info.markup.as_str())
737 fn check_hover_range_no_results(ra_fixture: &str) {
738 let (analysis, range) = fixture::range(ra_fixture);
742 links_in_hover: false,
743 documentation: Some(HoverDocFormat::Markdown),
748 assert!(hover.is_none());
752 fn hover_shows_type_of_an_expression() {
755 pub fn foo() -> u32 { 1 }
758 let foo_test = foo()$0;
771 fn hover_remove_markdown_if_configured() {
772 check_hover_no_markdown(
774 pub fn foo() -> u32 { 1 }
777 let foo_test = foo()$0;
788 fn hover_shows_long_type_of_an_expression() {
791 struct Scan<A, B, C> { a: A, b: B, c: C }
792 struct Iter<I> { inner: I }
793 enum Option<T> { Some(T), None }
795 struct OtherStruct<T> { i: T }
797 fn scan<A, B, C>(a: A, b: B, c: C) -> Iter<Scan<OtherStruct<A>, B, C>> {
798 Iter { inner: Scan { a, b, c } }
803 let closure = |memo: &mut u32, value: &u32, _another: &mut u32| -> Option<u32> {
804 Option::Some(*memo + value)
807 let mut iter$0 = scan(OtherStruct { i: num }, closure, number);
814 let mut iter: Iter<Scan<OtherStruct<OtherStruct<i32>>, |&mut u32, &u32, &mut u32| -> Option<u32>, u32>>
821 fn hover_shows_fn_signature() {
822 // Single file with result
825 pub fn foo() -> u32 { 1 }
827 fn main() { let foo_test = fo$0o(); }
842 // Multiple candidates but results are ambiguous.
846 pub fn foo() -> u32 { 1 }
849 pub fn foo() -> &str { "" }
852 pub fn foo(a: u32, b: u32) {}
859 fn main() { let foo_test = fo$0o(); }
871 fn hover_shows_fn_signature_with_type_params() {
874 pub fn foo<'a, T: AsRef<str>>(b: &'a T) -> &'a str { }
876 fn main() { let foo_test = fo$0o(); }
886 pub fn foo<'a, T>(b: &'a T) -> &'a str
895 fn hover_shows_fn_signature_on_fn_name() {
898 pub fn foo$0(a: u32, b: u32) -> u32 {}
910 pub fn foo(a: u32, b: u32) -> u32
917 fn hover_shows_fn_doc() {
922 /// # use std::path::Path;
924 /// foo(Path::new("hello, world!"))
926 pub fn foo$0(_: &Path) {}
946 # use std::path::Path;
948 foo(Path::new("hello, world!"))
955 fn hover_shows_fn_doc_attr_raw_string() {
958 #[doc = r#"Raw string doc attr"#]
959 pub fn foo$0(_: &Path) {}
982 fn hover_shows_struct_field_info() {
983 // Hovering over the field when instantiating
986 struct Foo { field_a: u32 }
989 let foo = Foo { field_a$0: 0, };
1005 // Hovering over the field in the definition
1008 struct Foo { field_a$0: u32 }
1011 let foo = Foo { field_a: 0 };
1029 fn hover_const_static() {
1031 r#"const foo$0: u32 = 123;"#,
1045 r#"static foo$0: u32 = 456;"#,
1061 fn hover_default_generic_types() {
1064 struct Test<K, T = u8> { k: K, t: T }
1067 let zz$0 = Test { t: 23u8, k: 33 };
1073 let zz: Test<i32, u8>
1083 enum Option<T> { Some(T) }
1086 fn main() { So$0me(12); }
1103 enum Option<T> { Some(T) }
1106 fn main() { let b$0ar = Some(12); }
1112 let bar: Option<i32>
1119 fn hover_enum_variant() {
1123 /// The None variant
1147 /// The Some variant
1151 let s = Option::Som$0e(12);
1173 fn hover_for_local_variable() {
1175 r#"fn func(foo: i32) { fo$0o; }"#,
1187 fn hover_for_local_variable_pat() {
1189 r#"fn func(fo$0o: i32) {}"#,
1201 fn hover_local_var_edge() {
1203 r#"fn func(foo: i32) { if true { $0foo; }; }"#,
1215 fn hover_for_param_edge() {
1217 r#"fn func($0foo: i32) {}"#,
1229 fn hover_for_param_with_multiple_traits() {
1234 type Target: ?Sized;
1237 type Target: ?Sized;
1239 fn f(_x$0: impl Deref<Target=u8> + DerefMut<Target=u8>) {}"#,
1244 _x: impl Deref<Target = u8> + DerefMut<Target = u8>
1251 fn test_hover_infer_associated_method_result() {
1254 struct Thing { x: u32 }
1257 fn new() -> Thing { Thing { x: 0 } }
1260 fn main() { let foo_$0test = Thing::new(); }
1273 fn test_hover_infer_associated_method_exact() {
1277 struct Thing { x: u32 }
1280 fn new() -> Thing { Thing { x: 0 } }
1284 fn main() { let foo_test = wrapper::Thing::new$0(); }
1290 test::wrapper::Thing
1301 fn test_hover_infer_associated_const_in_pattern() {
1332 fn test_hover_self() {
1335 struct Thing { x: u32 }
1337 fn new() -> Self { Self$0 { x: 0 } }
1354 struct Thing { x: u32 }
1356 fn new() -> Self$0 { Self { x: 0 } }
1375 pub fn new() -> Self$0 { Thing::A }
1394 pub fn thing(a: Self$0) {}
1412 fn test_hover_shadowing_pat() {
1433 fn test_hover_macro_invocation() {
1436 macro_rules! foo { () => {} }
1438 fn f() { fo$0o!(); }
1455 fn test_hover_macro2_invocation() {
1463 fn f() { fo$0o!(); }
1486 fn test_hover_tuple_field() {
1488 r#"struct TS(String, i32$0);"#,
1500 fn test_hover_through_macro() {
1503 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1506 fn bar() { fo$0o(); }
1524 fn test_hover_through_expr_in_macro() {
1527 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1528 fn foo(bar:u32) { let a = id!(ba$0r); }
1541 fn test_hover_through_expr_in_macro_recursive() {
1544 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1545 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1546 fn foo(bar:u32) { let a = id!(ba$0r); }
1559 fn test_hover_through_func_in_macro_recursive() {
1562 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1563 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1564 fn bar() -> u32 { 0 }
1565 fn foo() { let a = id!([0u32, bar($0)] ); }
1577 fn test_hover_through_literal_string_in_macro() {
1580 macro_rules! arr { ($($tt:tt)*) => { [$($tt)*)] } }
1582 let mastered_for_itunes = "";
1583 let _ = arr!("Tr$0acks", &mastered_for_itunes);
1596 fn test_hover_through_assert_macro() {
1599 #[rustc_builtin_macro]
1600 macro_rules! assert {}
1602 fn bar() -> bool { true }
1622 fn test_hover_through_literal_string_in_builtin_macro() {
1623 check_hover_no_result(
1625 #[rustc_builtin_macro]
1626 macro_rules! format {}
1629 format!("hel$0lo {}", 0);
1636 fn test_hover_non_ascii_space_doc() {
1639 /// <- `\u{3000}` here
1642 fn bar() { fo$0o(); }
1663 fn test_hover_function_show_qualifiers() {
1665 r#"async fn foo$0() {}"#,
1679 r#"pub const unsafe fn foo$0() {}"#,
1688 pub const unsafe fn foo()
1692 // Top level `pub(crate)` will be displayed as no visibility.
1694 r#"mod m { pub(crate) async unsafe extern "C" fn foo$0() {} }"#,
1703 pub(crate) async unsafe extern "C" fn foo()
1710 fn test_hover_trait_show_qualifiers() {
1712 r"unsafe trait foo$0() {}",
1729 fn test_hover_extern_crate() {
1732 //- /main.rs crate:main deps:std
1734 //- /std/lib.rs crate:std
1735 //! Standard library for this test
1749 Standard library for this test
1757 //- /main.rs crate:main deps:std
1758 extern crate std as ab$0c;
1759 //- /std/lib.rs crate:std
1760 //! Standard library for this test
1774 Standard library for this test
1783 fn test_hover_mod_with_same_name_as_function() {
1786 use self::m$0y::Bar;
1787 mod my { pub struct Bar; }
1806 fn test_hover_struct_doc_comment() {
1809 /// This is an example
1817 /// assert_eq!(6, my_crate::add_one(5));
1821 fn foo() { let bar = Ba$0r; }
1844 assert_eq!(6, my_crate::add_one(5));
1851 fn test_hover_struct_doc_attr() {
1857 fn foo() { let bar = Ba$0r; }
1878 fn test_hover_struct_doc_attr_multiple_and_mixed() {
1882 #[doc = "bar docs 1"]
1883 #[doc = "bar docs 2"]
1886 fn foo() { let bar = Ba$0r; }
1909 fn test_hover_external_url() {
1913 /// [external](https://www.google.com)
1929 [external](https://www.google.com)
1934 // Check that we don't rewrite links which we can't identify
1936 fn test_hover_unknown_target() {
1962 fn test_hover_no_links() {
1963 check_hover_no_links(
1966 /// case 1. bare URL: https://www.example.com/
1967 /// case 2. inline URL with title: [example](https://www.example.com/)
1968 /// case 3. code reference: [`Result`]
1969 /// case 4. code reference but miss footnote: [`String`]
1970 /// case 5. autolink: <http://www.example.com/>
1971 /// case 6. email address: <test@example.com>
1972 /// case 7. reference: [example][example]
1973 /// case 8. collapsed link: [example][]
1974 /// case 9. shortcut link: [example]
1975 /// case 10. inline without URL: [example]()
1976 /// case 11. reference: [foo][foo]
1977 /// case 12. reference: [foo][bar]
1978 /// case 13. collapsed link: [foo][]
1979 /// case 14. shortcut link: [foo]
1980 /// case 15. inline without URL: [foo]()
1981 /// case 16. just escaped text: \[foo]
1982 /// case 17. inline link: [Foo](foo::Foo)
1984 /// [`Result`]: ../../std/result/enum.Result.html
1985 /// [^example]: https://www.example.com/
2002 case 1. bare URL: https://www.example.com/
2003 case 2. inline URL with title: [example](https://www.example.com/)
2004 case 3. code reference: `Result`
2005 case 4. code reference but miss footnote: `String`
2006 case 5. autolink: http://www.example.com/
2007 case 6. email address: test@example.com
2008 case 7. reference: example
2009 case 8. collapsed link: example
2010 case 9. shortcut link: example
2011 case 10. inline without URL: example
2012 case 11. reference: foo
2013 case 12. reference: foo
2014 case 13. collapsed link: foo
2015 case 14. shortcut link: foo
2016 case 15. inline without URL: foo
2017 case 16. just escaped text: \[foo\]
2018 case 17. inline link: Foo
2020 [^example]: https://www.example.com/
2026 fn test_hover_macro_generated_struct_fn_doc_comment() {
2027 cov_mark::check!(hover_macro_generated_struct_fn_doc_comment);
2043 fn foo() { let bar = Bar; bar.fo$0o(); }
2064 fn test_hover_macro_generated_struct_fn_doc_attr() {
2065 cov_mark::check!(hover_macro_generated_struct_fn_doc_attr);
2073 #[doc = "Do the foo"]
2081 fn foo() { let bar = Bar; bar.fo$0o(); }
2102 fn test_hover_trait_has_impl_action() {
2104 r#"trait foo$0() {}"#,
2121 fn test_hover_struct_has_impl_action() {
2123 r"struct foo$0() {}",
2140 fn test_hover_union_has_impl_action() {
2142 r#"union foo$0() {}"#,
2159 fn test_hover_enum_has_impl_action() {
2161 r"enum foo$0() { A, B }",
2178 fn test_hover_self_has_impl_action() {
2180 r#"struct foo where Self$0:;"#,
2197 fn test_hover_test_has_action() {
2215 use_name_in_title: false,
2216 nav: NavigationTarget {
2221 focus_range: 11..19,
2242 fn test_hover_test_mod_has_action() {
2254 use_name_in_title: false,
2255 nav: NavigationTarget {
2263 description: "mod tests",
2277 fn test_hover_struct_has_goto_type_action() {
2282 fn main() { let s$0t = S{ f1:0 }; }
2289 mod_path: "test::S",
2290 nav: NavigationTarget {
2298 description: "struct S",
2309 fn test_hover_generic_struct_has_goto_type_actions() {
2313 struct S<T>{ f1: T }
2315 fn main() { let s$0t = S{ f1:Arg(0) }; }
2322 mod_path: "test::S",
2323 nav: NavigationTarget {
2328 focus_range: 24..25,
2331 description: "struct S<T>",
2335 mod_path: "test::Arg",
2336 nav: NavigationTarget {
2344 description: "struct Arg",
2355 fn test_hover_generic_struct_has_flattened_goto_type_actions() {
2359 struct S<T>{ f1: T }
2361 fn main() { let s$0t = S{ f1: S{ f1: Arg(0) } }; }
2368 mod_path: "test::S",
2369 nav: NavigationTarget {
2374 focus_range: 24..25,
2377 description: "struct S<T>",
2381 mod_path: "test::Arg",
2382 nav: NavigationTarget {
2390 description: "struct Arg",
2401 fn test_hover_tuple_has_goto_type_actions() {
2410 fn main() { let s$0t = (A(1), B(2), M::C(3) ); }
2417 mod_path: "test::A",
2418 nav: NavigationTarget {
2426 description: "struct A",
2430 mod_path: "test::B",
2431 nav: NavigationTarget {
2436 focus_range: 22..23,
2439 description: "struct B",
2443 mod_path: "test::M::C",
2444 nav: NavigationTarget {
2449 focus_range: 53..54,
2452 description: "pub struct C",
2463 fn test_hover_return_impl_trait_has_goto_type_action() {
2467 fn foo() -> impl Foo {}
2469 fn main() { let s$0t = foo(); }
2476 mod_path: "test::Foo",
2477 nav: NavigationTarget {
2485 description: "trait Foo",
2496 fn test_hover_generic_return_impl_trait_has_goto_type_action() {
2501 fn foo() -> impl Foo<S> {}
2503 fn main() { let s$0t = foo(); }
2510 mod_path: "test::Foo",
2511 nav: NavigationTarget {
2519 description: "trait Foo<T>",
2523 mod_path: "test::S",
2524 nav: NavigationTarget {
2529 focus_range: 23..24,
2532 description: "struct S",
2543 fn test_hover_return_impl_traits_has_goto_type_action() {
2548 fn foo() -> impl Foo + Bar {}
2550 fn main() { let s$0t = foo(); }
2557 mod_path: "test::Foo",
2558 nav: NavigationTarget {
2566 description: "trait Foo",
2570 mod_path: "test::Bar",
2571 nav: NavigationTarget {
2576 focus_range: 19..22,
2579 description: "trait Bar",
2590 fn test_hover_generic_return_impl_traits_has_goto_type_action() {
2598 fn foo() -> impl Foo<S1> + Bar<S2> {}
2600 fn main() { let s$0t = foo(); }
2607 mod_path: "test::Foo",
2608 nav: NavigationTarget {
2616 description: "trait Foo<T>",
2620 mod_path: "test::Bar",
2621 nav: NavigationTarget {
2626 focus_range: 22..25,
2629 description: "trait Bar<T>",
2633 mod_path: "test::S1",
2634 nav: NavigationTarget {
2639 focus_range: 39..41,
2642 description: "struct S1",
2646 mod_path: "test::S2",
2647 nav: NavigationTarget {
2652 focus_range: 52..54,
2655 description: "struct S2",
2666 fn test_hover_arg_impl_trait_has_goto_type_action() {
2670 fn foo(ar$0g: &impl Foo) {}
2677 mod_path: "test::Foo",
2678 nav: NavigationTarget {
2686 description: "trait Foo",
2697 fn test_hover_arg_impl_traits_has_goto_type_action() {
2704 fn foo(ar$0g: &impl Foo + Bar<S>) {}
2711 mod_path: "test::Foo",
2712 nav: NavigationTarget {
2720 description: "trait Foo",
2724 mod_path: "test::Bar",
2725 nav: NavigationTarget {
2730 focus_range: 19..22,
2733 description: "trait Bar<T>",
2737 mod_path: "test::S",
2738 nav: NavigationTarget {
2743 focus_range: 36..37,
2746 description: "struct S",
2757 fn test_hover_async_block_impl_trait_has_goto_type_action() {
2760 //- minicore: future
2763 let fo$0o = async { S };
2771 mod_path: "core::future::Future",
2772 nav: NavigationTarget {
2776 full_range: 253..435,
2777 focus_range: 292..298,
2780 description: "pub trait Future",
2784 mod_path: "test::S",
2785 nav: NavigationTarget {
2793 description: "struct S",
2804 fn test_hover_arg_generic_impl_trait_has_goto_type_action() {
2809 fn foo(ar$0g: &impl Foo<S>) {}
2816 mod_path: "test::Foo",
2817 nav: NavigationTarget {
2825 description: "trait Foo<T>",
2829 mod_path: "test::S",
2830 nav: NavigationTarget {
2835 focus_range: 23..24,
2838 description: "struct S",
2849 fn test_hover_dyn_return_has_goto_type_action() {
2857 fn foo() -> B<dyn Foo> {}
2859 fn main() { let s$0t = foo(); }
2866 mod_path: "test::B",
2867 nav: NavigationTarget {
2872 focus_range: 49..50,
2875 description: "struct B<T>",
2879 mod_path: "test::Foo",
2880 nav: NavigationTarget {
2888 description: "trait Foo",
2899 fn test_hover_dyn_arg_has_goto_type_action() {
2903 fn foo(ar$0g: &dyn Foo) {}
2910 mod_path: "test::Foo",
2911 nav: NavigationTarget {
2919 description: "trait Foo",
2930 fn test_hover_generic_dyn_arg_has_goto_type_action() {
2935 fn foo(ar$0g: &dyn Foo<S>) {}
2942 mod_path: "test::Foo",
2943 nav: NavigationTarget {
2951 description: "trait Foo<T>",
2955 mod_path: "test::S",
2956 nav: NavigationTarget {
2961 focus_range: 23..24,
2964 description: "struct S",
2975 fn test_hover_goto_type_action_links_order() {
2978 trait ImplTrait<T> {}
2979 trait DynTrait<T> {}
2983 fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
2990 mod_path: "test::ImplTrait",
2991 nav: NavigationTarget {
2999 description: "trait ImplTrait<T>",
3003 mod_path: "test::B",
3004 nav: NavigationTarget {
3009 focus_range: 50..51,
3012 description: "struct B<T>",
3016 mod_path: "test::DynTrait",
3017 nav: NavigationTarget {
3022 focus_range: 28..36,
3025 description: "trait DynTrait<T>",
3029 mod_path: "test::S",
3030 nav: NavigationTarget {
3035 focus_range: 65..66,
3038 description: "struct S",
3049 fn test_hover_associated_type_has_goto_type_action() {
3054 fn get(self) -> Self::Item {}
3060 impl Foo for S { type Item = Bar; }
3062 fn test() -> impl Foo { S {} }
3064 fn main() { let s$0t = test().get(); }
3071 mod_path: "test::Foo",
3072 nav: NavigationTarget {
3080 description: "trait Foo",
3091 fn test_hover_const_param_has_goto_type_action() {
3095 struct Foo<const BAR: Bar>;
3097 impl<const BAR: Bar> Foo<BAR$0> {}
3104 mod_path: "test::Bar",
3105 nav: NavigationTarget {
3113 description: "struct Bar",
3124 fn test_hover_type_param_has_goto_type_action() {
3129 fn foo<T: Foo>(t: T$0){}
3136 mod_path: "test::Foo",
3137 nav: NavigationTarget {
3145 description: "trait Foo",
3156 fn test_hover_self_has_go_to_type() {
3169 mod_path: "test::Foo",
3170 nav: NavigationTarget {
3178 description: "struct Foo",
3189 fn hover_displays_normalized_crate_names() {
3192 //- /lib.rs crate:name-with-dashes
3194 pub struct Thing { x: u32 }
3197 pub fn new() -> Thing { Thing { x: 0 } }
3201 //- /main.rs crate:main deps:name-with-dashes
3202 fn main() { let foo_test = name_with_dashes::wrapper::Thing::new$0(); }
3208 name_with_dashes::wrapper::Thing
3212 pub fn new() -> Thing
3219 fn hover_field_pat_shorthand_ref_match_ergonomics() {
3242 fn hover_self_param_shows_type() {
3261 fn hover_self_param_shows_type_for_arbitrary_self_type() {
3267 fn bar(sel$0f: Arc<Foo>) {}
3281 fn hover_doc_outer_inner() {
3288 /// This comment belongs to the function
3312 fn hover_doc_outer_inner_attribue() {
3315 #[doc = "Be quick;"]
3317 #![doc = "time is mana"]
3319 #[doc = "This comment belongs to the function"]
3343 fn hover_doc_block_style_indentend() {
3377 fn hover_comments_dont_highlight_parent() {
3378 cov_mark::check!(no_highlight_on_comment_hover);
3379 check_hover_no_result(
3407 fn hover_lifetime() {
3409 r#"fn foo<'lifetime>(_: &'lifetime$0 ()) {}"#,
3421 fn hover_type_param() {
3428 impl<T: Copy + Clone> Foo<T$0> where T: Sized {}
3451 // lifetimes bounds arent being tracked yet
3455 impl<T: 'static> Foo<T$0> {}
3468 fn hover_type_param_not_sized() {
3475 impl<T: Copy + Clone> Foo<T$0> where T: ?Sized {}
3481 T: Copy + Clone + ?Sized
3488 fn hover_const_param() {
3491 struct Foo<const LEN: usize>;
3492 impl<const LEN: usize> Foo<LEN$0> {}
3505 fn hover_const_pat() {
3509 const FOO: usize = 3;
3536 fn hover_mod_def() {
3563 fn hover_self_in_use() {
3566 //! This should not appear
3568 /// But this should appear
3571 use foo::bar::{self$0};
3586 But this should appear
3592 fn hover_keyword() {
3595 //- /main.rs crate:main deps:std
3596 fn f() { retur$0n; }
3597 //- /libstd.rs crate:std
3598 /// Docs for return_keyword
3599 mod return_keyword {}
3610 Docs for return_keyword
3616 fn hover_builtin() {
3619 //- /main.rs crate:main deps:std
3620 cosnt _: &str$0 = ""; }
3622 //- /libstd.rs crate:std
3623 /// Docs for prim_str
3641 fn hover_macro_expanded_function() {
3644 struct S<'a, T>(&'a T);
3648 fn bar<'t, T: Clone + 't>(s: &mut S<'t, T>, t: u32) -> *mut u32 where
3650 for<'a> T: Clone + 'a
3669 fn bar<'t, T>(s: &mut S<'t, T>, t: u32) -> *mut u32
3673 for<'a> T: Clone + 'a,
3680 fn hover_intra_doc_links() {
3685 /// This is the item. Cool!
3689 /// Gives you a [`TheItem$0`].
3691 /// [`TheItem`]: theitem::TheItem
3692 pub fn gimme() -> theitem::TheItem {
3709 This is the item. Cool!
3715 fn hover_generic_assoc() {
3718 fn foo<T: A>() where T::Assoc$0: {}
3738 let _: <T>::Assoc$0;
3778 fn string_shadowed_with_inner_items() {
3781 //- /main.rs crate:main deps:alloc
3783 /// Custom `String` type.
3792 //- /alloc.rs crate:alloc
3797 /// This is `alloc::String`.
3814 Custom `String` type.
3820 fn function_doesnt_shadow_crate_in_use_tree() {
3823 //- /main.rs crate:main deps:foo
3826 //- /foo.rs crate:foo
3840 fn hover_feature() {
3842 r#"#![feature(box_syntax$0)]"#,
3852 The tracking issue for this feature is: [#49733]
3854 [#49733]: https://github.com/rust-lang/rust/issues/49733
3856 See also [`box_patterns`](box-patterns.md)
3858 ------------------------
3860 Currently the only stable way to create a `Box` is via the `Box::new` method.
3861 Also it is not possible in stable Rust to destructure a `Box` in a match
3862 pattern. The unstable `box` keyword can be used to create a `Box`. An example
3866 #![feature(box_syntax)]
3880 r#"#![allow(arithmetic_overflow$0)]"#,
3882 *arithmetic_overflow*
3888 arithmetic operation overflows
3894 fn hover_clippy_lint() {
3896 r#"#![allow(clippy::almost_swapped$0)]"#,
3900 clippy::almost_swapped
3904 Checks for `foo = bar; bar = foo` sequences.
3910 fn hover_attr_path_qualifier() {
3911 cov_mark::check!(name_ref_classify_attr_path_qualifier);
3914 //- /foo.rs crate:foo
3916 //- /lib.rs crate:main.rs deps:foo
3947 use bar::{self as foo$0};
3990 fn hover_derive_input() {
3993 #[rustc_builtin_macro]
4013 #[rustc_builtin_macro]
4016 #[derive(foo::Copy$0)]
4034 fn hover_range_math() {
4037 fn f() { let expr = $01 + 2 * 3$0 }
4047 fn f() { let expr = 1 $0+ 2 * $03 }
4057 fn f() { let expr = 1 + $02 * 3$0 }
4067 fn hover_range_arrays() {
4070 fn f() { let expr = $0[1, 2, 3, 4]$0 }
4080 fn f() { let expr = [1, 2, $03, 4]$0 }
4090 fn f() { let expr = [1, 2, $03$0, 4] }
4100 fn hover_range_functions() {
4103 fn f<T>(a: &[T]) { }
4104 fn b() { $0f$0(&[1, 2, 3, 4, 5]); }
4114 fn f<T>(a: &[T]) { }
4115 fn b() { f($0&[1, 2, 3, 4, 5]$0); }
4125 fn hover_range_shows_nothing_when_invalid() {
4126 check_hover_range_no_results(
4128 fn f<T>(a: &[T]) { }
4129 fn b()$0 { f(&[1, 2, 3, 4, 5]); }$0
4133 check_hover_range_no_results(
4135 fn f<T>$0(a: &[T]) { }
4136 fn b() { f(&[1, 2, 3,$0 4, 5]); }
4140 check_hover_range_no_results(
4142 fn $0f() { let expr = [1, 2, 3, 4]$0 }
4148 fn hover_range_shows_unit_for_statements() {
4151 fn f<T>(a: &[T]) { }
4152 fn b() { $0f(&[1, 2, 3, 4, 5]); }$0
4162 fn f() { let expr$0 = $0[1, 2, 3, 4] }
4172 fn hover_range_for_pat() {
4199 fn hover_range_shows_coercions_if_applicable_expr() {
4203 let x: &u32 = $0&&&&&0$0;
4216 let x: *const u32 = $0&0$0;
4222 Coerced to: *const u32
4229 fn hover_range_shows_type_actions() {
4234 let x: &Foo = $0&&&&&Foo$0;
4242 mod_path: "test::Foo",
4243 nav: NavigationTarget {
4251 description: "struct Foo",