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 // We don't use NameClass::referenced_or_defined here as we do not want to resolve
121 // field pattern shorthands to their definition.
122 ast::Name(name) => NameClass::classify(&sema, &name).map(|class| match class {
123 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
124 NameClass::PatFieldShorthand { local_def, field_ref: _ } => Definition::Local(local_def),
126 ast::NameRef(name_ref) => NameRefClass::classify(&sema, &name_ref).map(|class| match class {
127 NameRefClass::Definition(def) => def,
128 NameRefClass::FieldShorthand { local_ref: _, field_ref } => {
129 Definition::Field(field_ref)
132 ast::Lifetime(lifetime) => NameClass::classify_lifetime(&sema, &lifetime).map_or_else(
134 NameRefClass::classify_lifetime(&sema, &lifetime).and_then(|class| match class {
135 NameRefClass::Definition(it) => Some(it),
142 if ast::Comment::cast(token.clone()).is_some() {
143 cov_mark::hit!(no_highlight_on_comment_hover);
144 let (attributes, def) = doc_attributes(&sema, &node)?;
145 let (docs, doc_mapping) = attributes.docs_with_rangemap(db)?;
146 let (idl_range, link, ns) =
147 extract_definitions_from_docs(&docs).into_iter().find_map(|(range, link, ns)| {
148 let mapped = doc_mapping.map(range)?;
149 (mapped.file_id == file_id.into() && mapped.value.contains(offset)).then(||(mapped.value, link, ns))
151 range_override = Some(idl_range);
152 Some(match resolve_doc_path_for_def(db,def, &link,ns)? {
153 Either::Left(it) => Definition::ModuleDef(it),
154 Either::Right(it) => Definition::Macro(it),
156 } else if let Some(attr) = token.ancestors().find_map(ast::Attr::cast) {
157 if let res@Some(_) = try_hover_for_lint(&attr, &token) {
160 range_override = Some(token.text_range());
161 try_resolve_derive_input_at(&sema, &attr, &token).map(Definition::Macro)
170 if let Some(definition) = definition {
171 let famous_defs = match &definition {
172 Definition::ModuleDef(hir::ModuleDef::BuiltinType(_)) => {
173 Some(FamousDefs(&sema, sema.scope(&node).krate()))
177 if let Some(markup) = hover_for_definition(db, definition, famous_defs.as_ref(), config) {
178 let mut res = HoverResult::default();
179 res.markup = process_markup(sema.db, definition, &markup, config);
180 if let Some(action) = show_implementations_action(db, definition) {
181 res.actions.push(action);
184 if let Some(action) = show_fn_references_action(db, definition) {
185 res.actions.push(action);
188 if let Some(action) = runnable_action(&sema, definition, file_id) {
189 res.actions.push(action);
192 if let Some(action) = goto_type_action_for_def(db, definition) {
193 res.actions.push(action);
196 let range = range_override.unwrap_or_else(|| sema.original_range(&node).range);
197 return Some(RangeInfo::new(range, res));
201 if let res @ Some(_) = hover_for_keyword(&sema, config, &token) {
205 // No definition below cursor, fall back to showing type hovers.
209 .take_while(|it| !ast::Item::can_cast(it.kind()))
210 .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
212 let expr_or_pat = match_ast! {
214 ast::Expr(it) => Either::Left(it),
215 ast::Pat(it) => Either::Right(it),
216 // If this node is a MACRO_CALL, it means that `descend_into_macros` failed to resolve.
217 // (e.g expanding a builtin macro). So we give up here.
218 ast::MacroCall(_it) => return None,
223 let res = hover_type_info(&sema, config, &expr_or_pat)?;
224 let range = sema.original_range(&node).range;
225 Some(RangeInfo::new(range, res))
230 range: syntax::TextRange,
231 sema: &Semantics<RootDatabase>,
232 config: &HoverConfig,
233 ) -> Option<RangeInfo<HoverResult>> {
234 let expr = file.covering_element(range).ancestors().find_map(|it| {
237 ast::Expr(expr) => Some(Either::Left(expr)),
238 ast::Pat(pat) => Some(Either::Right(pat)),
243 hover_type_info(sema, config, &expr).map(|it| {
244 let range = match expr {
245 Either::Left(it) => it.syntax().text_range(),
246 Either::Right(it) => it.syntax().text_range(),
248 RangeInfo::new(range, it)
253 sema: &Semantics<RootDatabase>,
254 config: &HoverConfig,
255 expr_or_pat: &Either<ast::Expr, ast::Pat>,
256 ) -> Option<HoverResult> {
257 let TypeInfo { original, adjusted } = match expr_or_pat {
258 Either::Left(expr) => sema.type_of_expr(expr)?,
259 Either::Right(pat) => sema.type_of_pat(pat)?,
262 let mut res = HoverResult::default();
263 let mut targets: Vec<hir::ModuleDef> = Vec::new();
264 let mut push_new_def = |item: hir::ModuleDef| {
265 if !targets.contains(&item) {
269 walk_and_push_ty(sema.db, &original, &mut push_new_def);
271 res.markup = if let Some(adjusted_ty) = adjusted {
272 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
273 let original = original.display(sema.db).to_string();
274 let adjusted = adjusted_ty.display(sema.db).to_string();
276 "```text\nType: {:>apad$}\nCoerced to: {:>opad$}\n```\n",
277 uncoerced = original,
279 // 6 base padding for static text prefix of each line
280 apad = 6 + adjusted.len().max(original.len()),
281 opad = original.len(),
285 if config.markdown() {
286 Markup::fenced_block(&original.display(sema.db))
288 original.display(sema.db).to_string().into()
291 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
295 fn try_hover_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option<RangeInfo<HoverResult>> {
296 let (path, tt) = attr.as_simple_call()?;
297 if !tt.syntax().text_range().contains(token.text_range().start()) {
300 let (is_clippy, lints) = match &*path {
301 "feature" => (false, FEATURES),
302 "allow" | "deny" | "forbid" | "warn" => {
303 let is_clippy = algo::non_trivia_sibling(token.clone().into(), Direction::Prev)
304 .filter(|t| t.kind() == T![:])
305 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
306 .filter(|t| t.kind() == T![:])
307 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
309 t.kind() == T![ident] && t.into_token().map_or(false, |t| t.text() == "clippy")
314 (false, DEFAULT_LINTS)
321 let needle = if is_clippy {
322 tmp = format!("clippy::{}", token.text());
329 lints.binary_search_by_key(&needle, |lint| lint.label).ok().map(|idx| &lints[idx])?;
333 markup: Markup::from(format!("```\n{}\n```\n___\n\n{}", lint.label, lint.description)),
339 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
340 fn to_action(nav_target: NavigationTarget) -> HoverAction {
341 HoverAction::Implementation(FilePosition {
342 file_id: nav_target.file_id,
343 offset: nav_target.focus_or_full_range().start(),
347 let adt = match def {
348 Definition::ModuleDef(hir::ModuleDef::Trait(it)) => {
349 return it.try_to_nav(db).map(to_action)
351 Definition::ModuleDef(hir::ModuleDef::Adt(it)) => Some(it),
352 Definition::SelfType(it) => it.self_ty(db).as_adt(),
355 adt.try_to_nav(db).map(to_action)
358 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
360 Definition::ModuleDef(hir::ModuleDef::Function(it)) => {
361 it.try_to_nav(db).map(|nav_target| {
362 HoverAction::Reference(FilePosition {
363 file_id: nav_target.file_id,
364 offset: nav_target.focus_or_full_range().start(),
373 sema: &hir::Semantics<RootDatabase>,
376 ) -> Option<HoverAction> {
378 Definition::ModuleDef(it) => match it {
379 hir::ModuleDef::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
380 hir::ModuleDef::Function(func) => {
381 let src = func.source(sema.db)?;
382 if src.file_id != file_id.into() {
383 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
384 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
388 runnable_fn(sema, func).map(HoverAction::Runnable)
396 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
397 let mut targets: Vec<hir::ModuleDef> = Vec::new();
398 let mut push_new_def = |item: hir::ModuleDef| {
399 if !targets.contains(&item) {
404 if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
405 it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
408 Definition::Local(it) => it.ty(db),
409 Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
410 Definition::Field(field) => field.ty(db),
414 walk_and_push_ty(db, &ty, &mut push_new_def);
417 Some(HoverAction::goto_type_from_targets(db, targets))
423 push_new_def: &mut dyn FnMut(hir::ModuleDef),
426 if let Some(adt) = t.as_adt() {
427 push_new_def(adt.into());
428 } else if let Some(trait_) = t.as_dyn_trait() {
429 push_new_def(trait_.into());
430 } else if let Some(traits) = t.as_impl_traits(db) {
431 traits.into_iter().for_each(|it| push_new_def(it.into()));
432 } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
433 push_new_def(trait_.into());
438 fn hover_markup(docs: Option<String>, desc: String, mod_path: Option<String>) -> Option<Markup> {
439 let mut buf = String::new();
441 if let Some(mod_path) = mod_path {
442 if !mod_path.is_empty() {
443 format_to!(buf, "```rust\n{}\n```\n\n", mod_path);
446 format_to!(buf, "```rust\n{}\n```", desc);
448 if let Some(doc) = docs {
449 format_to!(buf, "\n___\n\n{}", doc);
458 config: &HoverConfig,
460 let markup = markup.as_str();
461 let markup = if !config.markdown() {
462 remove_markdown(markup)
463 } else if config.links_in_hover {
464 rewrite_links(db, markup, def)
471 fn definition_owner_name(db: &RootDatabase, def: &Definition) -> Option<String> {
473 Definition::Field(f) => Some(f.parent_def(db).name(db)),
474 Definition::Local(l) => l.parent(db).name(db),
475 Definition::ModuleDef(md) => match md {
476 hir::ModuleDef::Function(f) => match f.as_assoc_item(db)?.container(db) {
477 hir::AssocItemContainer::Trait(t) => Some(t.name(db)),
478 hir::AssocItemContainer::Impl(i) => i.self_ty(db).as_adt().map(|adt| adt.name(db)),
480 hir::ModuleDef::Variant(e) => Some(e.parent_enum(db).name(db)),
485 .map(|name| name.to_string())
488 fn render_path(db: &RootDatabase, module: hir::Module, item_name: Option<String>) -> String {
490 db.crate_graph()[module.krate().into()].display_name.as_ref().map(|it| it.to_string());
491 let module_path = module
495 .flat_map(|it| it.name(db).map(|name| name.to_string()));
496 crate_name.into_iter().chain(module_path).chain(item_name).join("::")
499 fn definition_mod_path(db: &RootDatabase, def: &Definition) -> Option<String> {
500 if let Definition::GenericParam(_) = def {
503 def.module(db).map(|module| render_path(db, module, definition_owner_name(db, def)))
506 fn hover_for_definition(
509 famous_defs: Option<&FamousDefs>,
510 config: &HoverConfig,
511 ) -> Option<Markup> {
512 let mod_path = definition_mod_path(db, &def);
513 let (label, docs) = match def {
514 Definition::Macro(it) => (
515 match &it.source(db)?.value {
516 Either::Left(mac) => macro_label(mac),
517 Either::Right(mac_fn) => fn_as_proc_macro_label(mac_fn),
521 Definition::Field(def) => label_and_docs(db, def),
522 Definition::ModuleDef(it) => match it {
523 hir::ModuleDef::Module(it) => label_and_docs(db, it),
524 hir::ModuleDef::Function(it) => label_and_docs(db, it),
525 hir::ModuleDef::Adt(it) => label_and_docs(db, it),
526 hir::ModuleDef::Variant(it) => label_and_docs(db, it),
527 hir::ModuleDef::Const(it) => label_and_docs(db, it),
528 hir::ModuleDef::Static(it) => label_and_docs(db, it),
529 hir::ModuleDef::Trait(it) => label_and_docs(db, it),
530 hir::ModuleDef::TypeAlias(it) => label_and_docs(db, it),
531 hir::ModuleDef::BuiltinType(it) => {
533 .and_then(|fd| hover_for_builtin(fd, it))
534 .or_else(|| Some(Markup::fenced_block(&it.name())))
537 Definition::Local(it) => return hover_for_local(it, db),
538 Definition::SelfType(impl_def) => {
539 impl_def.self_ty(db).as_adt().map(|adt| label_and_docs(db, adt))?
541 Definition::GenericParam(it) => label_and_docs(db, it),
542 Definition::Label(it) => return Some(Markup::fenced_block(&it.name(db))),
546 docs.filter(|_| config.documentation.is_some()).map(Into::into),
551 fn label_and_docs<D>(db: &RootDatabase, def: D) -> (String, Option<hir::Documentation>)
553 D: HasAttrs + HirDisplay,
555 let label = def.display(db).to_string();
556 let docs = def.attrs(db).docs();
561 fn hover_for_local(it: hir::Local, db: &RootDatabase) -> Option<Markup> {
563 let ty = ty.display(db);
564 let is_mut = if it.is_mut(db) { "mut " } else { "" };
565 let desc = match it.source(db).value {
566 Either::Left(ident) => {
567 let name = it.name(db).unwrap();
568 let let_kw = if ident
571 .map_or(false, |p| p.kind() == LET_STMT || p.kind() == CONDITION)
577 format!("{}{}{}: {}", let_kw, is_mut, name, ty)
579 Either::Right(_) => format!("{}self: {}", is_mut, ty),
581 hover_markup(None, desc, None)
584 fn hover_for_keyword(
585 sema: &Semantics<RootDatabase>,
586 config: &HoverConfig,
588 ) -> Option<RangeInfo<HoverResult>> {
589 if !token.kind().is_keyword() || !config.documentation.is_some() {
592 let famous_defs = FamousDefs(sema, sema.scope(&token.parent()?).krate());
593 // std exposes {}_keyword modules with docstrings on the root to document keywords
594 let keyword_mod = format!("{}_keyword", token.text());
595 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?;
596 let docs = doc_owner.attrs(sema.db).docs()?;
597 let markup = process_markup(
599 Definition::ModuleDef(doc_owner.into()),
600 &hover_markup(Some(docs.into()), token.text().into(), None)?,
603 Some(RangeInfo::new(token.text_range(), HoverResult { markup, actions: Default::default() }))
606 fn hover_for_builtin(famous_defs: &FamousDefs, builtin: hir::BuiltinType) -> Option<Markup> {
607 // std exposes prim_{} modules with docstrings on the root to document the builtins
608 let primitive_mod = format!("prim_{}", builtin.name());
609 let doc_owner = find_std_module(famous_defs, &primitive_mod)?;
610 let docs = doc_owner.attrs(famous_defs.0.db).docs()?;
611 hover_markup(Some(docs.into()), builtin.name().to_string(), None)
614 fn find_std_module(famous_defs: &FamousDefs, name: &str) -> Option<hir::Module> {
615 let db = famous_defs.0.db;
616 let std_crate = famous_defs.std()?;
617 let std_root_module = std_crate.root_module(db);
620 .find(|module| module.name(db).map_or(false, |module| module.to_string() == name))
625 use expect_test::{expect, Expect};
626 use ide_db::base_db::{FileLoader, FileRange};
627 use syntax::TextRange;
629 use crate::{fixture, hover::HoverDocFormat, HoverConfig};
631 fn check_hover_no_result(ra_fixture: &str) {
632 let (analysis, position) = fixture::position(ra_fixture);
636 links_in_hover: true,
637 documentation: Some(HoverDocFormat::Markdown),
639 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
642 assert!(hover.is_none());
645 fn check(ra_fixture: &str, expect: Expect) {
646 let (analysis, position) = fixture::position(ra_fixture);
650 links_in_hover: true,
651 documentation: Some(HoverDocFormat::Markdown),
653 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
658 let content = analysis.db.file_text(position.file_id);
659 let hovered_element = &content[hover.range];
661 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
662 expect.assert_eq(&actual)
665 fn check_hover_no_links(ra_fixture: &str, expect: Expect) {
666 let (analysis, position) = fixture::position(ra_fixture);
670 links_in_hover: false,
671 documentation: Some(HoverDocFormat::Markdown),
673 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
678 let content = analysis.db.file_text(position.file_id);
679 let hovered_element = &content[hover.range];
681 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
682 expect.assert_eq(&actual)
685 fn check_hover_no_markdown(ra_fixture: &str, expect: Expect) {
686 let (analysis, position) = fixture::position(ra_fixture);
690 links_in_hover: true,
691 documentation: Some(HoverDocFormat::PlainText),
693 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
698 let content = analysis.db.file_text(position.file_id);
699 let hovered_element = &content[hover.range];
701 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
702 expect.assert_eq(&actual)
705 fn check_actions(ra_fixture: &str, expect: Expect) {
706 let (analysis, file_id, position) = fixture::range_or_position(ra_fixture);
710 links_in_hover: true,
711 documentation: Some(HoverDocFormat::Markdown),
713 FileRange { file_id, range: position.range_or_empty() },
717 expect.assert_debug_eq(&hover.info.actions)
720 fn check_hover_range(ra_fixture: &str, expect: Expect) {
721 let (analysis, range) = fixture::range(ra_fixture);
725 links_in_hover: false,
726 documentation: Some(HoverDocFormat::Markdown),
732 expect.assert_eq(hover.info.markup.as_str())
735 fn check_hover_range_no_results(ra_fixture: &str) {
736 let (analysis, range) = fixture::range(ra_fixture);
740 links_in_hover: false,
741 documentation: Some(HoverDocFormat::Markdown),
746 assert!(hover.is_none());
750 fn hover_shows_type_of_an_expression() {
753 pub fn foo() -> u32 { 1 }
756 let foo_test = foo()$0;
769 fn hover_remove_markdown_if_configured() {
770 check_hover_no_markdown(
772 pub fn foo() -> u32 { 1 }
775 let foo_test = foo()$0;
786 fn hover_shows_long_type_of_an_expression() {
789 struct Scan<A, B, C> { a: A, b: B, c: C }
790 struct Iter<I> { inner: I }
791 enum Option<T> { Some(T), None }
793 struct OtherStruct<T> { i: T }
795 fn scan<A, B, C>(a: A, b: B, c: C) -> Iter<Scan<OtherStruct<A>, B, C>> {
796 Iter { inner: Scan { a, b, c } }
801 let closure = |memo: &mut u32, value: &u32, _another: &mut u32| -> Option<u32> {
802 Option::Some(*memo + value)
805 let mut iter$0 = scan(OtherStruct { i: num }, closure, number);
812 let mut iter: Iter<Scan<OtherStruct<OtherStruct<i32>>, |&mut u32, &u32, &mut u32| -> Option<u32>, u32>>
819 fn hover_shows_fn_signature() {
820 // Single file with result
823 pub fn foo() -> u32 { 1 }
825 fn main() { let foo_test = fo$0o(); }
840 // Multiple candidates but results are ambiguous.
844 pub fn foo() -> u32 { 1 }
847 pub fn foo() -> &str { "" }
850 pub fn foo(a: u32, b: u32) {}
857 fn main() { let foo_test = fo$0o(); }
869 fn hover_shows_fn_signature_with_type_params() {
872 pub fn foo<'a, T: AsRef<str>>(b: &'a T) -> &'a str { }
874 fn main() { let foo_test = fo$0o(); }
884 pub fn foo<'a, T>(b: &'a T) -> &'a str
893 fn hover_shows_fn_signature_on_fn_name() {
896 pub fn foo$0(a: u32, b: u32) -> u32 {}
908 pub fn foo(a: u32, b: u32) -> u32
915 fn hover_shows_fn_doc() {
920 /// # use std::path::Path;
922 /// foo(Path::new("hello, world!"))
924 pub fn foo$0(_: &Path) {}
944 # use std::path::Path;
946 foo(Path::new("hello, world!"))
953 fn hover_shows_fn_doc_attr_raw_string() {
956 #[doc = r#"Raw string doc attr"#]
957 pub fn foo$0(_: &Path) {}
980 fn hover_shows_struct_field_info() {
981 // Hovering over the field when instantiating
984 struct Foo { field_a: u32 }
987 let foo = Foo { field_a$0: 0, };
1003 // Hovering over the field in the definition
1006 struct Foo { field_a$0: u32 }
1009 let foo = Foo { field_a: 0 };
1027 fn hover_const_static() {
1029 r#"const foo$0: u32 = 123;"#,
1043 r#"static foo$0: u32 = 456;"#,
1059 fn hover_default_generic_types() {
1062 struct Test<K, T = u8> { k: K, t: T }
1065 let zz$0 = Test { t: 23u8, k: 33 };
1071 let zz: Test<i32, u8>
1081 enum Option<T> { Some(T) }
1084 fn main() { So$0me(12); }
1101 enum Option<T> { Some(T) }
1104 fn main() { let b$0ar = Some(12); }
1110 let bar: Option<i32>
1117 fn hover_enum_variant() {
1121 /// The None variant
1145 /// The Some variant
1149 let s = Option::Som$0e(12);
1171 fn hover_for_local_variable() {
1173 r#"fn func(foo: i32) { fo$0o; }"#,
1185 fn hover_for_local_variable_pat() {
1187 r#"fn func(fo$0o: i32) {}"#,
1199 fn hover_local_var_edge() {
1201 r#"fn func(foo: i32) { if true { $0foo; }; }"#,
1213 fn hover_for_param_edge() {
1215 r#"fn func($0foo: i32) {}"#,
1227 fn hover_for_param_with_multiple_traits() {
1230 type Target: ?Sized;
1233 type Target: ?Sized;
1235 fn f(_x$0: impl Deref<Target=u8> + DerefMut<Target=u8>) {}"#,
1240 _x: impl Deref<Target = u8> + DerefMut<Target = u8>
1247 fn test_hover_infer_associated_method_result() {
1250 struct Thing { x: u32 }
1253 fn new() -> Thing { Thing { x: 0 } }
1256 fn main() { let foo_$0test = Thing::new(); }
1269 fn test_hover_infer_associated_method_exact() {
1273 struct Thing { x: u32 }
1276 fn new() -> Thing { Thing { x: 0 } }
1280 fn main() { let foo_test = wrapper::Thing::new$0(); }
1286 test::wrapper::Thing
1297 fn test_hover_infer_associated_const_in_pattern() {
1328 fn test_hover_self() {
1331 struct Thing { x: u32 }
1333 fn new() -> Self { Self$0 { x: 0 } }
1350 struct Thing { x: u32 }
1352 fn new() -> Self$0 { Self { x: 0 } }
1371 pub fn new() -> Self$0 { Thing::A }
1390 pub fn thing(a: Self$0) {}
1408 fn test_hover_shadowing_pat() {
1429 fn test_hover_macro_invocation() {
1432 macro_rules! foo { () => {} }
1434 fn f() { fo$0o!(); }
1451 fn test_hover_macro2_invocation() {
1459 fn f() { fo$0o!(); }
1482 fn test_hover_tuple_field() {
1484 r#"struct TS(String, i32$0);"#,
1496 fn test_hover_through_macro() {
1499 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1502 fn bar() { fo$0o(); }
1520 fn test_hover_through_expr_in_macro() {
1523 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1524 fn foo(bar:u32) { let a = id!(ba$0r); }
1537 fn test_hover_through_expr_in_macro_recursive() {
1540 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1541 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1542 fn foo(bar:u32) { let a = id!(ba$0r); }
1555 fn test_hover_through_func_in_macro_recursive() {
1558 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1559 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1560 fn bar() -> u32 { 0 }
1561 fn foo() { let a = id!([0u32, bar($0)] ); }
1573 fn test_hover_through_literal_string_in_macro() {
1576 macro_rules! arr { ($($tt:tt)*) => { [$($tt)*)] } }
1578 let mastered_for_itunes = "";
1579 let _ = arr!("Tr$0acks", &mastered_for_itunes);
1592 fn test_hover_through_assert_macro() {
1595 #[rustc_builtin_macro]
1596 macro_rules! assert {}
1598 fn bar() -> bool { true }
1618 fn test_hover_through_literal_string_in_builtin_macro() {
1619 check_hover_no_result(
1621 #[rustc_builtin_macro]
1622 macro_rules! format {}
1625 format!("hel$0lo {}", 0);
1632 fn test_hover_non_ascii_space_doc() {
1635 /// <- `\u{3000}` here
1638 fn bar() { fo$0o(); }
1659 fn test_hover_function_show_qualifiers() {
1661 r#"async fn foo$0() {}"#,
1675 r#"pub const unsafe fn foo$0() {}"#,
1684 pub const unsafe fn foo()
1688 // Top level `pub(crate)` will be displayed as no visibility.
1690 r#"mod m { pub(crate) async unsafe extern "C" fn foo$0() {} }"#,
1699 pub(crate) async unsafe extern "C" fn foo()
1706 fn test_hover_trait_show_qualifiers() {
1708 r"unsafe trait foo$0() {}",
1725 fn test_hover_extern_crate() {
1728 //- /main.rs crate:main deps:std
1730 //- /std/lib.rs crate:std
1731 //! Standard library for this test
1745 Standard library for this test
1753 //- /main.rs crate:main deps:std
1754 extern crate std as ab$0c;
1755 //- /std/lib.rs crate:std
1756 //! Standard library for this test
1770 Standard library for this test
1779 fn test_hover_mod_with_same_name_as_function() {
1782 use self::m$0y::Bar;
1783 mod my { pub struct Bar; }
1802 fn test_hover_struct_doc_comment() {
1805 /// This is an example
1813 /// assert_eq!(6, my_crate::add_one(5));
1817 fn foo() { let bar = Ba$0r; }
1840 assert_eq!(6, my_crate::add_one(5));
1847 fn test_hover_struct_doc_attr() {
1853 fn foo() { let bar = Ba$0r; }
1874 fn test_hover_struct_doc_attr_multiple_and_mixed() {
1878 #[doc = "bar docs 1"]
1879 #[doc = "bar docs 2"]
1882 fn foo() { let bar = Ba$0r; }
1905 fn test_hover_external_url() {
1909 /// [external](https://www.google.com)
1925 [external](https://www.google.com)
1930 // Check that we don't rewrite links which we can't identify
1932 fn test_hover_unknown_target() {
1958 fn test_hover_no_links() {
1959 check_hover_no_links(
1962 /// case 1. bare URL: https://www.example.com/
1963 /// case 2. inline URL with title: [example](https://www.example.com/)
1964 /// case 3. code reference: [`Result`]
1965 /// case 4. code reference but miss footnote: [`String`]
1966 /// case 5. autolink: <http://www.example.com/>
1967 /// case 6. email address: <test@example.com>
1968 /// case 7. reference: [example][example]
1969 /// case 8. collapsed link: [example][]
1970 /// case 9. shortcut link: [example]
1971 /// case 10. inline without URL: [example]()
1972 /// case 11. reference: [foo][foo]
1973 /// case 12. reference: [foo][bar]
1974 /// case 13. collapsed link: [foo][]
1975 /// case 14. shortcut link: [foo]
1976 /// case 15. inline without URL: [foo]()
1977 /// case 16. just escaped text: \[foo]
1978 /// case 17. inline link: [Foo](foo::Foo)
1980 /// [`Result`]: ../../std/result/enum.Result.html
1981 /// [^example]: https://www.example.com/
1998 case 1. bare URL: https://www.example.com/
1999 case 2. inline URL with title: [example](https://www.example.com/)
2000 case 3. code reference: `Result`
2001 case 4. code reference but miss footnote: `String`
2002 case 5. autolink: http://www.example.com/
2003 case 6. email address: test@example.com
2004 case 7. reference: example
2005 case 8. collapsed link: example
2006 case 9. shortcut link: example
2007 case 10. inline without URL: example
2008 case 11. reference: foo
2009 case 12. reference: foo
2010 case 13. collapsed link: foo
2011 case 14. shortcut link: foo
2012 case 15. inline without URL: foo
2013 case 16. just escaped text: \[foo\]
2014 case 17. inline link: Foo
2016 [^example]: https://www.example.com/
2022 fn test_hover_macro_generated_struct_fn_doc_comment() {
2023 cov_mark::check!(hover_macro_generated_struct_fn_doc_comment);
2039 fn foo() { let bar = Bar; bar.fo$0o(); }
2060 fn test_hover_macro_generated_struct_fn_doc_attr() {
2061 cov_mark::check!(hover_macro_generated_struct_fn_doc_attr);
2069 #[doc = "Do the foo"]
2077 fn foo() { let bar = Bar; bar.fo$0o(); }
2098 fn test_hover_trait_has_impl_action() {
2100 r#"trait foo$0() {}"#,
2117 fn test_hover_struct_has_impl_action() {
2119 r"struct foo$0() {}",
2136 fn test_hover_union_has_impl_action() {
2138 r#"union foo$0() {}"#,
2155 fn test_hover_enum_has_impl_action() {
2157 r"enum foo$0() { A, B }",
2174 fn test_hover_self_has_impl_action() {
2176 r#"struct foo where Self$0:;"#,
2193 fn test_hover_test_has_action() {
2211 use_name_in_title: false,
2212 nav: NavigationTarget {
2217 focus_range: 11..19,
2238 fn test_hover_test_mod_has_action() {
2250 use_name_in_title: false,
2251 nav: NavigationTarget {
2259 description: "mod tests",
2273 fn test_hover_struct_has_goto_type_action() {
2278 fn main() { let s$0t = S{ f1:0 }; }
2285 mod_path: "test::S",
2286 nav: NavigationTarget {
2294 description: "struct S",
2305 fn test_hover_generic_struct_has_goto_type_actions() {
2309 struct S<T>{ f1: T }
2311 fn main() { let s$0t = S{ f1:Arg(0) }; }
2318 mod_path: "test::S",
2319 nav: NavigationTarget {
2324 focus_range: 24..25,
2327 description: "struct S<T>",
2331 mod_path: "test::Arg",
2332 nav: NavigationTarget {
2340 description: "struct Arg",
2351 fn test_hover_generic_struct_has_flattened_goto_type_actions() {
2355 struct S<T>{ f1: T }
2357 fn main() { let s$0t = S{ f1: S{ f1: Arg(0) } }; }
2364 mod_path: "test::S",
2365 nav: NavigationTarget {
2370 focus_range: 24..25,
2373 description: "struct S<T>",
2377 mod_path: "test::Arg",
2378 nav: NavigationTarget {
2386 description: "struct Arg",
2397 fn test_hover_tuple_has_goto_type_actions() {
2406 fn main() { let s$0t = (A(1), B(2), M::C(3) ); }
2413 mod_path: "test::A",
2414 nav: NavigationTarget {
2422 description: "struct A",
2426 mod_path: "test::B",
2427 nav: NavigationTarget {
2432 focus_range: 22..23,
2435 description: "struct B",
2439 mod_path: "test::M::C",
2440 nav: NavigationTarget {
2445 focus_range: 53..54,
2448 description: "pub struct C",
2459 fn test_hover_return_impl_trait_has_goto_type_action() {
2463 fn foo() -> impl Foo {}
2465 fn main() { let s$0t = foo(); }
2472 mod_path: "test::Foo",
2473 nav: NavigationTarget {
2481 description: "trait Foo",
2492 fn test_hover_generic_return_impl_trait_has_goto_type_action() {
2497 fn foo() -> impl Foo<S> {}
2499 fn main() { let s$0t = foo(); }
2506 mod_path: "test::Foo",
2507 nav: NavigationTarget {
2515 description: "trait Foo<T>",
2519 mod_path: "test::S",
2520 nav: NavigationTarget {
2525 focus_range: 23..24,
2528 description: "struct S",
2539 fn test_hover_return_impl_traits_has_goto_type_action() {
2544 fn foo() -> impl Foo + Bar {}
2546 fn main() { let s$0t = foo(); }
2553 mod_path: "test::Foo",
2554 nav: NavigationTarget {
2562 description: "trait Foo",
2566 mod_path: "test::Bar",
2567 nav: NavigationTarget {
2572 focus_range: 19..22,
2575 description: "trait Bar",
2586 fn test_hover_generic_return_impl_traits_has_goto_type_action() {
2594 fn foo() -> impl Foo<S1> + Bar<S2> {}
2596 fn main() { let s$0t = foo(); }
2603 mod_path: "test::Foo",
2604 nav: NavigationTarget {
2612 description: "trait Foo<T>",
2616 mod_path: "test::Bar",
2617 nav: NavigationTarget {
2622 focus_range: 22..25,
2625 description: "trait Bar<T>",
2629 mod_path: "test::S1",
2630 nav: NavigationTarget {
2635 focus_range: 39..41,
2638 description: "struct S1",
2642 mod_path: "test::S2",
2643 nav: NavigationTarget {
2648 focus_range: 52..54,
2651 description: "struct S2",
2662 fn test_hover_arg_impl_trait_has_goto_type_action() {
2666 fn foo(ar$0g: &impl Foo) {}
2673 mod_path: "test::Foo",
2674 nav: NavigationTarget {
2682 description: "trait Foo",
2693 fn test_hover_arg_impl_traits_has_goto_type_action() {
2700 fn foo(ar$0g: &impl Foo + Bar<S>) {}
2707 mod_path: "test::Foo",
2708 nav: NavigationTarget {
2716 description: "trait Foo",
2720 mod_path: "test::Bar",
2721 nav: NavigationTarget {
2726 focus_range: 19..22,
2729 description: "trait Bar<T>",
2733 mod_path: "test::S",
2734 nav: NavigationTarget {
2739 focus_range: 36..37,
2742 description: "struct S",
2753 fn test_hover_async_block_impl_trait_has_goto_type_action() {
2756 //- minicore: future
2759 let fo$0o = async { S };
2767 mod_path: "core::future::Future",
2768 nav: NavigationTarget {
2772 full_range: 253..435,
2773 focus_range: 292..298,
2776 description: "pub trait Future",
2780 mod_path: "test::S",
2781 nav: NavigationTarget {
2789 description: "struct S",
2800 fn test_hover_arg_generic_impl_trait_has_goto_type_action() {
2805 fn foo(ar$0g: &impl Foo<S>) {}
2812 mod_path: "test::Foo",
2813 nav: NavigationTarget {
2821 description: "trait Foo<T>",
2825 mod_path: "test::S",
2826 nav: NavigationTarget {
2831 focus_range: 23..24,
2834 description: "struct S",
2845 fn test_hover_dyn_return_has_goto_type_action() {
2853 fn foo() -> B<dyn Foo> {}
2855 fn main() { let s$0t = foo(); }
2862 mod_path: "test::B",
2863 nav: NavigationTarget {
2868 focus_range: 49..50,
2871 description: "struct B<T>",
2875 mod_path: "test::Foo",
2876 nav: NavigationTarget {
2884 description: "trait Foo",
2895 fn test_hover_dyn_arg_has_goto_type_action() {
2899 fn foo(ar$0g: &dyn Foo) {}
2906 mod_path: "test::Foo",
2907 nav: NavigationTarget {
2915 description: "trait Foo",
2926 fn test_hover_generic_dyn_arg_has_goto_type_action() {
2931 fn foo(ar$0g: &dyn Foo<S>) {}
2938 mod_path: "test::Foo",
2939 nav: NavigationTarget {
2947 description: "trait Foo<T>",
2951 mod_path: "test::S",
2952 nav: NavigationTarget {
2957 focus_range: 23..24,
2960 description: "struct S",
2971 fn test_hover_goto_type_action_links_order() {
2974 trait ImplTrait<T> {}
2975 trait DynTrait<T> {}
2979 fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
2986 mod_path: "test::ImplTrait",
2987 nav: NavigationTarget {
2995 description: "trait ImplTrait<T>",
2999 mod_path: "test::B",
3000 nav: NavigationTarget {
3005 focus_range: 50..51,
3008 description: "struct B<T>",
3012 mod_path: "test::DynTrait",
3013 nav: NavigationTarget {
3018 focus_range: 28..36,
3021 description: "trait DynTrait<T>",
3025 mod_path: "test::S",
3026 nav: NavigationTarget {
3031 focus_range: 65..66,
3034 description: "struct S",
3045 fn test_hover_associated_type_has_goto_type_action() {
3050 fn get(self) -> Self::Item {}
3056 impl Foo for S { type Item = Bar; }
3058 fn test() -> impl Foo { S {} }
3060 fn main() { let s$0t = test().get(); }
3067 mod_path: "test::Foo",
3068 nav: NavigationTarget {
3076 description: "trait Foo",
3087 fn test_hover_const_param_has_goto_type_action() {
3091 struct Foo<const BAR: Bar>;
3093 impl<const BAR: Bar> Foo<BAR$0> {}
3100 mod_path: "test::Bar",
3101 nav: NavigationTarget {
3109 description: "struct Bar",
3120 fn test_hover_type_param_has_goto_type_action() {
3125 fn foo<T: Foo>(t: T$0){}
3132 mod_path: "test::Foo",
3133 nav: NavigationTarget {
3141 description: "trait Foo",
3152 fn test_hover_self_has_go_to_type() {
3165 mod_path: "test::Foo",
3166 nav: NavigationTarget {
3174 description: "struct Foo",
3185 fn hover_displays_normalized_crate_names() {
3188 //- /lib.rs crate:name-with-dashes
3190 pub struct Thing { x: u32 }
3193 pub fn new() -> Thing { Thing { x: 0 } }
3197 //- /main.rs crate:main deps:name-with-dashes
3198 fn main() { let foo_test = name_with_dashes::wrapper::Thing::new$0(); }
3204 name_with_dashes::wrapper::Thing
3208 pub fn new() -> Thing
3215 fn hover_field_pat_shorthand_ref_match_ergonomics() {
3238 fn hover_self_param_shows_type() {
3257 fn hover_self_param_shows_type_for_arbitrary_self_type() {
3263 fn bar(sel$0f: Arc<Foo>) {}
3277 fn hover_doc_outer_inner() {
3284 /// This comment belongs to the function
3308 fn hover_doc_outer_inner_attribue() {
3311 #[doc = "Be quick;"]
3313 #![doc = "time is mana"]
3315 #[doc = "This comment belongs to the function"]
3339 fn hover_doc_block_style_indentend() {
3373 fn hover_comments_dont_highlight_parent() {
3374 cov_mark::check!(no_highlight_on_comment_hover);
3375 check_hover_no_result(
3403 fn hover_lifetime() {
3405 r#"fn foo<'lifetime>(_: &'lifetime$0 ()) {}"#,
3417 fn hover_type_param() {
3424 impl<T: Copy + Clone> Foo<T$0> where T: Sized {}
3430 T: Copy + Clone + Sized
3447 // lifetimes bounds arent being tracked yet
3451 impl<T: 'static> Foo<T$0> {}
3464 fn hover_const_param() {
3467 struct Foo<const LEN: usize>;
3468 impl<const LEN: usize> Foo<LEN$0> {}
3481 fn hover_const_pat() {
3485 const FOO: usize = 3;
3512 fn hover_mod_def() {
3539 fn hover_self_in_use() {
3542 //! This should not appear
3544 /// But this should appear
3547 use foo::bar::{self$0};
3562 But this should appear
3568 fn hover_keyword() {
3571 //- /main.rs crate:main deps:std
3572 fn f() { retur$0n; }
3573 //- /libstd.rs crate:std
3574 /// Docs for return_keyword
3575 mod return_keyword {}
3586 Docs for return_keyword
3592 fn hover_builtin() {
3595 //- /main.rs crate:main deps:std
3596 cosnt _: &str$0 = ""; }
3598 //- /libstd.rs crate:std
3599 /// Docs for prim_str
3617 fn hover_macro_expanded_function() {
3620 struct S<'a, T>(&'a T);
3624 fn bar<'t, T: Clone + 't>(s: &mut S<'t, T>, t: u32) -> *mut u32 where
3626 for<'a> T: Clone + 'a
3645 fn bar<'t, T>(s: &mut S<'t, T>, t: u32) -> *mut u32
3649 for<'a> T: Clone + 'a,
3656 fn hover_intra_doc_links() {
3661 /// This is the item. Cool!
3665 /// Gives you a [`TheItem$0`].
3667 /// [`TheItem`]: theitem::TheItem
3668 pub fn gimme() -> theitem::TheItem {
3685 This is the item. Cool!
3691 fn hover_generic_assoc() {
3694 fn foo<T: A>() where T::Assoc$0: {}
3714 let _: <T>::Assoc$0;
3754 fn string_shadowed_with_inner_items() {
3757 //- /main.rs crate:main deps:alloc
3759 /// Custom `String` type.
3768 //- /alloc.rs crate:alloc
3773 /// This is `alloc::String`.
3790 Custom `String` type.
3796 fn function_doesnt_shadow_crate_in_use_tree() {
3799 //- /main.rs crate:main deps:foo
3802 //- /foo.rs crate:foo
3816 fn hover_feature() {
3818 r#"#![feature(box_syntax$0)]"#,
3828 The tracking issue for this feature is: [#49733]
3830 [#49733]: https://github.com/rust-lang/rust/issues/49733
3832 See also [`box_patterns`](box-patterns.md)
3834 ------------------------
3836 Currently the only stable way to create a `Box` is via the `Box::new` method.
3837 Also it is not possible in stable Rust to destructure a `Box` in a match
3838 pattern. The unstable `box` keyword can be used to create a `Box`. An example
3842 #![feature(box_syntax)]
3856 r#"#![allow(arithmetic_overflow$0)]"#,
3858 *arithmetic_overflow*
3864 arithmetic operation overflows
3870 fn hover_clippy_lint() {
3872 r#"#![allow(clippy::almost_swapped$0)]"#,
3876 clippy::almost_swapped
3880 Checks for `foo = bar; bar = foo` sequences.
3886 fn hover_attr_path_qualifier() {
3887 cov_mark::check!(name_ref_classify_attr_path_qualifier);
3890 //- /foo.rs crate:foo
3892 //- /lib.rs crate:main.rs deps:foo
3923 use bar::{self as foo$0};
3966 fn hover_derive_input() {
3969 #[rustc_builtin_macro]
3989 #[rustc_builtin_macro]
3992 #[derive(foo::Copy$0)]
4010 fn hover_range_math() {
4013 fn f() { let expr = $01 + 2 * 3$0 }
4023 fn f() { let expr = 1 $0+ 2 * $03 }
4033 fn f() { let expr = 1 + $02 * 3$0 }
4043 fn hover_range_arrays() {
4046 fn f() { let expr = $0[1, 2, 3, 4]$0 }
4056 fn f() { let expr = [1, 2, $03, 4]$0 }
4066 fn f() { let expr = [1, 2, $03$0, 4] }
4076 fn hover_range_functions() {
4079 fn f<T>(a: &[T]) { }
4080 fn b() { $0f$0(&[1, 2, 3, 4, 5]); }
4090 fn f<T>(a: &[T]) { }
4091 fn b() { f($0&[1, 2, 3, 4, 5]$0); }
4101 fn hover_range_shows_nothing_when_invalid() {
4102 check_hover_range_no_results(
4104 fn f<T>(a: &[T]) { }
4105 fn b()$0 { f(&[1, 2, 3, 4, 5]); }$0
4109 check_hover_range_no_results(
4111 fn f<T>$0(a: &[T]) { }
4112 fn b() { f(&[1, 2, 3,$0 4, 5]); }
4116 check_hover_range_no_results(
4118 fn $0f() { let expr = [1, 2, 3, 4]$0 }
4124 fn hover_range_shows_unit_for_statements() {
4127 fn f<T>(a: &[T]) { }
4128 fn b() { $0f(&[1, 2, 3, 4, 5]); }$0
4138 fn f() { let expr$0 = $0[1, 2, 3, 4] }
4148 fn hover_range_for_pat() {
4175 fn hover_range_shows_coercions_if_applicable_expr() {
4179 let x: &u32 = $0&&&&&0$0;
4192 let x: *const u32 = $0&0$0;
4198 Coerced to: *const u32
4205 fn hover_range_shows_type_actions() {
4210 let x: &Foo = $0&&&&&Foo$0;
4218 mod_path: "test::Foo",
4219 nav: NavigationTarget {
4227 description: "struct Foo",