3 AsAssocItem, AssocItemContainer, GenericParam, HasAttrs, HasSource, HirDisplay, InFile, Module,
7 base_db::SourceDatabase,
8 defs::{Definition, NameClass, NameRefClass},
10 generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES},
15 use itertools::Itertools;
18 algo, ast, match_ast, AstNode, AstToken, Direction, SyntaxKind::*, SyntaxToken, TokenAtOffset,
23 display::{macro_label, TryToNav},
25 doc_attributes, extract_definitions_from_markdown, remove_links, resolve_doc_path_for_def,
28 markdown_remove::remove_markdown,
30 runnables::{runnable_fn, runnable_mod},
31 FileId, FilePosition, NavigationTarget, RangeInfo, Runnable,
34 #[derive(Clone, Debug, PartialEq, Eq)]
35 pub struct HoverConfig {
36 pub implementations: bool,
40 pub goto_type_def: bool,
41 pub links_in_hover: bool,
46 pub const NO_ACTIONS: Self = Self {
47 implementations: false,
56 pub fn any(&self) -> bool {
57 self.implementations || self.references || self.runnable() || self.goto_type_def
60 pub fn none(&self) -> bool {
64 pub fn runnable(&self) -> bool {
65 self.run || self.debug
69 #[derive(Debug, Clone)]
70 pub enum HoverAction {
72 Implementation(FilePosition),
73 Reference(FilePosition),
74 GoToType(Vec<HoverGotoTypeData>),
77 #[derive(Debug, Clone, Eq, PartialEq)]
78 pub struct HoverGotoTypeData {
80 pub nav: NavigationTarget,
83 /// Contains the results when hovering over an item
84 #[derive(Debug, Default)]
85 pub struct HoverResult {
87 pub actions: Vec<HoverAction>,
92 // Shows additional information, like type of an expression or documentation for definition when "focusing" code.
93 // Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
95 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
98 position: FilePosition,
101 ) -> Option<RangeInfo<HoverResult>> {
102 let sema = Semantics::new(db);
103 let file = sema.parse(position.file_id).syntax().clone();
104 let token = pick_best(file.token_at_offset(position.offset))?;
105 let token = sema.descend_into_macros(token);
107 let mut res = HoverResult::default();
109 let node = token.parent()?;
110 let mut range = None;
111 let definition = match_ast! {
113 // we don't use NameClass::referenced_or_defined here as we do not want to resolve
114 // field pattern shorthands to their definition
115 ast::Name(name) => NameClass::classify(&sema, &name).and_then(|class| match class {
116 NameClass::ConstReference(def) => Some(def),
117 def => def.defined(db),
119 ast::NameRef(name_ref) => {
120 NameRefClass::classify(&sema, &name_ref).map(|d| d.referenced(db))
122 ast::Lifetime(lifetime) => NameClass::classify_lifetime(&sema, &lifetime).map_or_else(
123 || NameRefClass::classify_lifetime(&sema, &lifetime).map(|d| d.referenced(db)),
128 if ast::Comment::cast(token.clone()).is_some() {
129 cov_mark::hit!(no_highlight_on_comment_hover);
130 let (attributes, def) = doc_attributes(&sema, &node)?;
131 let (docs, doc_mapping) = attributes.docs_with_rangemap(db)?;
132 let (idl_range, link, ns) =
133 extract_definitions_from_markdown(docs.as_str()).into_iter().find_map(|(range, link, ns)| {
134 let InFile { file_id, value: range } = doc_mapping.map(range.clone())?;
135 if file_id == position.file_id.into() && range.contains(position.offset) {
136 Some((range, link, ns))
141 range = Some(idl_range);
142 resolve_doc_path_for_def(db, def, &link, ns).map(Definition::ModuleDef)
143 } else if let res@Some(_) = try_hover_for_attribute(&token) {
152 if let Some(definition) = definition {
153 let famous_defs = match &definition {
154 Definition::ModuleDef(ModuleDef::BuiltinType(_)) => {
155 Some(FamousDefs(&sema, sema.scope(&node).krate()))
159 if let Some(markup) = hover_for_definition(db, definition, famous_defs.as_ref()) {
160 res.markup = process_markup(sema.db, definition, &markup, links_in_hover, markdown);
161 if let Some(action) = show_implementations_action(db, definition) {
162 res.actions.push(action);
165 if let Some(action) = show_fn_references_action(db, definition) {
166 res.actions.push(action);
169 if let Some(action) = runnable_action(&sema, definition, position.file_id) {
170 res.actions.push(action);
173 if let Some(action) = goto_type_action(db, definition) {
174 res.actions.push(action);
177 let range = range.unwrap_or_else(|| sema.original_range(&node).range);
178 return Some(RangeInfo::new(range, res));
182 if let res @ Some(_) = hover_for_keyword(&sema, links_in_hover, markdown, &token) {
188 .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
190 let ty = match_ast! {
192 ast::Expr(it) => sema.type_of_expr(&it)?,
193 ast::Pat(it) => sema.type_of_pat(&it)?,
194 // If this node is a MACRO_CALL, it means that `descend_into_macros` failed to resolve.
195 // (e.g expanding a builtin macro). So we give up here.
196 ast::MacroCall(_it) => return None,
201 res.markup = if markdown {
202 Markup::fenced_block(&ty.display(db))
204 ty.display(db).to_string().into()
206 let range = sema.original_range(&node).range;
207 Some(RangeInfo::new(range, res))
210 fn try_hover_for_attribute(token: &SyntaxToken) -> Option<RangeInfo<HoverResult>> {
211 let attr = token.ancestors().find_map(ast::Attr::cast)?;
212 let (path, tt) = attr.as_simple_call()?;
213 if !tt.syntax().text_range().contains(token.text_range().start()) {
216 let (is_clippy, lints) = match &*path {
217 "feature" => (false, FEATURES),
218 "allow" | "deny" | "forbid" | "warn" => {
219 let is_clippy = algo::non_trivia_sibling(token.clone().into(), Direction::Prev)
220 .filter(|t| t.kind() == T![:])
221 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
222 .filter(|t| t.kind() == T![:])
223 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
225 t.kind() == T![ident] && t.into_token().map_or(false, |t| t.text() == "clippy")
230 (false, DEFAULT_LINTS)
237 let needle = if is_clippy {
238 tmp = format!("clippy::{}", token.text());
245 lints.binary_search_by_key(&needle, |lint| lint.label).ok().map(|idx| &lints[idx])?;
249 markup: Markup::from(format!("```\n{}\n```\n___\n\n{}", lint.label, lint.description)),
255 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
256 fn to_action(nav_target: NavigationTarget) -> HoverAction {
257 HoverAction::Implementation(FilePosition {
258 file_id: nav_target.file_id,
259 offset: nav_target.focus_or_full_range().start(),
263 let adt = match def {
264 Definition::ModuleDef(ModuleDef::Trait(it)) => return it.try_to_nav(db).map(to_action),
265 Definition::ModuleDef(ModuleDef::Adt(it)) => Some(it),
266 Definition::SelfType(it) => it.self_ty(db).as_adt(),
269 adt.try_to_nav(db).map(to_action)
272 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
274 Definition::ModuleDef(ModuleDef::Function(it)) => it.try_to_nav(db).map(|nav_target| {
275 HoverAction::Reference(FilePosition {
276 file_id: nav_target.file_id,
277 offset: nav_target.focus_or_full_range().start(),
285 sema: &Semantics<RootDatabase>,
288 ) -> Option<HoverAction> {
290 Definition::ModuleDef(it) => match it {
291 ModuleDef::Module(it) => runnable_mod(&sema, it).map(|it| HoverAction::Runnable(it)),
292 ModuleDef::Function(func) => {
293 let src = func.source(sema.db)?;
294 if src.file_id != file_id.into() {
295 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
296 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
300 runnable_fn(&sema, func).map(HoverAction::Runnable)
308 fn goto_type_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
309 let mut targets: Vec<ModuleDef> = Vec::new();
310 let mut push_new_def = |item: ModuleDef| {
311 if !targets.contains(&item) {
316 if let Definition::GenericParam(GenericParam::TypeParam(it)) = def {
317 it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
320 Definition::Local(it) => it.ty(db),
321 Definition::GenericParam(GenericParam::ConstParam(it)) => it.ty(db),
326 if let Some(adt) = t.as_adt() {
327 push_new_def(adt.into());
328 } else if let Some(trait_) = t.as_dyn_trait() {
329 push_new_def(trait_.into());
330 } else if let Some(traits) = t.as_impl_traits(db) {
331 traits.into_iter().for_each(|it| push_new_def(it.into()));
332 } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
333 push_new_def(trait_.into());
338 let targets = targets
341 Some(HoverGotoTypeData {
342 mod_path: render_path(db, it.module(db)?, it.name(db).map(|name| name.to_string())),
343 nav: it.try_to_nav(db)?,
348 Some(HoverAction::GoToType(targets))
352 docs: Option<String>,
353 desc: Option<String>,
354 mod_path: Option<String>,
355 ) -> Option<Markup> {
358 let mut buf = String::new();
360 if let Some(mod_path) = mod_path {
361 if !mod_path.is_empty() {
362 format_to!(buf, "```rust\n{}\n```\n\n", mod_path);
365 format_to!(buf, "```rust\n{}\n```", desc);
367 if let Some(doc) = docs {
368 format_to!(buf, "\n___\n\n{}", doc);
372 None => docs.map(Markup::from),
380 links_in_hover: bool,
383 let markup = markup.as_str();
384 let markup = if !markdown {
385 remove_markdown(markup)
386 } else if links_in_hover {
387 rewrite_links(db, markup, &def)
394 fn definition_owner_name(db: &RootDatabase, def: &Definition) -> Option<String> {
396 Definition::Field(f) => Some(f.parent_def(db).name(db)),
397 Definition::Local(l) => l.parent(db).name(db),
398 Definition::ModuleDef(md) => match md {
399 ModuleDef::Function(f) => match f.as_assoc_item(db)?.container(db) {
400 AssocItemContainer::Trait(t) => Some(t.name(db)),
401 AssocItemContainer::Impl(i) => i.self_ty(db).as_adt().map(|adt| adt.name(db)),
403 ModuleDef::Variant(e) => Some(e.parent_enum(db).name(db)),
408 .map(|name| name.to_string())
411 fn render_path(db: &RootDatabase, module: Module, item_name: Option<String>) -> String {
413 db.crate_graph()[module.krate().into()].display_name.as_ref().map(|it| it.to_string());
414 let module_path = module
418 .flat_map(|it| it.name(db).map(|name| name.to_string()));
419 crate_name.into_iter().chain(module_path).chain(item_name).join("::")
422 fn definition_mod_path(db: &RootDatabase, def: &Definition) -> Option<String> {
423 def.module(db).map(|module| render_path(db, module, definition_owner_name(db, def)))
426 fn hover_for_definition(
429 famous_defs: Option<&FamousDefs>,
430 ) -> Option<Markup> {
431 let mod_path = definition_mod_path(db, &def);
433 Definition::Macro(it) => match &it.source(db)?.value {
434 Either::Left(mac) => {
435 let label = macro_label(&mac);
436 from_def_source_labeled(db, it, Some(label), mod_path)
438 Either::Right(_) => {
443 Definition::Field(def) => from_hir_fmt(db, def, mod_path),
444 Definition::ModuleDef(it) => match it {
445 ModuleDef::Module(it) => from_hir_fmt(db, it, mod_path),
446 ModuleDef::Function(it) => from_hir_fmt(db, it, mod_path),
447 ModuleDef::Adt(it) => from_hir_fmt(db, it, mod_path),
448 ModuleDef::Variant(it) => from_hir_fmt(db, it, mod_path),
449 ModuleDef::Const(it) => from_hir_fmt(db, it, mod_path),
450 ModuleDef::Static(it) => from_hir_fmt(db, it, mod_path),
451 ModuleDef::Trait(it) => from_hir_fmt(db, it, mod_path),
452 ModuleDef::TypeAlias(it) => from_hir_fmt(db, it, mod_path),
453 ModuleDef::BuiltinType(it) => famous_defs
454 .and_then(|fd| hover_for_builtin(fd, it))
455 .or_else(|| Some(Markup::fenced_block(&it.name()))),
457 Definition::Local(it) => hover_for_local(it, db),
458 Definition::SelfType(impl_def) => {
459 impl_def.self_ty(db).as_adt().and_then(|adt| from_hir_fmt(db, adt, mod_path))
461 Definition::GenericParam(it) => from_hir_fmt(db, it, None),
462 Definition::Label(it) => Some(Markup::fenced_block(&it.name(db))),
465 fn from_hir_fmt<D>(db: &RootDatabase, def: D, mod_path: Option<String>) -> Option<Markup>
467 D: HasAttrs + HirDisplay,
469 let label = def.display(db).to_string();
470 from_def_source_labeled(db, def, Some(label), mod_path)
473 fn from_def_source_labeled<D>(
476 short_label: Option<String>,
477 mod_path: Option<String>,
482 let docs = def.attrs(db).docs().map(Into::into);
483 hover_markup(docs, short_label, mod_path)
487 fn hover_for_local(it: hir::Local, db: &RootDatabase) -> Option<Markup> {
489 let ty = ty.display(db);
490 let is_mut = if it.is_mut(db) { "mut " } else { "" };
491 let desc = match it.source(db).value {
492 Either::Left(ident) => {
493 let name = it.name(db).unwrap();
494 let let_kw = if ident
497 .map_or(false, |p| p.kind() == LET_STMT || p.kind() == CONDITION)
503 format!("{}{}{}: {}", let_kw, is_mut, name, ty)
505 Either::Right(_) => format!("{}self: {}", is_mut, ty),
507 hover_markup(None, Some(desc), None)
510 fn hover_for_keyword(
511 sema: &Semantics<RootDatabase>,
512 links_in_hover: bool,
515 ) -> Option<RangeInfo<HoverResult>> {
516 if !token.kind().is_keyword() {
519 let famous_defs = FamousDefs(&sema, sema.scope(&token.parent()?).krate());
520 // std exposes {}_keyword modules with docstrings on the root to document keywords
521 let keyword_mod = format!("{}_keyword", token.text());
522 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?;
523 let docs = doc_owner.attrs(sema.db).docs()?;
524 let markup = process_markup(
526 Definition::ModuleDef(doc_owner.into()),
527 &hover_markup(Some(docs.into()), Some(token.text().into()), None)?,
531 Some(RangeInfo::new(token.text_range(), HoverResult { markup, actions: Default::default() }))
534 fn hover_for_builtin(famous_defs: &FamousDefs, builtin: hir::BuiltinType) -> Option<Markup> {
535 // std exposes prim_{} modules with docstrings on the root to document the builtins
536 let primitive_mod = format!("prim_{}", builtin.name());
537 let doc_owner = find_std_module(famous_defs, &primitive_mod)?;
538 let docs = doc_owner.attrs(famous_defs.0.db).docs()?;
539 hover_markup(Some(docs.into()), Some(builtin.name().to_string()), None)
542 fn find_std_module(famous_defs: &FamousDefs, name: &str) -> Option<hir::Module> {
543 let db = famous_defs.0.db;
544 let std_crate = famous_defs.std()?;
545 let std_root_module = std_crate.root_module(db);
548 .find(|module| module.name(db).map_or(false, |module| module.to_string() == name))
551 fn pick_best(tokens: TokenAtOffset<SyntaxToken>) -> Option<SyntaxToken> {
552 return tokens.max_by_key(priority);
554 fn priority(n: &SyntaxToken) -> usize {
556 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] => 3,
557 T!['('] | T![')'] => 2,
558 kind if kind.is_trivia() => 0,
566 use expect_test::{expect, Expect};
567 use ide_db::base_db::FileLoader;
573 fn check_hover_no_result(ra_fixture: &str) {
574 let (analysis, position) = fixture::position(ra_fixture);
575 assert!(analysis.hover(position, true, true).unwrap().is_none());
578 fn check(ra_fixture: &str, expect: Expect) {
579 let (analysis, position) = fixture::position(ra_fixture);
580 let hover = analysis.hover(position, true, true).unwrap().unwrap();
582 let content = analysis.db.file_text(position.file_id);
583 let hovered_element = &content[hover.range];
585 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
586 expect.assert_eq(&actual)
589 fn check_hover_no_links(ra_fixture: &str, expect: Expect) {
590 let (analysis, position) = fixture::position(ra_fixture);
591 let hover = analysis.hover(position, false, true).unwrap().unwrap();
593 let content = analysis.db.file_text(position.file_id);
594 let hovered_element = &content[hover.range];
596 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
597 expect.assert_eq(&actual)
600 fn check_hover_no_markdown(ra_fixture: &str, expect: Expect) {
601 let (analysis, position) = fixture::position(ra_fixture);
602 let hover = analysis.hover(position, true, false).unwrap().unwrap();
604 let content = analysis.db.file_text(position.file_id);
605 let hovered_element = &content[hover.range];
607 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
608 expect.assert_eq(&actual)
611 fn check_actions(ra_fixture: &str, expect: Expect) {
612 let (analysis, position) = fixture::position(ra_fixture);
613 let hover = analysis.hover(position, true, true).unwrap().unwrap();
614 expect.assert_debug_eq(&hover.info.actions)
618 fn hover_shows_type_of_an_expression() {
621 pub fn foo() -> u32 { 1 }
624 let foo_test = foo()$0;
637 fn hover_remove_markdown_if_configured() {
638 check_hover_no_markdown(
640 pub fn foo() -> u32 { 1 }
643 let foo_test = foo()$0;
654 fn hover_shows_long_type_of_an_expression() {
657 struct Scan<A, B, C> { a: A, b: B, c: C }
658 struct Iter<I> { inner: I }
659 enum Option<T> { Some(T), None }
661 struct OtherStruct<T> { i: T }
663 fn scan<A, B, C>(a: A, b: B, c: C) -> Iter<Scan<OtherStruct<A>, B, C>> {
664 Iter { inner: Scan { a, b, c } }
669 let closure = |memo: &mut u32, value: &u32, _another: &mut u32| -> Option<u32> {
670 Option::Some(*memo + value)
673 let mut iter$0 = scan(OtherStruct { i: num }, closure, number);
680 let mut iter: Iter<Scan<OtherStruct<OtherStruct<i32>>, |&mut u32, &u32, &mut u32| -> Option<u32>, u32>>
687 fn hover_shows_fn_signature() {
688 // Single file with result
691 pub fn foo() -> u32 { 1 }
693 fn main() { let foo_test = fo$0o(); }
708 // Multiple candidates but results are ambiguous.
712 pub fn foo() -> u32 { 1 }
715 pub fn foo() -> &str { "" }
718 pub fn foo(a: u32, b: u32) {}
725 fn main() { let foo_test = fo$0o(); }
737 fn hover_shows_fn_signature_with_type_params() {
740 pub fn foo<'a, T: AsRef<str>>(b: &'a T) -> &'a str { }
742 fn main() { let foo_test = fo$0o(); }
752 pub fn foo<'a, T>(b: &'a T) -> &'a str
761 fn hover_shows_fn_signature_on_fn_name() {
764 pub fn foo$0(a: u32, b: u32) -> u32 {}
776 pub fn foo(a: u32, b: u32) -> u32
783 fn hover_shows_fn_doc() {
788 /// # use std::path::Path;
790 /// foo(Path::new("hello, world!"))
792 pub fn foo$0(_: &Path) {}
812 # use std::path::Path;
814 foo(Path::new("hello, world!"))
821 fn hover_shows_fn_doc_attr_raw_string() {
824 #[doc = r#"Raw string doc attr"#]
825 pub fn foo$0(_: &Path) {}
848 fn hover_shows_struct_field_info() {
849 // Hovering over the field when instantiating
852 struct Foo { field_a: u32 }
855 let foo = Foo { field_a$0: 0, };
871 // Hovering over the field in the definition
874 struct Foo { field_a$0: u32 }
877 let foo = Foo { field_a: 0 };
895 fn hover_const_static() {
897 r#"const foo$0: u32 = 123;"#,
911 r#"static foo$0: u32 = 456;"#,
927 fn hover_default_generic_types() {
930 struct Test<K, T = u8> { k: K, t: T }
933 let zz$0 = Test { t: 23u8, k: 33 };
939 let zz: Test<i32, u8>
949 enum Option<T> { Some(T) }
952 fn main() { So$0me(12); }
969 enum Option<T> { Some(T) }
972 fn main() { let b$0ar = Some(12); }
985 fn hover_enum_variant() {
1013 /// The Some variant
1017 let s = Option::Som$0e(12);
1039 fn hover_for_local_variable() {
1041 r#"fn func(foo: i32) { fo$0o; }"#,
1053 fn hover_for_local_variable_pat() {
1055 r#"fn func(fo$0o: i32) {}"#,
1067 fn hover_local_var_edge() {
1069 r#"fn func(foo: i32) { if true { $0foo; }; }"#,
1081 fn hover_for_param_edge() {
1083 r#"fn func($0foo: i32) {}"#,
1095 fn hover_for_param_with_multiple_traits() {
1098 type Target: ?Sized;
1101 type Target: ?Sized;
1103 fn f(_x$0: impl Deref<Target=u8> + DerefMut<Target=u8>) {}"#,
1108 _x: impl Deref<Target = u8> + DerefMut<Target = u8>
1115 fn test_hover_infer_associated_method_result() {
1118 struct Thing { x: u32 }
1121 fn new() -> Thing { Thing { x: 0 } }
1124 fn main() { let foo_$0test = Thing::new(); }
1137 fn test_hover_infer_associated_method_exact() {
1141 struct Thing { x: u32 }
1144 fn new() -> Thing { Thing { x: 0 } }
1148 fn main() { let foo_test = wrapper::Thing::new$0(); }
1154 test::wrapper::Thing
1165 fn test_hover_infer_associated_const_in_pattern() {
1196 fn test_hover_self() {
1199 struct Thing { x: u32 }
1201 fn new() -> Self { Self$0 { x: 0 } }
1218 struct Thing { x: u32 }
1220 fn new() -> Self$0 { Self { x: 0 } }
1239 pub fn new() -> Self$0 { Thing::A }
1258 pub fn thing(a: Self$0) {}
1276 fn test_hover_shadowing_pat() {
1297 fn test_hover_macro_invocation() {
1300 macro_rules! foo { () => {} }
1302 fn f() { fo$0o!(); }
1319 fn test_hover_macro2_invocation() {
1327 fn f() { fo$0o!(); }
1350 fn test_hover_tuple_field() {
1352 r#"struct TS(String, i32$0);"#,
1364 fn test_hover_through_macro() {
1367 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1370 fn bar() { fo$0o(); }
1388 fn test_hover_through_expr_in_macro() {
1391 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1392 fn foo(bar:u32) { let a = id!(ba$0r); }
1405 fn test_hover_through_expr_in_macro_recursive() {
1408 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1409 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1410 fn foo(bar:u32) { let a = id!(ba$0r); }
1423 fn test_hover_through_func_in_macro_recursive() {
1426 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1427 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1428 fn bar() -> u32 { 0 }
1429 fn foo() { let a = id!([0u32, bar($0)] ); }
1441 fn test_hover_through_literal_string_in_macro() {
1444 macro_rules! arr { ($($tt:tt)*) => { [$($tt)*)] } }
1446 let mastered_for_itunes = "";
1447 let _ = arr!("Tr$0acks", &mastered_for_itunes);
1460 fn test_hover_through_assert_macro() {
1463 #[rustc_builtin_macro]
1464 macro_rules! assert {}
1466 fn bar() -> bool { true }
1486 fn test_hover_through_literal_string_in_builtin_macro() {
1487 check_hover_no_result(
1489 #[rustc_builtin_macro]
1490 macro_rules! format {}
1493 format!("hel$0lo {}", 0);
1500 fn test_hover_non_ascii_space_doc() {
1503 /// <- `\u{3000}` here
1506 fn bar() { fo$0o(); }
1527 fn test_hover_function_show_qualifiers() {
1529 r#"async fn foo$0() {}"#,
1543 r#"pub const unsafe fn foo$0() {}"#,
1552 pub const unsafe fn foo()
1556 // Top level `pub(crate)` will be displayed as no visibility.
1558 r#"mod m { pub(crate) async unsafe extern "C" fn foo$0() {} }"#,
1567 pub(crate) async unsafe extern "C" fn foo()
1574 fn test_hover_trait_show_qualifiers() {
1576 r"unsafe trait foo$0() {}",
1593 fn test_hover_extern_crate() {
1596 //- /main.rs crate:main deps:std
1598 //- /std/lib.rs crate:std
1599 //! Standard library for this test
1613 Standard library for this test
1621 //- /main.rs crate:main deps:std
1622 extern crate std as ab$0c;
1623 //- /std/lib.rs crate:std
1624 //! Standard library for this test
1638 Standard library for this test
1647 fn test_hover_mod_with_same_name_as_function() {
1650 use self::m$0y::Bar;
1651 mod my { pub struct Bar; }
1670 fn test_hover_struct_doc_comment() {
1673 /// This is an example
1681 /// assert_eq!(6, my_crate::add_one(5));
1685 fn foo() { let bar = Ba$0r; }
1708 assert_eq!(6, my_crate::add_one(5));
1715 fn test_hover_struct_doc_attr() {
1721 fn foo() { let bar = Ba$0r; }
1742 fn test_hover_struct_doc_attr_multiple_and_mixed() {
1746 #[doc = "bar docs 1"]
1747 #[doc = "bar docs 2"]
1750 fn foo() { let bar = Ba$0r; }
1773 fn test_hover_path_link() {
1777 /// [Foo](struct.Foo.html)
1793 [Foo](https://docs.rs/test/*/test/struct.Foo.html)
1799 fn test_hover_path_link_no_strip() {
1803 /// [struct Foo](struct.Foo.html)
1819 [struct Foo](https://docs.rs/test/*/test/struct.Foo.html)
1824 #[ignore = "path based links currently only support documentation on ModuleDef items"]
1826 fn test_hover_path_link_field() {
1831 /// [Foo](struct.Foo.html)
1848 [Foo](https://docs.rs/test/*/test/struct.Foo.html)
1854 fn test_hover_intra_link() {
1876 [Foo](https://docs.rs/test/*/test/foo/struct.Foo.html)
1882 fn test_hover_intra_link_html_root_url() {
1885 #![doc(arbitrary_attribute = "test", html_root_url = "https:/example.com", arbitrary_attribute2)]
1906 [Foo](https://example.com/test/foo/struct.Foo.html)
1912 fn test_hover_intra_link_shortlink() {
1932 [Foo](https://docs.rs/test/*/test/struct.Foo.html)
1938 fn test_hover_intra_link_shortlink_code() {
1958 [`Foo`](https://docs.rs/test/*/test/struct.Foo.html)
1964 fn test_hover_intra_link_namespaced() {
1985 [Foo](https://docs.rs/test/*/test/struct.Foo.html)
1991 fn test_hover_intra_link_shortlink_namspaced_code() {
2011 [`Foo`](https://docs.rs/test/*/test/struct.Foo.html)
2017 fn test_hover_intra_link_shortlink_namspaced_code_with_at() {
2037 [`Foo`](https://docs.rs/test/*/test/struct.Foo.html)
2043 fn test_hover_intra_link_reference() {
2065 [my Foo](https://docs.rs/test/*/test/struct.Foo.html)
2070 fn test_hover_intra_link_reference_to_trait_method() {
2078 /// [buzz]: Foo::buzz
2094 [Foo](https://docs.rs/test/*/test/trait.Foo.html#tymethod.buzz)
2100 fn test_hover_external_url() {
2104 /// [external](https://www.google.com)
2120 [external](https://www.google.com)
2125 // Check that we don't rewrite links which we can't identify
2127 fn test_hover_unknown_target() {
2153 fn test_doc_links_enum_variant() {
2174 [E](https://docs.rs/test/*/test/enum.E.html)
2180 fn test_doc_links_field() {
2201 [`S`](https://docs.rs/test/*/test/struct.S.html)
2207 fn test_hover_no_links() {
2208 check_hover_no_links(
2211 /// case 1. bare URL: https://www.example.com/
2212 /// case 2. inline URL with title: [example](https://www.example.com/)
2213 /// case 3. code reference: [`Result`]
2214 /// case 4. code reference but miss footnote: [`String`]
2215 /// case 5. autolink: <http://www.example.com/>
2216 /// case 6. email address: <test@example.com>
2217 /// case 7. reference: [example][example]
2218 /// case 8. collapsed link: [example][]
2219 /// case 9. shortcut link: [example]
2220 /// case 10. inline without URL: [example]()
2221 /// case 11. reference: [foo][foo]
2222 /// case 12. reference: [foo][bar]
2223 /// case 13. collapsed link: [foo][]
2224 /// case 14. shortcut link: [foo]
2225 /// case 15. inline without URL: [foo]()
2226 /// case 16. just escaped text: \[foo]
2227 /// case 17. inline link: [Foo](foo::Foo)
2229 /// [`Result`]: ../../std/result/enum.Result.html
2230 /// [^example]: https://www.example.com/
2247 case 1. bare URL: https://www.example.com/
2248 case 2. inline URL with title: [example](https://www.example.com/)
2249 case 3. code reference: `Result`
2250 case 4. code reference but miss footnote: `String`
2251 case 5. autolink: http://www.example.com/
2252 case 6. email address: test@example.com
2253 case 7. reference: example
2254 case 8. collapsed link: example
2255 case 9. shortcut link: example
2256 case 10. inline without URL: example
2257 case 11. reference: foo
2258 case 12. reference: foo
2259 case 13. collapsed link: foo
2260 case 14. shortcut link: foo
2261 case 15. inline without URL: foo
2262 case 16. just escaped text: \[foo]
2263 case 17. inline link: Foo
2265 [^example]: https://www.example.com/
2271 fn test_hover_macro_generated_struct_fn_doc_comment() {
2272 cov_mark::check!(hover_macro_generated_struct_fn_doc_comment);
2288 fn foo() { let bar = Bar; bar.fo$0o(); }
2309 fn test_hover_macro_generated_struct_fn_doc_attr() {
2310 cov_mark::check!(hover_macro_generated_struct_fn_doc_attr);
2318 #[doc = "Do the foo"]
2326 fn foo() { let bar = Bar; bar.fo$0o(); }
2347 fn test_hover_trait_has_impl_action() {
2349 r#"trait foo$0() {}"#,
2366 fn test_hover_struct_has_impl_action() {
2368 r"struct foo$0() {}",
2385 fn test_hover_union_has_impl_action() {
2387 r#"union foo$0() {}"#,
2404 fn test_hover_enum_has_impl_action() {
2406 r"enum foo$0() { A, B }",
2423 fn test_hover_self_has_impl_action() {
2425 r#"struct foo where Self$0:;"#,
2442 fn test_hover_test_has_action() {
2460 nav: NavigationTarget {
2465 focus_range: 11..19,
2486 fn test_hover_test_mod_has_action() {
2498 nav: NavigationTarget {
2519 fn test_hover_struct_has_goto_type_action() {
2524 fn main() { let s$0t = S{ f1:0 }; }
2531 mod_path: "test::S",
2532 nav: NavigationTarget {
2540 description: "struct S",
2551 fn test_hover_generic_struct_has_goto_type_actions() {
2555 struct S<T>{ f1: T }
2557 fn main() { let s$0t = S{ f1:Arg(0) }; }
2564 mod_path: "test::S",
2565 nav: NavigationTarget {
2570 focus_range: 24..25,
2573 description: "struct S<T>",
2577 mod_path: "test::Arg",
2578 nav: NavigationTarget {
2586 description: "struct Arg",
2597 fn test_hover_generic_struct_has_flattened_goto_type_actions() {
2601 struct S<T>{ f1: T }
2603 fn main() { let s$0t = S{ f1: S{ f1: Arg(0) } }; }
2610 mod_path: "test::S",
2611 nav: NavigationTarget {
2616 focus_range: 24..25,
2619 description: "struct S<T>",
2623 mod_path: "test::Arg",
2624 nav: NavigationTarget {
2632 description: "struct Arg",
2643 fn test_hover_tuple_has_goto_type_actions() {
2652 fn main() { let s$0t = (A(1), B(2), M::C(3) ); }
2659 mod_path: "test::A",
2660 nav: NavigationTarget {
2668 description: "struct A",
2672 mod_path: "test::B",
2673 nav: NavigationTarget {
2678 focus_range: 22..23,
2681 description: "struct B",
2685 mod_path: "test::M::C",
2686 nav: NavigationTarget {
2691 focus_range: 53..54,
2694 description: "pub struct C",
2705 fn test_hover_return_impl_trait_has_goto_type_action() {
2709 fn foo() -> impl Foo {}
2711 fn main() { let s$0t = foo(); }
2718 mod_path: "test::Foo",
2719 nav: NavigationTarget {
2727 description: "trait Foo",
2738 fn test_hover_generic_return_impl_trait_has_goto_type_action() {
2743 fn foo() -> impl Foo<S> {}
2745 fn main() { let s$0t = foo(); }
2752 mod_path: "test::Foo",
2753 nav: NavigationTarget {
2761 description: "trait Foo<T>",
2765 mod_path: "test::S",
2766 nav: NavigationTarget {
2771 focus_range: 23..24,
2774 description: "struct S",
2785 fn test_hover_return_impl_traits_has_goto_type_action() {
2790 fn foo() -> impl Foo + Bar {}
2792 fn main() { let s$0t = foo(); }
2799 mod_path: "test::Foo",
2800 nav: NavigationTarget {
2808 description: "trait Foo",
2812 mod_path: "test::Bar",
2813 nav: NavigationTarget {
2818 focus_range: 19..22,
2821 description: "trait Bar",
2832 fn test_hover_generic_return_impl_traits_has_goto_type_action() {
2840 fn foo() -> impl Foo<S1> + Bar<S2> {}
2842 fn main() { let s$0t = foo(); }
2849 mod_path: "test::Foo",
2850 nav: NavigationTarget {
2858 description: "trait Foo<T>",
2862 mod_path: "test::Bar",
2863 nav: NavigationTarget {
2868 focus_range: 22..25,
2871 description: "trait Bar<T>",
2875 mod_path: "test::S1",
2876 nav: NavigationTarget {
2881 focus_range: 39..41,
2884 description: "struct S1",
2888 mod_path: "test::S2",
2889 nav: NavigationTarget {
2894 focus_range: 52..54,
2897 description: "struct S2",
2908 fn test_hover_arg_impl_trait_has_goto_type_action() {
2912 fn foo(ar$0g: &impl Foo) {}
2919 mod_path: "test::Foo",
2920 nav: NavigationTarget {
2928 description: "trait Foo",
2939 fn test_hover_arg_impl_traits_has_goto_type_action() {
2946 fn foo(ar$0g: &impl Foo + Bar<S>) {}
2953 mod_path: "test::Foo",
2954 nav: NavigationTarget {
2962 description: "trait Foo",
2966 mod_path: "test::Bar",
2967 nav: NavigationTarget {
2972 focus_range: 19..22,
2975 description: "trait Bar<T>",
2979 mod_path: "test::S",
2980 nav: NavigationTarget {
2985 focus_range: 36..37,
2988 description: "struct S",
2999 fn test_hover_async_block_impl_trait_has_goto_type_action() {
3004 let fo$0o = async { S };
3007 #[prelude_import] use future::*;
3009 #[lang = "future_trait"]
3010 pub trait Future { type Output; }
3018 mod_path: "test::future::Future",
3019 nav: NavigationTarget {
3023 full_range: 101..163,
3024 focus_range: 140..146,
3027 description: "pub trait Future",
3031 mod_path: "test::S",
3032 nav: NavigationTarget {
3040 description: "struct S",
3051 fn test_hover_arg_generic_impl_trait_has_goto_type_action() {
3056 fn foo(ar$0g: &impl Foo<S>) {}
3063 mod_path: "test::Foo",
3064 nav: NavigationTarget {
3072 description: "trait Foo<T>",
3076 mod_path: "test::S",
3077 nav: NavigationTarget {
3082 focus_range: 23..24,
3085 description: "struct S",
3096 fn test_hover_dyn_return_has_goto_type_action() {
3104 fn foo() -> B<dyn Foo> {}
3106 fn main() { let s$0t = foo(); }
3113 mod_path: "test::B",
3114 nav: NavigationTarget {
3119 focus_range: 49..50,
3122 description: "struct B<T>",
3126 mod_path: "test::Foo",
3127 nav: NavigationTarget {
3135 description: "trait Foo",
3146 fn test_hover_dyn_arg_has_goto_type_action() {
3150 fn foo(ar$0g: &dyn Foo) {}
3157 mod_path: "test::Foo",
3158 nav: NavigationTarget {
3166 description: "trait Foo",
3177 fn test_hover_generic_dyn_arg_has_goto_type_action() {
3182 fn foo(ar$0g: &dyn Foo<S>) {}
3189 mod_path: "test::Foo",
3190 nav: NavigationTarget {
3198 description: "trait Foo<T>",
3202 mod_path: "test::S",
3203 nav: NavigationTarget {
3208 focus_range: 23..24,
3211 description: "struct S",
3222 fn test_hover_goto_type_action_links_order() {
3225 trait ImplTrait<T> {}
3226 trait DynTrait<T> {}
3230 fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
3237 mod_path: "test::ImplTrait",
3238 nav: NavigationTarget {
3246 description: "trait ImplTrait<T>",
3250 mod_path: "test::B",
3251 nav: NavigationTarget {
3256 focus_range: 50..51,
3259 description: "struct B<T>",
3263 mod_path: "test::DynTrait",
3264 nav: NavigationTarget {
3269 focus_range: 28..36,
3272 description: "trait DynTrait<T>",
3276 mod_path: "test::S",
3277 nav: NavigationTarget {
3282 focus_range: 65..66,
3285 description: "struct S",
3296 fn test_hover_associated_type_has_goto_type_action() {
3301 fn get(self) -> Self::Item {}
3307 impl Foo for S { type Item = Bar; }
3309 fn test() -> impl Foo { S {} }
3311 fn main() { let s$0t = test().get(); }
3318 mod_path: "test::Foo",
3319 nav: NavigationTarget {
3327 description: "trait Foo",
3338 fn test_hover_const_param_has_goto_type_action() {
3342 struct Foo<const BAR: Bar>;
3344 impl<const BAR: Bar> Foo<BAR$0> {}
3351 mod_path: "test::Bar",
3352 nav: NavigationTarget {
3360 description: "struct Bar",
3371 fn test_hover_type_param_has_goto_type_action() {
3376 fn foo<T: Foo>(t: T$0){}
3383 mod_path: "test::Foo",
3384 nav: NavigationTarget {
3392 description: "trait Foo",
3403 fn test_hover_self_has_go_to_type() {
3416 mod_path: "test::Foo",
3417 nav: NavigationTarget {
3425 description: "struct Foo",
3436 fn hover_displays_normalized_crate_names() {
3439 //- /lib.rs crate:name-with-dashes
3441 pub struct Thing { x: u32 }
3444 pub fn new() -> Thing { Thing { x: 0 } }
3448 //- /main.rs crate:main deps:name-with-dashes
3449 fn main() { let foo_test = name_with_dashes::wrapper::Thing::new$0(); }
3455 name_with_dashes::wrapper::Thing
3459 pub fn new() -> Thing
3466 fn hover_field_pat_shorthand_ref_match_ergonomics() {
3489 fn hover_self_param_shows_type() {
3508 fn hover_self_param_shows_type_for_arbitrary_self_type() {
3514 fn bar(sel$0f: Arc<Foo>) {}
3528 fn hover_doc_outer_inner() {
3535 /// This comment belongs to the function
3559 fn hover_doc_outer_inner_attribue() {
3562 #[doc = "Be quick;"]
3564 #![doc = "time is mana"]
3566 #[doc = "This comment belongs to the function"]
3590 fn hover_doc_block_style_indentend() {
3624 fn hover_comments_dont_highlight_parent() {
3625 cov_mark::check!(no_highlight_on_comment_hover);
3626 check_hover_no_result(
3654 fn hover_lifetime() {
3656 r#"fn foo<'lifetime>(_: &'lifetime$0 ()) {}"#,
3668 fn hover_type_param() {
3675 impl<T: Copy + Clone> Foo<T$0> where T: Sized {}
3681 T: Copy + Clone + Sized
3698 // lifetimes bounds arent being tracked yet
3702 impl<T: 'static> Foo<T$0> {}
3715 fn hover_const_param() {
3718 struct Foo<const LEN: usize>;
3719 impl<const LEN: usize> Foo<LEN$0> {}
3732 fn hover_const_pat() {
3736 const FOO: usize = 3;
3763 fn hover_mod_def() {
3790 fn hover_self_in_use() {
3793 //! This should not appear
3795 /// But this should appear
3798 use foo::bar::{self$0};
3813 But this should appear
3819 fn hover_keyword() {
3820 let ra_fixture = r#"//- /main.rs crate:main deps:std
3821 fn f() { retur$0n; }"#;
3822 let fixture = format!("{}\n{}", ra_fixture, FamousDefs::FIXTURE);
3834 Docs for return_keyword
3840 fn hover_builtin() {
3841 let ra_fixture = r#"//- /main.rs crate:main deps:std
3842 cosnt _: &str$0 = ""; }"#;
3843 let fixture = format!("{}\n{}", ra_fixture, FamousDefs::FIXTURE);
3861 fn hover_macro_expanded_function() {
3864 struct S<'a, T>(&'a T);
3868 fn bar<'t, T: Clone + 't>(s: &mut S<'t, T>, t: u32) -> *mut u32 where
3870 for<'a> T: Clone + 'a
3889 fn bar<'t, T>(s: &mut S<'t, T>, t: u32) -> *mut u32
3893 for<'a> T: Clone + 'a,
3900 fn hover_intra_doc_links() {
3905 /// This is the item. Cool!
3909 /// Gives you a [`TheItem$0`].
3911 /// [`TheItem`]: theitem::TheItem
3912 pub fn gimme() -> theitem::TheItem {
3929 This is the item. Cool!
3935 fn hover_generic_assoc() {
3938 fn foo<T: A>() where T::Assoc$0: {}
3958 let _: <T>::Assoc$0;
3998 fn string_shadowed_with_inner_items() {
4001 //- /main.rs crate:main deps:alloc
4003 /// Custom `String` type.
4012 //- /alloc.rs crate:alloc
4017 /// This is `alloc::String`.
4034 Custom `String` type.
4040 fn function_doesnt_shadow_crate_in_use_tree() {
4043 //- /main.rs crate:main deps:foo
4046 //- /foo.rs crate:foo
4060 fn hover_feature() {
4062 r#"#![feature(box_syntax$0)]"#,
4072 The tracking issue for this feature is: [#49733]
4074 [#49733]: https://github.com/rust-lang/rust/issues/49733
4076 See also [`box_patterns`](box-patterns.md)
4078 ------------------------
4080 Currently the only stable way to create a `Box` is via the `Box::new` method.
4081 Also it is not possible in stable Rust to destructure a `Box` in a match
4082 pattern. The unstable `box` keyword can be used to create a `Box`. An example
4086 #![feature(box_syntax)]
4100 r#"#![allow(arithmetic_overflow$0)]"#,
4102 *arithmetic_overflow*
4108 arithmetic operation overflows
4114 fn hover_clippy_lint() {
4116 r#"#![allow(clippy::almost_swapped$0)]"#,
4120 clippy::almost_swapped
4124 Checks for `foo = bar; bar = foo` sequences.