1 use std::{collections::HashSet, ops::ControlFlow};
4 use hir::{AsAssocItem, HasAttrs, HasSource, HirDisplay, Semantics, TypeInfo};
6 base_db::{FileRange, SourceDatabase},
7 defs::{Definition, NameClass, NameRefClass},
9 generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES},
10 pick_best_token, try_resolve_derive_input_at, FamousDefs,
14 use itertools::Itertools;
17 algo, ast, display::fn_as_proc_macro_label, match_ast, AstNode, Direction, SyntaxKind::*,
18 SyntaxNode, SyntaxToken, TextRange, TextSize, T,
22 display::{macro_label, TryToNav},
24 doc_attributes, extract_definitions_from_docs, remove_links, resolve_doc_path_for_def,
27 markdown_remove::remove_markdown,
29 runnables::{runnable_fn, runnable_mod},
30 FileId, FilePosition, NavigationTarget, RangeInfo, Runnable,
33 #[derive(Clone, Debug, PartialEq, Eq)]
34 pub struct HoverConfig {
35 pub links_in_hover: bool,
36 pub documentation: Option<HoverDocFormat>,
40 fn markdown(&self) -> bool {
41 matches!(self.documentation, Some(HoverDocFormat::Markdown))
45 #[derive(Clone, Debug, PartialEq, Eq)]
46 pub enum HoverDocFormat {
51 #[derive(Debug, Clone)]
52 pub enum HoverAction {
54 Implementation(FilePosition),
55 Reference(FilePosition),
56 GoToType(Vec<HoverGotoTypeData>),
60 fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
64 Some(HoverGotoTypeData {
65 mod_path: render_path(
68 it.name(db).map(|name| name.to_string()),
70 nav: it.try_to_nav(db)?,
74 HoverAction::GoToType(targets)
78 #[derive(Debug, Clone, Eq, PartialEq)]
79 pub struct HoverGotoTypeData {
81 pub nav: NavigationTarget,
84 /// Contains the results when hovering over an item
85 #[derive(Debug, Default)]
86 pub struct HoverResult {
88 pub actions: Vec<HoverAction>,
93 // Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
94 // Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
96 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
99 FileRange { file_id, range }: FileRange,
100 config: &HoverConfig,
101 ) -> Option<RangeInfo<HoverResult>> {
102 let sema = hir::Semantics::new(db);
103 let file = sema.parse(file_id).syntax().clone();
105 if !range.is_empty() {
106 return hover_ranged(&file, range, &sema, config);
108 let offset = range.start();
110 let token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
111 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] => 3,
112 T!['('] | T![')'] => 2,
113 kind if kind.is_trivia() => 0,
117 let mut seen = HashSet::default();
119 let mut fallback = None;
120 // attributes, require special machinery as they are mere ident tokens
121 if token.kind() != COMMENT {
122 if let Some(attr) = token.ancestors().find_map(ast::Attr::cast) {
124 if let Some(res) = try_hover_for_lint(&attr, &token) {
128 let def = try_resolve_derive_input_at(&sema, &attr, &token).map(Definition::Macro);
129 if let Some(def) = def {
131 hover_for_definition(&sema, file_id, def, &token.parent().unwrap(), config)
133 return Some(RangeInfo::new(token.text_range(), hover));
140 sema.descend_into_macros_many(token.clone())
142 .filter_map(|token| match token.parent() {
144 match find_hover_result(&sema, file_id, offset, config, token, &node, &mut seen) {
145 Some(res) => match res {
146 ControlFlow::Break(inner) => Some(inner),
147 ControlFlow::Continue(_) => {
148 if fallback.is_none() {
149 // FIXME we're only taking the first fallback into account that's not `None`
150 fallback = hover_for_keyword(&sema, config, &token)
151 .or(type_hover(&sema, config, &token));
161 // reduce all descends into a single `RangeInfo`
162 // that spans from the earliest start to the latest end (fishy/FIXME),
163 // concatenates all `Markup`s with `\n---\n`,
164 // and accumulates all actions into its `actions` vector.
165 .reduce(|mut acc, RangeInfo { range, mut info }| {
166 let start = acc.range.start().min(range.start());
167 let end = acc.range.end().max(range.end());
169 acc.range = TextRange::new(start, end);
170 acc.info.actions.append(&mut info.actions);
171 acc.info.markup = Markup::from(format!("{}\n---\n{}", acc.info.markup, info.markup));
177 fn find_hover_result(
178 sema: &Semantics<RootDatabase>,
181 config: &HoverConfig,
184 seen: &mut HashSet<Definition>,
185 ) -> Option<ControlFlow<RangeInfo<HoverResult>>> {
186 let mut range_override = None;
188 // intra-doc links and attributes are special cased
189 // so don't add them to the `seen` duplicate check
190 let mut add_to_seen_definitions = true;
192 let definition = find_definition(sema, node).or_else(|| {
194 // FIXME: move comment + attribute special cases somewhere else to simplify control flow,
195 // hopefully simplifying the return type of this function in the process
196 // (the `Break`/`Continue` distinction is needed to decide whether to use fallback hovers)
198 // FIXME: hovering the intra doc link to `Foo` not working:
204 if token.kind() == COMMENT {
205 add_to_seen_definitions = false;
206 cov_mark::hit!(no_highlight_on_comment_hover);
207 let (attributes, def) = doc_attributes(sema, node)?;
208 let (docs, doc_mapping) = attributes.docs_with_rangemap(sema.db)?;
209 let (idl_range, link, ns) = extract_definitions_from_docs(&docs).into_iter().find_map(
210 |(range, link, ns)| {
211 let mapped = doc_mapping.map(range)?;
212 (mapped.file_id == file_id.into() && mapped.value.contains(offset))
213 .then(|| (mapped.value, link, ns))
216 range_override = Some(idl_range);
217 Some(match resolve_doc_path_for_def(sema.db, def, &link, ns)? {
218 Either::Left(it) => Definition::ModuleDef(it),
219 Either::Right(it) => Definition::Macro(it),
226 if let Some(definition) = definition {
228 if seen.contains(&definition) {
231 if add_to_seen_definitions {
232 seen.insert(definition);
234 if let Some(res) = hover_for_definition(sema, file_id, definition, &node, config) {
235 let range = range_override.unwrap_or_else(|| sema.original_range(&node).range);
236 return Some(ControlFlow::Break(RangeInfo::new(range, res)));
240 Some(ControlFlow::Continue(()))
244 sema: &Semantics<RootDatabase>,
245 config: &HoverConfig,
247 ) -> Option<RangeInfo<HoverResult>> {
248 if token.kind() == COMMENT {
253 .take_while(|it| !ast::Item::can_cast(it.kind()))
254 .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
256 let expr_or_pat = match_ast! {
258 ast::Expr(it) => Either::Left(it),
259 ast::Pat(it) => Either::Right(it),
260 // If this node is a MACRO_CALL, it means that `descend_into_macros_many` failed to resolve.
261 // (e.g expanding a builtin macro). So we give up here.
262 ast::MacroCall(_it) => return None,
267 let res = hover_type_info(&sema, config, &expr_or_pat)?;
268 let range = sema.original_range(&node).range;
269 Some(RangeInfo::new(range, res))
274 range: syntax::TextRange,
275 sema: &Semantics<RootDatabase>,
276 config: &HoverConfig,
277 ) -> Option<RangeInfo<HoverResult>> {
278 let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
281 ast::Expr(expr) => Some(Either::Left(expr)),
282 ast::Pat(pat) => Some(Either::Right(pat)),
287 let res = match &expr_or_pat {
288 Either::Left(ast::Expr::TryExpr(try_expr)) => hover_try_expr(sema, config, try_expr),
289 Either::Left(ast::Expr::PrefixExpr(prefix_expr))
290 if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
292 hover_deref_expr(sema, config, prefix_expr)
296 let res = res.or_else(|| hover_type_info(sema, config, &expr_or_pat));
298 let range = match expr_or_pat {
299 Either::Left(it) => it.syntax().text_range(),
300 Either::Right(it) => it.syntax().text_range(),
302 RangeInfo::new(range, it)
307 sema: &Semantics<RootDatabase>,
308 config: &HoverConfig,
309 try_expr: &ast::TryExpr,
310 ) -> Option<HoverResult> {
311 let inner_ty = sema.type_of_expr(&try_expr.expr()?)?.original;
312 let mut ancestors = try_expr.syntax().ancestors();
313 let mut body_ty = loop {
314 let next = ancestors.next()?;
317 ast::Fn(fn_) => sema.to_def(&fn_)?.ret_type(sema.db),
318 ast::Item(__) => return None,
319 ast::ClosureExpr(closure) => sema.type_of_expr(&closure.body()?)?.original,
320 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
321 sema.type_of_expr(&effect.block_expr()?.into())?.original
330 if inner_ty == body_ty {
334 let mut inner_ty = inner_ty;
335 let mut s = "Try Target".to_owned();
337 let adts = inner_ty.as_adt().zip(body_ty.as_adt());
338 if let Some((hir::Adt::Enum(inner), hir::Adt::Enum(body))) = adts {
339 let famous_defs = FamousDefs(sema, sema.scope(&try_expr.syntax()).krate());
340 // special case for two options, there is no value in showing them
341 if let Some(option_enum) = famous_defs.core_option_Option() {
342 if inner == option_enum && body == option_enum {
343 cov_mark::hit!(hover_try_expr_opt_opt);
348 // special case two results to show the error variants only
349 if let Some(result_enum) = famous_defs.core_result_Result() {
350 if inner == result_enum && body == result_enum {
351 let error_type_args =
352 inner_ty.type_arguments().nth(1).zip(body_ty.type_arguments().nth(1));
353 if let Some((inner, body)) = error_type_args {
356 s = "Try Error".to_owned();
362 let mut res = HoverResult::default();
364 let mut targets: Vec<hir::ModuleDef> = Vec::new();
365 let mut push_new_def = |item: hir::ModuleDef| {
366 if !targets.contains(&item) {
370 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
371 walk_and_push_ty(sema.db, &body_ty, &mut push_new_def);
372 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
374 let inner_ty = inner_ty.display(sema.db).to_string();
375 let body_ty = body_ty.display(sema.db).to_string();
376 let ty_len_max = inner_ty.len().max(body_ty.len());
378 let l = "Propagated as: ".len() - " Type: ".len();
379 let static_text_len_diff = l as isize - s.len() as isize;
380 let tpad = static_text_len_diff.max(0) as usize;
381 let ppad = static_text_len_diff.min(0).abs() as usize;
383 res.markup = format!(
384 "{bt_start}{} Type: {:>pad0$}\nPropagated as: {:>pad1$}\n{bt_end}",
388 pad0 = ty_len_max + tpad,
389 pad1 = ty_len_max + ppad,
390 bt_start = if config.markdown() { "```text\n" } else { "" },
391 bt_end = if config.markdown() { "```\n" } else { "" }
398 sema: &Semantics<RootDatabase>,
399 config: &HoverConfig,
400 deref_expr: &ast::PrefixExpr,
401 ) -> Option<HoverResult> {
402 let inner_ty = sema.type_of_expr(&deref_expr.expr()?)?.original;
403 let TypeInfo { original, adjusted } =
404 sema.type_of_expr(&ast::Expr::from(deref_expr.clone()))?;
406 let mut res = HoverResult::default();
407 let mut targets: Vec<hir::ModuleDef> = Vec::new();
408 let mut push_new_def = |item: hir::ModuleDef| {
409 if !targets.contains(&item) {
413 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
414 walk_and_push_ty(sema.db, &original, &mut push_new_def);
416 res.markup = if let Some(adjusted_ty) = adjusted {
417 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
418 let original = original.display(sema.db).to_string();
419 let adjusted = adjusted_ty.display(sema.db).to_string();
420 let inner = inner_ty.display(sema.db).to_string();
421 let type_len = "To type: ".len();
422 let coerced_len = "Coerced to: ".len();
423 let deref_len = "Dereferenced from: ".len();
424 let max_len = (original.len() + type_len)
425 .max(adjusted.len() + coerced_len)
426 .max(inner.len() + deref_len);
428 "{bt_start}Dereferenced from: {:>ipad$}\nTo type: {:>apad$}\nCoerced to: {:>opad$}\n{bt_end}",
432 ipad = max_len - deref_len,
433 apad = max_len - type_len,
434 opad = max_len - coerced_len,
435 bt_start = if config.markdown() { "```text\n" } else { "" },
436 bt_end = if config.markdown() { "```\n" } else { "" }
440 let original = original.display(sema.db).to_string();
441 let inner = inner_ty.display(sema.db).to_string();
442 let type_len = "To type: ".len();
443 let deref_len = "Dereferenced from: ".len();
444 let max_len = (original.len() + type_len).max(inner.len() + deref_len);
446 "{bt_start}Dereferenced from: {:>ipad$}\nTo type: {:>apad$}\n{bt_end}",
449 ipad = max_len - deref_len,
450 apad = max_len - type_len,
451 bt_start = if config.markdown() { "```text\n" } else { "" },
452 bt_end = if config.markdown() { "```\n" } else { "" }
456 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
462 sema: &Semantics<RootDatabase>,
463 config: &HoverConfig,
464 expr_or_pat: &Either<ast::Expr, ast::Pat>,
465 ) -> Option<HoverResult> {
466 let TypeInfo { original, adjusted } = match expr_or_pat {
467 Either::Left(expr) => sema.type_of_expr(expr)?,
468 Either::Right(pat) => sema.type_of_pat(pat)?,
471 let mut res = HoverResult::default();
472 let mut targets: Vec<hir::ModuleDef> = Vec::new();
473 let mut push_new_def = |item: hir::ModuleDef| {
474 if !targets.contains(&item) {
478 walk_and_push_ty(sema.db, &original, &mut push_new_def);
480 res.markup = if let Some(adjusted_ty) = adjusted {
481 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
482 let original = original.display(sema.db).to_string();
483 let adjusted = adjusted_ty.display(sema.db).to_string();
484 let static_text_diff_len = "Coerced to: ".len() - "Type: ".len();
486 "{bt_start}Type: {:>apad$}\nCoerced to: {:>opad$}\n{bt_end}",
489 apad = static_text_diff_len + adjusted.len().max(original.len()),
490 opad = original.len(),
491 bt_start = if config.markdown() { "```text\n" } else { "" },
492 bt_end = if config.markdown() { "```\n" } else { "" }
496 if config.markdown() {
497 Markup::fenced_block(&original.display(sema.db))
499 original.display(sema.db).to_string().into()
502 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
506 fn try_hover_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option<RangeInfo<HoverResult>> {
507 let (path, tt) = attr.as_simple_call()?;
508 if !tt.syntax().text_range().contains(token.text_range().start()) {
511 let (is_clippy, lints) = match &*path {
512 "feature" => (false, FEATURES),
513 "allow" | "deny" | "forbid" | "warn" => {
514 let is_clippy = algo::non_trivia_sibling(token.clone().into(), Direction::Prev)
515 .filter(|t| t.kind() == T![:])
516 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
517 .filter(|t| t.kind() == T![:])
518 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
520 t.kind() == T![ident] && t.into_token().map_or(false, |t| t.text() == "clippy")
525 (false, DEFAULT_LINTS)
532 let needle = if is_clippy {
533 tmp = format!("clippy::{}", token.text());
540 lints.binary_search_by_key(&needle, |lint| lint.label).ok().map(|idx| &lints[idx])?;
544 markup: Markup::from(format!("```\n{}\n```\n___\n\n{}", lint.label, lint.description)),
550 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
551 fn to_action(nav_target: NavigationTarget) -> HoverAction {
552 HoverAction::Implementation(FilePosition {
553 file_id: nav_target.file_id,
554 offset: nav_target.focus_or_full_range().start(),
558 let adt = match def {
559 Definition::ModuleDef(hir::ModuleDef::Trait(it)) => {
560 return it.try_to_nav(db).map(to_action)
562 Definition::ModuleDef(hir::ModuleDef::Adt(it)) => Some(it),
563 Definition::SelfType(it) => it.self_ty(db).as_adt(),
566 adt.try_to_nav(db).map(to_action)
569 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
571 Definition::ModuleDef(hir::ModuleDef::Function(it)) => {
572 it.try_to_nav(db).map(|nav_target| {
573 HoverAction::Reference(FilePosition {
574 file_id: nav_target.file_id,
575 offset: nav_target.focus_or_full_range().start(),
584 sema: &hir::Semantics<RootDatabase>,
587 ) -> Option<HoverAction> {
589 Definition::ModuleDef(it) => match it {
590 hir::ModuleDef::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
591 hir::ModuleDef::Function(func) => {
592 let src = func.source(sema.db)?;
593 if src.file_id != file_id.into() {
594 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
595 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
599 runnable_fn(sema, func).map(HoverAction::Runnable)
607 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
608 let mut targets: Vec<hir::ModuleDef> = Vec::new();
609 let mut push_new_def = |item: hir::ModuleDef| {
610 if !targets.contains(&item) {
615 if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
616 it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
619 Definition::Local(it) => it.ty(db),
620 Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
621 Definition::Field(field) => field.ty(db),
625 walk_and_push_ty(db, &ty, &mut push_new_def);
628 Some(HoverAction::goto_type_from_targets(db, targets))
634 push_new_def: &mut dyn FnMut(hir::ModuleDef),
637 if let Some(adt) = t.as_adt() {
638 push_new_def(adt.into());
639 } else if let Some(trait_) = t.as_dyn_trait() {
640 push_new_def(trait_.into());
641 } else if let Some(traits) = t.as_impl_traits(db) {
642 traits.into_iter().for_each(|it| push_new_def(it.into()));
643 } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
644 push_new_def(trait_.into());
649 fn hover_markup(docs: Option<String>, desc: String, mod_path: Option<String>) -> Option<Markup> {
650 let mut buf = String::new();
652 if let Some(mod_path) = mod_path {
653 if !mod_path.is_empty() {
654 format_to!(buf, "```rust\n{}\n```\n\n", mod_path);
657 format_to!(buf, "```rust\n{}\n```", desc);
659 if let Some(doc) = docs {
660 format_to!(buf, "\n___\n\n{}", doc);
669 config: &HoverConfig,
671 let markup = markup.as_str();
672 let markup = if !config.markdown() {
673 remove_markdown(markup)
674 } else if config.links_in_hover {
675 rewrite_links(db, markup, def)
682 fn definition_owner_name(db: &RootDatabase, def: &Definition) -> Option<String> {
684 Definition::Field(f) => Some(f.parent_def(db).name(db)),
685 Definition::Local(l) => l.parent(db).name(db),
686 Definition::ModuleDef(md) => match md {
687 hir::ModuleDef::Function(f) => match f.as_assoc_item(db)?.container(db) {
688 hir::AssocItemContainer::Trait(t) => Some(t.name(db)),
689 hir::AssocItemContainer::Impl(i) => i.self_ty(db).as_adt().map(|adt| adt.name(db)),
691 hir::ModuleDef::Variant(e) => Some(e.parent_enum(db).name(db)),
696 .map(|name| name.to_string())
699 fn render_path(db: &RootDatabase, module: hir::Module, item_name: Option<String>) -> String {
701 db.crate_graph()[module.krate().into()].display_name.as_ref().map(|it| it.to_string());
702 let module_path = module
706 .flat_map(|it| it.name(db).map(|name| name.to_string()));
707 crate_name.into_iter().chain(module_path).chain(item_name).join("::")
710 fn definition_mod_path(db: &RootDatabase, def: &Definition) -> Option<String> {
711 if let Definition::GenericParam(_) = def {
714 def.module(db).map(|module| render_path(db, module, definition_owner_name(db, def)))
717 pub(crate) fn find_definition(
718 sema: &Semantics<RootDatabase>,
720 ) -> Option<Definition> {
723 ast::Name(name) => NameClass::classify(sema, &name).map(|class| match class {
724 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
725 NameClass::PatFieldShorthand { local_def, field_ref: _ } => Definition::Local(local_def),
727 ast::NameRef(name_ref) => NameRefClass::classify(sema, &name_ref).map(|class| match class {
728 NameRefClass::Definition(def) => def,
729 NameRefClass::FieldShorthand { local_ref: _, field_ref } => {
730 Definition::Field(field_ref)
733 ast::Lifetime(lifetime) => NameClass::classify_lifetime(&sema, &lifetime).map_or_else(
735 NameRefClass::classify_lifetime(&sema, &lifetime).and_then(|class| match class {
736 NameRefClass::Definition(it) => Some(it),
747 pub(crate) fn hover_for_definition(
748 sema: &Semantics<RootDatabase>,
750 definition: Definition,
752 config: &HoverConfig,
753 ) -> Option<HoverResult> {
754 let famous_defs = match &definition {
755 Definition::ModuleDef(hir::ModuleDef::BuiltinType(_)) => {
756 Some(FamousDefs(&sema, sema.scope(&node).krate()))
760 if let Some(markup) = markup_for_definition(sema.db, definition, famous_defs.as_ref(), config) {
761 let mut res = HoverResult::default();
762 res.markup = process_markup(sema.db, definition, &markup, config);
763 if let Some(action) = show_implementations_action(sema.db, definition) {
764 res.actions.push(action);
767 if let Some(action) = show_fn_references_action(sema.db, definition) {
768 res.actions.push(action);
771 if let Some(action) = runnable_action(&sema, definition, file_id) {
772 res.actions.push(action);
775 if let Some(action) = goto_type_action_for_def(sema.db, definition) {
776 res.actions.push(action);
783 fn markup_for_definition(
786 famous_defs: Option<&FamousDefs>,
787 config: &HoverConfig,
788 ) -> Option<Markup> {
789 let mod_path = definition_mod_path(db, &def);
790 let (label, docs) = match def {
791 Definition::Macro(it) => (
792 match &it.source(db)?.value {
793 Either::Left(mac) => macro_label(mac),
794 Either::Right(mac_fn) => fn_as_proc_macro_label(mac_fn),
798 Definition::Field(def) => label_and_docs(db, def),
799 Definition::ModuleDef(it) => match it {
800 hir::ModuleDef::Module(it) => label_and_docs(db, it),
801 hir::ModuleDef::Function(it) => label_and_docs(db, it),
802 hir::ModuleDef::Adt(it) => label_and_docs(db, it),
803 hir::ModuleDef::Variant(it) => label_and_docs(db, it),
804 hir::ModuleDef::Const(it) => label_and_docs(db, it),
805 hir::ModuleDef::Static(it) => label_and_docs(db, it),
806 hir::ModuleDef::Trait(it) => label_and_docs(db, it),
807 hir::ModuleDef::TypeAlias(it) => label_and_docs(db, it),
808 hir::ModuleDef::BuiltinType(it) => {
810 .and_then(|fd| hover_for_builtin(fd, it))
811 .or_else(|| Some(Markup::fenced_block(&it.name())))
814 Definition::Local(it) => return hover_for_local(it, db),
815 Definition::SelfType(impl_def) => {
816 impl_def.self_ty(db).as_adt().map(|adt| label_and_docs(db, adt))?
818 Definition::GenericParam(it) => label_and_docs(db, it),
819 Definition::Label(it) => return Some(Markup::fenced_block(&it.name(db))),
823 docs.filter(|_| config.documentation.is_some()).map(Into::into),
828 fn label_and_docs<D>(db: &RootDatabase, def: D) -> (String, Option<hir::Documentation>)
830 D: HasAttrs + HirDisplay,
832 let label = def.display(db).to_string();
833 let docs = def.attrs(db).docs();
838 fn hover_for_local(it: hir::Local, db: &RootDatabase) -> Option<Markup> {
840 let ty = ty.display(db);
841 let is_mut = if it.is_mut(db) { "mut " } else { "" };
842 let desc = match it.source(db).value {
843 Either::Left(ident) => {
844 let name = it.name(db).unwrap();
845 let let_kw = if ident
848 .map_or(false, |p| p.kind() == LET_STMT || p.kind() == CONDITION)
854 format!("{}{}{}: {}", let_kw, is_mut, name, ty)
856 Either::Right(_) => format!("{}self: {}", is_mut, ty),
858 hover_markup(None, desc, None)
861 fn hover_for_keyword(
862 sema: &Semantics<RootDatabase>,
863 config: &HoverConfig,
865 ) -> Option<RangeInfo<HoverResult>> {
866 if !token.kind().is_keyword() || !config.documentation.is_some() {
869 let famous_defs = FamousDefs(sema, sema.scope(&token.parent()?).krate());
870 // std exposes {}_keyword modules with docstrings on the root to document keywords
871 let keyword_mod = format!("{}_keyword", token.text());
872 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?;
873 let docs = doc_owner.attrs(sema.db).docs()?;
874 let markup = process_markup(
876 Definition::ModuleDef(doc_owner.into()),
877 &hover_markup(Some(docs.into()), token.text().into(), None)?,
880 Some(RangeInfo::new(token.text_range(), HoverResult { markup, actions: Default::default() }))
883 fn hover_for_builtin(famous_defs: &FamousDefs, builtin: hir::BuiltinType) -> Option<Markup> {
884 // std exposes prim_{} modules with docstrings on the root to document the builtins
885 let primitive_mod = format!("prim_{}", builtin.name());
886 let doc_owner = find_std_module(famous_defs, &primitive_mod)?;
887 let docs = doc_owner.attrs(famous_defs.0.db).docs()?;
888 hover_markup(Some(docs.into()), builtin.name().to_string(), None)
891 fn find_std_module(famous_defs: &FamousDefs, name: &str) -> Option<hir::Module> {
892 let db = famous_defs.0.db;
893 let std_crate = famous_defs.std()?;
894 let std_root_module = std_crate.root_module(db);
897 .find(|module| module.name(db).map_or(false, |module| module.to_string() == name))
902 use expect_test::{expect, Expect};
903 use ide_db::base_db::{FileLoader, FileRange};
904 use syntax::TextRange;
906 use crate::{fixture, hover::HoverDocFormat, HoverConfig};
908 fn check_hover_no_result(ra_fixture: &str) {
909 let (analysis, position) = fixture::position(ra_fixture);
913 links_in_hover: true,
914 documentation: Some(HoverDocFormat::Markdown),
916 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
919 assert!(hover.is_none(), "hover not expected but found: {:?}", hover.unwrap());
922 fn check(ra_fixture: &str, expect: Expect) {
923 let (analysis, position) = fixture::position(ra_fixture);
927 links_in_hover: true,
928 documentation: Some(HoverDocFormat::Markdown),
930 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
935 let content = analysis.db.file_text(position.file_id);
936 let hovered_element = &content[hover.range];
938 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
939 expect.assert_eq(&actual)
942 fn check_hover_no_links(ra_fixture: &str, expect: Expect) {
943 let (analysis, position) = fixture::position(ra_fixture);
947 links_in_hover: false,
948 documentation: Some(HoverDocFormat::Markdown),
950 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
955 let content = analysis.db.file_text(position.file_id);
956 let hovered_element = &content[hover.range];
958 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
959 expect.assert_eq(&actual)
962 fn check_hover_no_markdown(ra_fixture: &str, expect: Expect) {
963 let (analysis, position) = fixture::position(ra_fixture);
967 links_in_hover: true,
968 documentation: Some(HoverDocFormat::PlainText),
970 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
975 let content = analysis.db.file_text(position.file_id);
976 let hovered_element = &content[hover.range];
978 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
979 expect.assert_eq(&actual)
982 fn check_actions(ra_fixture: &str, expect: Expect) {
983 let (analysis, file_id, position) = fixture::range_or_position(ra_fixture);
987 links_in_hover: true,
988 documentation: Some(HoverDocFormat::Markdown),
990 FileRange { file_id, range: position.range_or_empty() },
994 expect.assert_debug_eq(&hover.info.actions)
997 fn check_hover_range(ra_fixture: &str, expect: Expect) {
998 let (analysis, range) = fixture::range(ra_fixture);
1002 links_in_hover: false,
1003 documentation: Some(HoverDocFormat::Markdown),
1009 expect.assert_eq(hover.info.markup.as_str())
1012 fn check_hover_range_no_results(ra_fixture: &str) {
1013 let (analysis, range) = fixture::range(ra_fixture);
1014 let hover = analysis
1017 links_in_hover: false,
1018 documentation: Some(HoverDocFormat::Markdown),
1023 assert!(hover.is_none());
1027 fn hover_descend_macros_avoids_duplicates() {
1030 macro_rules! dupe_use {
1054 fn hover_shows_all_macro_descends() {
1103 fn hover_shows_type_of_an_expression() {
1106 pub fn foo() -> u32 { 1 }
1109 let foo_test = foo()$0;
1122 fn hover_remove_markdown_if_configured() {
1123 check_hover_no_markdown(
1125 pub fn foo() -> u32 { 1 }
1128 let foo_test = foo()$0;
1139 fn hover_shows_long_type_of_an_expression() {
1142 struct Scan<A, B, C> { a: A, b: B, c: C }
1143 struct Iter<I> { inner: I }
1144 enum Option<T> { Some(T), None }
1146 struct OtherStruct<T> { i: T }
1148 fn scan<A, B, C>(a: A, b: B, c: C) -> Iter<Scan<OtherStruct<A>, B, C>> {
1149 Iter { inner: Scan { a, b, c } }
1154 let closure = |memo: &mut u32, value: &u32, _another: &mut u32| -> Option<u32> {
1155 Option::Some(*memo + value)
1158 let mut iter$0 = scan(OtherStruct { i: num }, closure, number);
1165 let mut iter: Iter<Scan<OtherStruct<OtherStruct<i32>>, |&mut u32, &u32, &mut u32| -> Option<u32>, u32>>
1172 fn hover_shows_fn_signature() {
1173 // Single file with result
1176 pub fn foo() -> u32 { 1 }
1178 fn main() { let foo_test = fo$0o(); }
1193 // Multiple candidates but results are ambiguous.
1197 pub fn foo() -> u32 { 1 }
1200 pub fn foo() -> &str { "" }
1203 pub fn foo(a: u32, b: u32) {}
1210 fn main() { let foo_test = fo$0o(); }
1220 // Use literal `crate` in path
1225 fn foo() -> crate::X { X }
1227 fn main() { f$0oo(); }
1237 fn foo() -> crate::X
1242 // Check `super` in path
1247 mod m { pub fn foo() -> super::X { super::X } }
1249 fn main() { m::f$0oo(); }
1259 pub fn foo() -> super::X
1266 fn hover_shows_fn_signature_with_type_params() {
1269 pub fn foo<'a, T: AsRef<str>>(b: &'a T) -> &'a str { }
1271 fn main() { let foo_test = fo$0o(); }
1281 pub fn foo<'a, T>(b: &'a T) -> &'a str
1290 fn hover_shows_fn_signature_on_fn_name() {
1293 pub fn foo$0(a: u32, b: u32) -> u32 {}
1305 pub fn foo(a: u32, b: u32) -> u32
1312 fn hover_shows_fn_doc() {
1317 /// # use std::path::Path;
1319 /// foo(Path::new("hello, world!"))
1321 pub fn foo$0(_: &Path) {}
1333 pub fn foo(_: &Path)
1341 # use std::path::Path;
1343 foo(Path::new("hello, world!"))
1350 fn hover_shows_fn_doc_attr_raw_string() {
1353 #[doc = r#"Raw string doc attr"#]
1354 pub fn foo$0(_: &Path) {}
1366 pub fn foo(_: &Path)
1377 fn hover_shows_struct_field_info() {
1378 // Hovering over the field when instantiating
1381 struct Foo { field_a: u32 }
1384 let foo = Foo { field_a$0: 0, };
1400 // Hovering over the field in the definition
1403 struct Foo { field_a$0: u32 }
1406 let foo = Foo { field_a: 0 };
1424 fn hover_const_static() {
1426 r#"const foo$0: u32 = 123;"#,
1440 r#"static foo$0: u32 = 456;"#,
1456 fn hover_default_generic_types() {
1459 struct Test<K, T = u8> { k: K, t: T }
1462 let zz$0 = Test { t: 23u8, k: 33 };
1468 let zz: Test<i32, u8>
1478 enum Option<T> { Some(T) }
1481 fn main() { So$0me(12); }
1498 enum Option<T> { Some(T) }
1501 fn main() { let b$0ar = Some(12); }
1507 let bar: Option<i32>
1514 fn hover_enum_variant() {
1518 /// The None variant
1542 /// The Some variant
1546 let s = Option::Som$0e(12);
1568 fn hover_for_local_variable() {
1570 r#"fn func(foo: i32) { fo$0o; }"#,
1582 fn hover_for_local_variable_pat() {
1584 r#"fn func(fo$0o: i32) {}"#,
1596 fn hover_local_var_edge() {
1598 r#"fn func(foo: i32) { if true { $0foo; }; }"#,
1610 fn hover_for_param_edge() {
1612 r#"fn func($0foo: i32) {}"#,
1624 fn hover_for_param_with_multiple_traits() {
1629 type Target: ?Sized;
1632 type Target: ?Sized;
1634 fn f(_x$0: impl Deref<Target=u8> + DerefMut<Target=u8>) {}"#,
1639 _x: impl Deref<Target = u8> + DerefMut<Target = u8>
1646 fn test_hover_infer_associated_method_result() {
1649 struct Thing { x: u32 }
1652 fn new() -> Thing { Thing { x: 0 } }
1655 fn main() { let foo_$0test = Thing::new(); }
1668 fn test_hover_infer_associated_method_exact() {
1672 struct Thing { x: u32 }
1675 fn new() -> Thing { Thing { x: 0 } }
1679 fn main() { let foo_test = wrapper::Thing::new$0(); }
1685 test::wrapper::Thing
1696 fn test_hover_infer_associated_const_in_pattern() {
1727 fn test_hover_self() {
1730 struct Thing { x: u32 }
1732 fn new() -> Self { Self$0 { x: 0 } }
1749 struct Thing { x: u32 }
1751 fn new() -> Self$0 { Self { x: 0 } }
1770 pub fn new() -> Self$0 { Thing::A }
1789 pub fn thing(a: Self$0) {}
1807 fn test_hover_shadowing_pat() {
1828 fn test_hover_macro_invocation() {
1831 macro_rules! foo { () => {} }
1833 fn f() { fo$0o!(); }
1850 fn test_hover_macro2_invocation() {
1858 fn f() { fo$0o!(); }
1881 fn test_hover_tuple_field() {
1883 r#"struct TS(String, i32$0);"#,
1895 fn test_hover_through_macro() {
1898 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1901 fn bar() { fo$0o(); }
1919 fn test_hover_through_attr() {
1922 //- proc_macros: identity
1923 #[proc_macros::identity]
1941 fn test_hover_through_expr_in_macro() {
1944 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1945 fn foo(bar:u32) { let a = id!(ba$0r); }
1958 fn test_hover_through_expr_in_macro_recursive() {
1961 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1962 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1963 fn foo(bar:u32) { let a = id!(ba$0r); }
1976 fn test_hover_through_func_in_macro_recursive() {
1979 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1980 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1981 fn bar() -> u32 { 0 }
1982 fn foo() { let a = id!([0u32, bar($0)] ); }
1994 fn test_hover_through_literal_string_in_macro() {
1997 macro_rules! arr { ($($tt:tt)*) => { [$($tt)*)] } }
1999 let mastered_for_itunes = "";
2000 let _ = arr!("Tr$0acks", &mastered_for_itunes);
2013 fn test_hover_through_assert_macro() {
2016 #[rustc_builtin_macro]
2017 macro_rules! assert {}
2019 fn bar() -> bool { true }
2039 fn test_hover_through_literal_string_in_builtin_macro() {
2040 check_hover_no_result(
2042 #[rustc_builtin_macro]
2043 macro_rules! format {}
2046 format!("hel$0lo {}", 0);
2053 fn test_hover_non_ascii_space_doc() {
2056 /// <- `\u{3000}` here
2059 fn bar() { fo$0o(); }
2080 fn test_hover_function_show_qualifiers() {
2082 r#"async fn foo$0() {}"#,
2096 r#"pub const unsafe fn foo$0() {}"#,
2105 pub const unsafe fn foo()
2109 // Top level `pub(crate)` will be displayed as no visibility.
2111 r#"mod m { pub(crate) async unsafe extern "C" fn foo$0() {} }"#,
2120 pub(crate) async unsafe extern "C" fn foo()
2127 fn test_hover_trait_show_qualifiers() {
2129 r"unsafe trait foo$0() {}",
2146 fn test_hover_extern_crate() {
2149 //- /main.rs crate:main deps:std
2151 //- /std/lib.rs crate:std
2152 //! Standard library for this test
2166 Standard library for this test
2174 //- /main.rs crate:main deps:std
2175 extern crate std as ab$0c;
2176 //- /std/lib.rs crate:std
2177 //! Standard library for this test
2191 Standard library for this test
2200 fn test_hover_mod_with_same_name_as_function() {
2203 use self::m$0y::Bar;
2204 mod my { pub struct Bar; }
2223 fn test_hover_struct_doc_comment() {
2226 /// This is an example
2234 /// assert_eq!(6, my_crate::add_one(5));
2238 fn foo() { let bar = Ba$0r; }
2261 assert_eq!(6, my_crate::add_one(5));
2268 fn test_hover_struct_doc_attr() {
2274 fn foo() { let bar = Ba$0r; }
2295 fn test_hover_struct_doc_attr_multiple_and_mixed() {
2299 #[doc = "bar docs 1"]
2300 #[doc = "bar docs 2"]
2303 fn foo() { let bar = Ba$0r; }
2326 fn test_hover_external_url() {
2330 /// [external](https://www.google.com)
2346 [external](https://www.google.com)
2351 // Check that we don't rewrite links which we can't identify
2353 fn test_hover_unknown_target() {
2379 fn test_hover_no_links() {
2380 check_hover_no_links(
2383 /// case 1. bare URL: https://www.example.com/
2384 /// case 2. inline URL with title: [example](https://www.example.com/)
2385 /// case 3. code reference: [`Result`]
2386 /// case 4. code reference but miss footnote: [`String`]
2387 /// case 5. autolink: <http://www.example.com/>
2388 /// case 6. email address: <test@example.com>
2389 /// case 7. reference: [example][example]
2390 /// case 8. collapsed link: [example][]
2391 /// case 9. shortcut link: [example]
2392 /// case 10. inline without URL: [example]()
2393 /// case 11. reference: [foo][foo]
2394 /// case 12. reference: [foo][bar]
2395 /// case 13. collapsed link: [foo][]
2396 /// case 14. shortcut link: [foo]
2397 /// case 15. inline without URL: [foo]()
2398 /// case 16. just escaped text: \[foo]
2399 /// case 17. inline link: [Foo](foo::Foo)
2401 /// [`Result`]: ../../std/result/enum.Result.html
2402 /// [^example]: https://www.example.com/
2419 case 1. bare URL: https://www.example.com/
2420 case 2. inline URL with title: [example](https://www.example.com/)
2421 case 3. code reference: `Result`
2422 case 4. code reference but miss footnote: `String`
2423 case 5. autolink: http://www.example.com/
2424 case 6. email address: test@example.com
2425 case 7. reference: example
2426 case 8. collapsed link: example
2427 case 9. shortcut link: example
2428 case 10. inline without URL: example
2429 case 11. reference: foo
2430 case 12. reference: foo
2431 case 13. collapsed link: foo
2432 case 14. shortcut link: foo
2433 case 15. inline without URL: foo
2434 case 16. just escaped text: \[foo\]
2435 case 17. inline link: Foo
2437 [^example]: https://www.example.com/
2443 fn test_hover_macro_generated_struct_fn_doc_comment() {
2444 cov_mark::check!(hover_macro_generated_struct_fn_doc_comment);
2460 fn foo() { let bar = Bar; bar.fo$0o(); }
2481 fn test_hover_macro_generated_struct_fn_doc_attr() {
2482 cov_mark::check!(hover_macro_generated_struct_fn_doc_attr);
2490 #[doc = "Do the foo"]
2498 fn foo() { let bar = Bar; bar.fo$0o(); }
2519 fn test_hover_trait_has_impl_action() {
2521 r#"trait foo$0() {}"#,
2538 fn test_hover_struct_has_impl_action() {
2540 r"struct foo$0() {}",
2557 fn test_hover_union_has_impl_action() {
2559 r#"union foo$0() {}"#,
2576 fn test_hover_enum_has_impl_action() {
2578 r"enum foo$0() { A, B }",
2595 fn test_hover_self_has_impl_action() {
2597 r#"struct foo where Self$0:;"#,
2614 fn test_hover_test_has_action() {
2632 use_name_in_title: false,
2633 nav: NavigationTarget {
2638 focus_range: 11..19,
2659 fn test_hover_test_mod_has_action() {
2671 use_name_in_title: false,
2672 nav: NavigationTarget {
2680 description: "mod tests",
2694 fn test_hover_struct_has_goto_type_action() {
2699 fn main() { let s$0t = S{ f1:0 }; }
2706 mod_path: "test::S",
2707 nav: NavigationTarget {
2715 description: "struct S",
2726 fn test_hover_generic_struct_has_goto_type_actions() {
2730 struct S<T>{ f1: T }
2732 fn main() { let s$0t = S{ f1:Arg(0) }; }
2739 mod_path: "test::S",
2740 nav: NavigationTarget {
2745 focus_range: 24..25,
2748 description: "struct S<T>",
2752 mod_path: "test::Arg",
2753 nav: NavigationTarget {
2761 description: "struct Arg",
2772 fn test_hover_generic_struct_has_flattened_goto_type_actions() {
2776 struct S<T>{ f1: T }
2778 fn main() { let s$0t = S{ f1: S{ f1: Arg(0) } }; }
2785 mod_path: "test::S",
2786 nav: NavigationTarget {
2791 focus_range: 24..25,
2794 description: "struct S<T>",
2798 mod_path: "test::Arg",
2799 nav: NavigationTarget {
2807 description: "struct Arg",
2818 fn test_hover_tuple_has_goto_type_actions() {
2827 fn main() { let s$0t = (A(1), B(2), M::C(3) ); }
2834 mod_path: "test::A",
2835 nav: NavigationTarget {
2843 description: "struct A",
2847 mod_path: "test::B",
2848 nav: NavigationTarget {
2853 focus_range: 22..23,
2856 description: "struct B",
2860 mod_path: "test::M::C",
2861 nav: NavigationTarget {
2866 focus_range: 53..54,
2869 description: "pub struct C",
2880 fn test_hover_return_impl_trait_has_goto_type_action() {
2884 fn foo() -> impl Foo {}
2886 fn main() { let s$0t = foo(); }
2893 mod_path: "test::Foo",
2894 nav: NavigationTarget {
2902 description: "trait Foo",
2913 fn test_hover_generic_return_impl_trait_has_goto_type_action() {
2918 fn foo() -> impl Foo<S> {}
2920 fn main() { let s$0t = foo(); }
2927 mod_path: "test::Foo",
2928 nav: NavigationTarget {
2936 description: "trait Foo<T>",
2940 mod_path: "test::S",
2941 nav: NavigationTarget {
2946 focus_range: 23..24,
2949 description: "struct S",
2960 fn test_hover_return_impl_traits_has_goto_type_action() {
2965 fn foo() -> impl Foo + Bar {}
2967 fn main() { let s$0t = foo(); }
2974 mod_path: "test::Foo",
2975 nav: NavigationTarget {
2983 description: "trait Foo",
2987 mod_path: "test::Bar",
2988 nav: NavigationTarget {
2993 focus_range: 19..22,
2996 description: "trait Bar",
3007 fn test_hover_generic_return_impl_traits_has_goto_type_action() {
3015 fn foo() -> impl Foo<S1> + Bar<S2> {}
3017 fn main() { let s$0t = foo(); }
3024 mod_path: "test::Foo",
3025 nav: NavigationTarget {
3033 description: "trait Foo<T>",
3037 mod_path: "test::Bar",
3038 nav: NavigationTarget {
3043 focus_range: 22..25,
3046 description: "trait Bar<T>",
3050 mod_path: "test::S1",
3051 nav: NavigationTarget {
3056 focus_range: 39..41,
3059 description: "struct S1",
3063 mod_path: "test::S2",
3064 nav: NavigationTarget {
3069 focus_range: 52..54,
3072 description: "struct S2",
3083 fn test_hover_arg_impl_trait_has_goto_type_action() {
3087 fn foo(ar$0g: &impl Foo) {}
3094 mod_path: "test::Foo",
3095 nav: NavigationTarget {
3103 description: "trait Foo",
3114 fn test_hover_arg_impl_traits_has_goto_type_action() {
3121 fn foo(ar$0g: &impl Foo + Bar<S>) {}
3128 mod_path: "test::Foo",
3129 nav: NavigationTarget {
3137 description: "trait Foo",
3141 mod_path: "test::Bar",
3142 nav: NavigationTarget {
3147 focus_range: 19..22,
3150 description: "trait Bar<T>",
3154 mod_path: "test::S",
3155 nav: NavigationTarget {
3160 focus_range: 36..37,
3163 description: "struct S",
3174 fn test_hover_async_block_impl_trait_has_goto_type_action() {
3177 //- minicore: future
3180 let fo$0o = async { S };
3188 mod_path: "core::future::Future",
3189 nav: NavigationTarget {
3193 full_range: 254..436,
3194 focus_range: 293..299,
3197 description: "pub trait Future",
3201 mod_path: "test::S",
3202 nav: NavigationTarget {
3210 description: "struct S",
3221 fn test_hover_arg_generic_impl_trait_has_goto_type_action() {
3226 fn foo(ar$0g: &impl Foo<S>) {}
3233 mod_path: "test::Foo",
3234 nav: NavigationTarget {
3242 description: "trait Foo<T>",
3246 mod_path: "test::S",
3247 nav: NavigationTarget {
3252 focus_range: 23..24,
3255 description: "struct S",
3266 fn test_hover_dyn_return_has_goto_type_action() {
3274 fn foo() -> B<dyn Foo> {}
3276 fn main() { let s$0t = foo(); }
3283 mod_path: "test::B",
3284 nav: NavigationTarget {
3289 focus_range: 49..50,
3292 description: "struct B<T>",
3296 mod_path: "test::Foo",
3297 nav: NavigationTarget {
3305 description: "trait Foo",
3316 fn test_hover_dyn_arg_has_goto_type_action() {
3320 fn foo(ar$0g: &dyn Foo) {}
3327 mod_path: "test::Foo",
3328 nav: NavigationTarget {
3336 description: "trait Foo",
3347 fn test_hover_generic_dyn_arg_has_goto_type_action() {
3352 fn foo(ar$0g: &dyn Foo<S>) {}
3359 mod_path: "test::Foo",
3360 nav: NavigationTarget {
3368 description: "trait Foo<T>",
3372 mod_path: "test::S",
3373 nav: NavigationTarget {
3378 focus_range: 23..24,
3381 description: "struct S",
3392 fn test_hover_goto_type_action_links_order() {
3395 trait ImplTrait<T> {}
3396 trait DynTrait<T> {}
3400 fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
3407 mod_path: "test::ImplTrait",
3408 nav: NavigationTarget {
3416 description: "trait ImplTrait<T>",
3420 mod_path: "test::B",
3421 nav: NavigationTarget {
3426 focus_range: 50..51,
3429 description: "struct B<T>",
3433 mod_path: "test::DynTrait",
3434 nav: NavigationTarget {
3439 focus_range: 28..36,
3442 description: "trait DynTrait<T>",
3446 mod_path: "test::S",
3447 nav: NavigationTarget {
3452 focus_range: 65..66,
3455 description: "struct S",
3466 fn test_hover_associated_type_has_goto_type_action() {
3471 fn get(self) -> Self::Item {}
3477 impl Foo for S { type Item = Bar; }
3479 fn test() -> impl Foo { S {} }
3481 fn main() { let s$0t = test().get(); }
3488 mod_path: "test::Foo",
3489 nav: NavigationTarget {
3497 description: "trait Foo",
3508 fn test_hover_const_param_has_goto_type_action() {
3512 struct Foo<const BAR: Bar>;
3514 impl<const BAR: Bar> Foo<BAR$0> {}
3521 mod_path: "test::Bar",
3522 nav: NavigationTarget {
3530 description: "struct Bar",
3541 fn test_hover_type_param_has_goto_type_action() {
3546 fn foo<T: Foo>(t: T$0){}
3553 mod_path: "test::Foo",
3554 nav: NavigationTarget {
3562 description: "trait Foo",
3573 fn test_hover_self_has_go_to_type() {
3586 mod_path: "test::Foo",
3587 nav: NavigationTarget {
3595 description: "struct Foo",
3606 fn hover_displays_normalized_crate_names() {
3609 //- /lib.rs crate:name-with-dashes
3611 pub struct Thing { x: u32 }
3614 pub fn new() -> Thing { Thing { x: 0 } }
3618 //- /main.rs crate:main deps:name-with-dashes
3619 fn main() { let foo_test = name_with_dashes::wrapper::Thing::new$0(); }
3625 name_with_dashes::wrapper::Thing
3629 pub fn new() -> Thing
3636 fn hover_field_pat_shorthand_ref_match_ergonomics() {
3659 fn hover_self_param_shows_type() {
3678 fn hover_self_param_shows_type_for_arbitrary_self_type() {
3684 fn bar(sel$0f: Arc<Foo>) {}
3698 fn hover_doc_outer_inner() {
3705 /// This comment belongs to the function
3729 fn hover_doc_outer_inner_attribue() {
3732 #[doc = "Be quick;"]
3734 #![doc = "time is mana"]
3736 #[doc = "This comment belongs to the function"]
3760 fn hover_doc_block_style_indentend() {
3794 fn hover_comments_dont_highlight_parent() {
3795 cov_mark::check!(no_highlight_on_comment_hover);
3796 check_hover_no_result(
3824 fn hover_lifetime() {
3826 r#"fn foo<'lifetime>(_: &'lifetime$0 ()) {}"#,
3838 fn hover_type_param() {
3845 impl<T: TraitA + TraitB> Foo<T$0> where T: Sized {}
3869 // lifetimes bounds arent being tracked yet
3874 impl<T: 'static> Foo<T$0> {}
3887 fn hover_type_param_sized_bounds() {
3888 // implicit `: Sized` bound
3894 impl<T: Trait> Foo<T$0> {}
3909 impl<T: Trait + ?Sized> Foo<T$0> {}
3921 mod type_param_sized_bounds {
3925 fn single_implicit() {
3942 fn single_explicit() {
3946 fn foo<T$0: Sized>() {}
3959 fn single_relaxed() {
3963 fn foo<T$0: ?Sized>() {}
3976 fn multiple_implicit() {
3981 fn foo<T$0: Trait>() {}
3994 fn multiple_explicit() {
3999 fn foo<T$0: Trait + Sized>() {}
4012 fn multiple_relaxed() {
4017 fn foo<T$0: Trait + ?Sized>() {}
4034 fn foo<T$0: ?Sized + Sized + Sized>() {}
4048 fn foo<T$0: Sized + ?Sized + Sized + Trait>() {}
4062 fn hover_const_param() {
4065 struct Foo<const LEN: usize>;
4066 impl<const LEN: usize> Foo<LEN$0> {}
4079 fn hover_const_pat() {
4083 const FOO: usize = 3;
4110 fn hover_mod_def() {
4137 fn hover_self_in_use() {
4140 //! This should not appear
4142 /// But this should appear
4145 use foo::bar::{self$0};
4160 But this should appear
4166 fn hover_keyword() {
4169 //- /main.rs crate:main deps:std
4170 fn f() { retur$0n; }
4171 //- /libstd.rs crate:std
4172 /// Docs for return_keyword
4173 mod return_keyword {}
4184 Docs for return_keyword
4190 fn hover_builtin() {
4193 //- /main.rs crate:main deps:std
4194 cosnt _: &str$0 = ""; }
4196 //- /libstd.rs crate:std
4197 /// Docs for prim_str
4215 fn hover_macro_expanded_function() {
4218 struct S<'a, T>(&'a T);
4222 fn bar<'t, T: Clone + 't>(s: &mut S<'t, T>, t: u32) -> *mut u32 where
4224 for<'a> T: Clone + 'a
4243 fn bar<'t, T>(s: &mut S<'t, T>, t: u32) -> *mut u32
4247 for<'a> T: Clone + 'a,
4254 fn hover_intra_doc_links() {
4259 /// This is the item. Cool!
4263 /// Gives you a [`TheItem$0`].
4265 /// [`TheItem`]: theitem::TheItem
4266 pub fn gimme() -> theitem::TheItem {
4283 This is the item. Cool!
4289 fn hover_generic_assoc() {
4292 fn foo<T: A>() where T::Assoc$0: {}
4312 let _: <T>::Assoc$0;
4352 fn string_shadowed_with_inner_items() {
4355 //- /main.rs crate:main deps:alloc
4357 /// Custom `String` type.
4366 //- /alloc.rs crate:alloc
4371 /// This is `alloc::String`.
4388 Custom `String` type.
4394 fn function_doesnt_shadow_crate_in_use_tree() {
4397 //- /main.rs crate:main deps:foo
4400 //- /foo.rs crate:foo
4414 fn hover_feature() {
4416 r#"#![feature(box_syntax$0)]"#,
4426 The tracking issue for this feature is: [#49733]
4428 [#49733]: https://github.com/rust-lang/rust/issues/49733
4430 See also [`box_patterns`](box-patterns.md)
4432 ------------------------
4434 Currently the only stable way to create a `Box` is via the `Box::new` method.
4435 Also it is not possible in stable Rust to destructure a `Box` in a match
4436 pattern. The unstable `box` keyword can be used to create a `Box`. An example
4440 #![feature(box_syntax)]
4454 r#"#![allow(arithmetic_overflow$0)]"#,
4456 *arithmetic_overflow*
4462 arithmetic operation overflows
4468 fn hover_clippy_lint() {
4470 r#"#![allow(clippy::almost_swapped$0)]"#,
4474 clippy::almost_swapped
4478 Checks for `foo = bar; bar = foo` sequences.
4484 fn hover_attr_path_qualifier() {
4485 cov_mark::check!(name_ref_classify_attr_path_qualifier);
4488 //- /foo.rs crate:foo
4490 //- /lib.rs crate:main.rs deps:foo
4521 use bar::{self as foo$0};
4564 fn hover_derive_input() {
4567 #[rustc_builtin_macro]
4587 #[rustc_builtin_macro]
4590 #[derive(foo::Copy$0)]
4608 fn hover_range_math() {
4611 fn f() { let expr = $01 + 2 * 3$0 }
4621 fn f() { let expr = 1 $0+ 2 * $03 }
4631 fn f() { let expr = 1 + $02 * 3$0 }
4641 fn hover_range_arrays() {
4644 fn f() { let expr = $0[1, 2, 3, 4]$0 }
4654 fn f() { let expr = [1, 2, $03, 4]$0 }
4664 fn f() { let expr = [1, 2, $03$0, 4] }
4674 fn hover_range_functions() {
4677 fn f<T>(a: &[T]) { }
4678 fn b() { $0f$0(&[1, 2, 3, 4, 5]); }
4688 fn f<T>(a: &[T]) { }
4689 fn b() { f($0&[1, 2, 3, 4, 5]$0); }
4699 fn hover_range_shows_nothing_when_invalid() {
4700 check_hover_range_no_results(
4702 fn f<T>(a: &[T]) { }
4703 fn b()$0 { f(&[1, 2, 3, 4, 5]); }$0
4707 check_hover_range_no_results(
4709 fn f<T>$0(a: &[T]) { }
4710 fn b() { f(&[1, 2, 3,$0 4, 5]); }
4714 check_hover_range_no_results(
4716 fn $0f() { let expr = [1, 2, 3, 4]$0 }
4722 fn hover_range_shows_unit_for_statements() {
4725 fn f<T>(a: &[T]) { }
4726 fn b() { $0f(&[1, 2, 3, 4, 5]); }$0
4736 fn f() { let expr$0 = $0[1, 2, 3, 4] }
4746 fn hover_range_for_pat() {
4773 fn hover_range_shows_coercions_if_applicable_expr() {
4777 let x: &u32 = $0&&&&&0$0;
4790 let x: *const u32 = $0&0$0;
4796 Coerced to: *const u32
4803 fn hover_range_shows_type_actions() {
4808 let x: &Foo = $0&&&&&Foo$0;
4816 mod_path: "test::Foo",
4817 nav: NavigationTarget {
4825 description: "struct Foo",
4836 fn hover_try_expr_res() {
4842 fn foo() -> Result<(), FooError> {
4843 Ok($0Result::<(), FooError>::Ok(())?$0)
4857 fn foo() -> Result<(), FooError> {
4858 Ok($0Result::<(), BarError>::Ok(())?$0)
4863 Try Error Type: BarError
4864 Propagated as: FooError
4871 fn hover_try_expr() {
4874 struct NotResult<T, U>(T, U);
4878 fn foo() -> NotResult<(), Looooong> {
4879 $0NotResult((), Short)?$0;
4884 Try Target Type: NotResult<(), Short>
4885 Propagated as: NotResult<(), Looooong>
4891 struct NotResult<T, U>(T, U);
4895 fn foo() -> NotResult<(), Short> {
4896 $0NotResult((), Looooong)?$0;
4901 Try Target Type: NotResult<(), Looooong>
4902 Propagated as: NotResult<(), Short>
4909 fn hover_try_expr_option() {
4910 cov_mark::check!(hover_try_expr_opt_opt);
4913 //- minicore: option, try
4915 fn foo() -> Option<()> {
4922 <Option<i32> as Try>::Output
4928 fn hover_deref_expr() {
4932 use core::ops::Deref;
4934 struct DerefExample<T> {
4938 impl<T> Deref for DerefExample<T> {
4941 fn deref(&self) -> &Self::Target {
4947 let x = DerefExample { value: 0 };
4948 let y: i32 = $0*x$0;
4953 Dereferenced from: DerefExample<i32>
4961 fn hover_deref_expr_with_coercion() {
4965 use core::ops::Deref;
4967 struct DerefExample<T> {
4971 impl<T> Deref for DerefExample<T> {
4974 fn deref(&self) -> &Self::Target {
4980 let x = DerefExample { value: &&&&&0 };
4981 let y: &i32 = $0*x$0;
4986 Dereferenced from: DerefExample<&&&&&i32>