1 use std::{collections::HashSet, ops::ControlFlow};
4 use hir::{AsAssocItem, HasAttrs, HasSource, HirDisplay, Semantics, TypeInfo};
6 base_db::{FileRange, SourceDatabase},
9 generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES},
10 pick_best_token, 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 original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
111 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] => 3,
112 T!['('] | T![')'] => 2,
113 kind if kind.is_trivia() => 0,
117 let mut seen = HashSet::default();
119 let mut fallback = None;
120 // attributes, require special machinery as they are mere ident tokens
122 let descend_macros = sema.descend_into_macros_many(original_token.clone());
124 for token in &descend_macros {
125 if token.kind() != COMMENT {
126 if let Some(attr) = token.ancestors().find_map(ast::Attr::cast) {
128 if let Some(res) = try_hover_for_lint(&attr, &token) {
137 .filter_map(|token| match token.parent() {
139 match find_hover_result(
149 Some(res) => match res {
150 ControlFlow::Break(inner) => Some(inner),
151 ControlFlow::Continue(_) => {
152 if fallback.is_none() {
153 // FIXME we're only taking the first fallback into account that's not `None`
154 fallback = hover_for_keyword(&sema, config, &token)
155 .or(type_hover(&sema, config, &token));
165 // reduce all descends into a single `RangeInfo`
166 // that spans from the earliest start to the latest end (fishy/FIXME),
167 // concatenates all `Markup`s with `\n---\n`,
168 // and accumulates all actions into its `actions` vector.
169 .reduce(|mut acc, RangeInfo { range, mut info }| {
170 let start = acc.range.start().min(range.start());
171 let end = acc.range.end().max(range.end());
173 acc.range = TextRange::new(start, end);
174 acc.info.actions.append(&mut info.actions);
175 acc.info.markup = Markup::from(format!("{}\n---\n{}", acc.info.markup, info.markup));
181 fn find_hover_result(
182 sema: &Semantics<RootDatabase>,
185 config: &HoverConfig,
186 original_token: &SyntaxToken,
189 seen: &mut HashSet<Definition>,
190 ) -> Option<ControlFlow<RangeInfo<HoverResult>>> {
191 let mut range_override = None;
193 // intra-doc links and attributes are special cased
194 // so don't add them to the `seen` duplicate check
195 let mut add_to_seen_definitions = true;
197 let definition = Definition::from_node(sema, token).into_iter().next().or_else(|| {
199 // FIXME: move comment + attribute special cases somewhere else to simplify control flow,
200 // hopefully simplifying the return type of this function in the process
201 // (the `Break`/`Continue` distinction is needed to decide whether to use fallback hovers)
203 // FIXME: hovering the intra doc link to `Foo` not working:
209 if token.kind() == COMMENT {
210 add_to_seen_definitions = false;
211 cov_mark::hit!(no_highlight_on_comment_hover);
212 let (attributes, def) = doc_attributes(sema, node)?;
213 let (docs, doc_mapping) = attributes.docs_with_rangemap(sema.db)?;
214 let (idl_range, link, ns) = extract_definitions_from_docs(&docs).into_iter().find_map(
215 |(range, link, ns)| {
216 let mapped = doc_mapping.map(range)?;
217 (mapped.file_id == file_id.into() && mapped.value.contains(offset))
218 .then(|| (mapped.value, link, ns))
221 range_override = Some(idl_range);
222 Some(match resolve_doc_path_for_def(sema.db, def, &link, ns)? {
223 Either::Left(it) => Definition::ModuleDef(it),
224 Either::Right(it) => Definition::Macro(it),
231 if let Some(definition) = definition {
233 if seen.contains(&definition) {
236 if add_to_seen_definitions {
237 seen.insert(definition);
239 if let Some(res) = hover_for_definition(sema, file_id, definition, &node, config) {
240 let range = range_override.unwrap_or_else(|| original_token.text_range());
241 return Some(ControlFlow::Break(RangeInfo::new(range, res)));
245 Some(ControlFlow::Continue(()))
249 sema: &Semantics<RootDatabase>,
250 config: &HoverConfig,
252 ) -> Option<RangeInfo<HoverResult>> {
253 if token.kind() == COMMENT {
258 .take_while(|it| !ast::Item::can_cast(it.kind()))
259 .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
261 let expr_or_pat = match_ast! {
263 ast::Expr(it) => Either::Left(it),
264 ast::Pat(it) => Either::Right(it),
265 // If this node is a MACRO_CALL, it means that `descend_into_macros_many` failed to resolve.
266 // (e.g expanding a builtin macro). So we give up here.
267 ast::MacroCall(_it) => return None,
272 let res = hover_type_info(&sema, config, &expr_or_pat)?;
273 let range = sema.original_range(&node).range;
274 Some(RangeInfo::new(range, res))
279 range: syntax::TextRange,
280 sema: &Semantics<RootDatabase>,
281 config: &HoverConfig,
282 ) -> Option<RangeInfo<HoverResult>> {
283 let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
286 ast::Expr(expr) => Some(Either::Left(expr)),
287 ast::Pat(pat) => Some(Either::Right(pat)),
292 let res = match &expr_or_pat {
293 Either::Left(ast::Expr::TryExpr(try_expr)) => hover_try_expr(sema, config, try_expr),
294 Either::Left(ast::Expr::PrefixExpr(prefix_expr))
295 if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
297 hover_deref_expr(sema, config, prefix_expr)
301 let res = res.or_else(|| hover_type_info(sema, config, &expr_or_pat));
303 let range = match expr_or_pat {
304 Either::Left(it) => it.syntax().text_range(),
305 Either::Right(it) => it.syntax().text_range(),
307 RangeInfo::new(range, it)
312 sema: &Semantics<RootDatabase>,
313 config: &HoverConfig,
314 try_expr: &ast::TryExpr,
315 ) -> Option<HoverResult> {
316 let inner_ty = sema.type_of_expr(&try_expr.expr()?)?.original;
317 let mut ancestors = try_expr.syntax().ancestors();
318 let mut body_ty = loop {
319 let next = ancestors.next()?;
322 ast::Fn(fn_) => sema.to_def(&fn_)?.ret_type(sema.db),
323 ast::Item(__) => return None,
324 ast::ClosureExpr(closure) => sema.type_of_expr(&closure.body()?)?.original,
325 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
326 sema.type_of_expr(&effect.block_expr()?.into())?.original
335 if inner_ty == body_ty {
339 let mut inner_ty = inner_ty;
340 let mut s = "Try Target".to_owned();
342 let adts = inner_ty.as_adt().zip(body_ty.as_adt());
343 if let Some((hir::Adt::Enum(inner), hir::Adt::Enum(body))) = adts {
344 let famous_defs = FamousDefs(sema, sema.scope(&try_expr.syntax()).krate());
345 // special case for two options, there is no value in showing them
346 if let Some(option_enum) = famous_defs.core_option_Option() {
347 if inner == option_enum && body == option_enum {
348 cov_mark::hit!(hover_try_expr_opt_opt);
353 // special case two results to show the error variants only
354 if let Some(result_enum) = famous_defs.core_result_Result() {
355 if inner == result_enum && body == result_enum {
356 let error_type_args =
357 inner_ty.type_arguments().nth(1).zip(body_ty.type_arguments().nth(1));
358 if let Some((inner, body)) = error_type_args {
361 s = "Try Error".to_owned();
367 let mut res = HoverResult::default();
369 let mut targets: Vec<hir::ModuleDef> = Vec::new();
370 let mut push_new_def = |item: hir::ModuleDef| {
371 if !targets.contains(&item) {
375 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
376 walk_and_push_ty(sema.db, &body_ty, &mut push_new_def);
377 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
379 let inner_ty = inner_ty.display(sema.db).to_string();
380 let body_ty = body_ty.display(sema.db).to_string();
381 let ty_len_max = inner_ty.len().max(body_ty.len());
383 let l = "Propagated as: ".len() - " Type: ".len();
384 let static_text_len_diff = l as isize - s.len() as isize;
385 let tpad = static_text_len_diff.max(0) as usize;
386 let ppad = static_text_len_diff.min(0).abs() as usize;
388 res.markup = format!(
389 "{bt_start}{} Type: {:>pad0$}\nPropagated as: {:>pad1$}\n{bt_end}",
393 pad0 = ty_len_max + tpad,
394 pad1 = ty_len_max + ppad,
395 bt_start = if config.markdown() { "```text\n" } else { "" },
396 bt_end = if config.markdown() { "```\n" } else { "" }
403 sema: &Semantics<RootDatabase>,
404 config: &HoverConfig,
405 deref_expr: &ast::PrefixExpr,
406 ) -> Option<HoverResult> {
407 let inner_ty = sema.type_of_expr(&deref_expr.expr()?)?.original;
408 let TypeInfo { original, adjusted } =
409 sema.type_of_expr(&ast::Expr::from(deref_expr.clone()))?;
411 let mut res = HoverResult::default();
412 let mut targets: Vec<hir::ModuleDef> = Vec::new();
413 let mut push_new_def = |item: hir::ModuleDef| {
414 if !targets.contains(&item) {
418 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
419 walk_and_push_ty(sema.db, &original, &mut push_new_def);
421 res.markup = if let Some(adjusted_ty) = adjusted {
422 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
423 let original = original.display(sema.db).to_string();
424 let adjusted = adjusted_ty.display(sema.db).to_string();
425 let inner = inner_ty.display(sema.db).to_string();
426 let type_len = "To type: ".len();
427 let coerced_len = "Coerced to: ".len();
428 let deref_len = "Dereferenced from: ".len();
429 let max_len = (original.len() + type_len)
430 .max(adjusted.len() + coerced_len)
431 .max(inner.len() + deref_len);
433 "{bt_start}Dereferenced from: {:>ipad$}\nTo type: {:>apad$}\nCoerced to: {:>opad$}\n{bt_end}",
437 ipad = max_len - deref_len,
438 apad = max_len - type_len,
439 opad = max_len - coerced_len,
440 bt_start = if config.markdown() { "```text\n" } else { "" },
441 bt_end = if config.markdown() { "```\n" } else { "" }
445 let original = original.display(sema.db).to_string();
446 let inner = inner_ty.display(sema.db).to_string();
447 let type_len = "To type: ".len();
448 let deref_len = "Dereferenced from: ".len();
449 let max_len = (original.len() + type_len).max(inner.len() + deref_len);
451 "{bt_start}Dereferenced from: {:>ipad$}\nTo type: {:>apad$}\n{bt_end}",
454 ipad = max_len - deref_len,
455 apad = max_len - type_len,
456 bt_start = if config.markdown() { "```text\n" } else { "" },
457 bt_end = if config.markdown() { "```\n" } else { "" }
461 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
467 sema: &Semantics<RootDatabase>,
468 config: &HoverConfig,
469 expr_or_pat: &Either<ast::Expr, ast::Pat>,
470 ) -> Option<HoverResult> {
471 let TypeInfo { original, adjusted } = match expr_or_pat {
472 Either::Left(expr) => sema.type_of_expr(expr)?,
473 Either::Right(pat) => sema.type_of_pat(pat)?,
476 let mut res = HoverResult::default();
477 let mut targets: Vec<hir::ModuleDef> = Vec::new();
478 let mut push_new_def = |item: hir::ModuleDef| {
479 if !targets.contains(&item) {
483 walk_and_push_ty(sema.db, &original, &mut push_new_def);
485 res.markup = if let Some(adjusted_ty) = adjusted {
486 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
487 let original = original.display(sema.db).to_string();
488 let adjusted = adjusted_ty.display(sema.db).to_string();
489 let static_text_diff_len = "Coerced to: ".len() - "Type: ".len();
491 "{bt_start}Type: {:>apad$}\nCoerced to: {:>opad$}\n{bt_end}",
494 apad = static_text_diff_len + adjusted.len().max(original.len()),
495 opad = original.len(),
496 bt_start = if config.markdown() { "```text\n" } else { "" },
497 bt_end = if config.markdown() { "```\n" } else { "" }
501 if config.markdown() {
502 Markup::fenced_block(&original.display(sema.db))
504 original.display(sema.db).to_string().into()
507 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
511 fn try_hover_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option<RangeInfo<HoverResult>> {
512 let (path, tt) = attr.as_simple_call()?;
513 if !tt.syntax().text_range().contains(token.text_range().start()) {
516 let (is_clippy, lints) = match &*path {
517 "feature" => (false, FEATURES),
518 "allow" | "deny" | "forbid" | "warn" => {
519 let is_clippy = algo::non_trivia_sibling(token.clone().into(), Direction::Prev)
520 .filter(|t| t.kind() == T![:])
521 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
522 .filter(|t| t.kind() == T![:])
523 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
525 t.kind() == T![ident] && t.into_token().map_or(false, |t| t.text() == "clippy")
530 (false, DEFAULT_LINTS)
537 let needle = if is_clippy {
538 tmp = format!("clippy::{}", token.text());
545 lints.binary_search_by_key(&needle, |lint| lint.label).ok().map(|idx| &lints[idx])?;
549 markup: Markup::from(format!("```\n{}\n```\n___\n\n{}", lint.label, lint.description)),
555 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
556 fn to_action(nav_target: NavigationTarget) -> HoverAction {
557 HoverAction::Implementation(FilePosition {
558 file_id: nav_target.file_id,
559 offset: nav_target.focus_or_full_range().start(),
563 let adt = match def {
564 Definition::ModuleDef(hir::ModuleDef::Trait(it)) => {
565 return it.try_to_nav(db).map(to_action)
567 Definition::ModuleDef(hir::ModuleDef::Adt(it)) => Some(it),
568 Definition::SelfType(it) => it.self_ty(db).as_adt(),
571 adt.try_to_nav(db).map(to_action)
574 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
576 Definition::ModuleDef(hir::ModuleDef::Function(it)) => {
577 it.try_to_nav(db).map(|nav_target| {
578 HoverAction::Reference(FilePosition {
579 file_id: nav_target.file_id,
580 offset: nav_target.focus_or_full_range().start(),
589 sema: &hir::Semantics<RootDatabase>,
592 ) -> Option<HoverAction> {
594 Definition::ModuleDef(it) => match it {
595 hir::ModuleDef::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
596 hir::ModuleDef::Function(func) => {
597 let src = func.source(sema.db)?;
598 if src.file_id != file_id.into() {
599 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
600 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
604 runnable_fn(sema, func).map(HoverAction::Runnable)
612 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
613 let mut targets: Vec<hir::ModuleDef> = Vec::new();
614 let mut push_new_def = |item: hir::ModuleDef| {
615 if !targets.contains(&item) {
620 if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
621 it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
624 Definition::Local(it) => it.ty(db),
625 Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
626 Definition::Field(field) => field.ty(db),
630 walk_and_push_ty(db, &ty, &mut push_new_def);
633 Some(HoverAction::goto_type_from_targets(db, targets))
639 push_new_def: &mut dyn FnMut(hir::ModuleDef),
642 if let Some(adt) = t.as_adt() {
643 push_new_def(adt.into());
644 } else if let Some(trait_) = t.as_dyn_trait() {
645 push_new_def(trait_.into());
646 } else if let Some(traits) = t.as_impl_traits(db) {
647 traits.into_iter().for_each(|it| push_new_def(it.into()));
648 } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
649 push_new_def(trait_.into());
654 fn hover_markup(docs: Option<String>, desc: String, mod_path: Option<String>) -> Option<Markup> {
655 let mut buf = String::new();
657 if let Some(mod_path) = mod_path {
658 if !mod_path.is_empty() {
659 format_to!(buf, "```rust\n{}\n```\n\n", mod_path);
662 format_to!(buf, "```rust\n{}\n```", desc);
664 if let Some(doc) = docs {
665 format_to!(buf, "\n___\n\n{}", doc);
674 config: &HoverConfig,
676 let markup = markup.as_str();
677 let markup = if !config.markdown() {
678 remove_markdown(markup)
679 } else if config.links_in_hover {
680 rewrite_links(db, markup, def)
687 fn definition_owner_name(db: &RootDatabase, def: &Definition) -> Option<String> {
689 Definition::Field(f) => Some(f.parent_def(db).name(db)),
690 Definition::Local(l) => l.parent(db).name(db),
691 Definition::ModuleDef(md) => match md {
692 hir::ModuleDef::Function(f) => match f.as_assoc_item(db)?.container(db) {
693 hir::AssocItemContainer::Trait(t) => Some(t.name(db)),
694 hir::AssocItemContainer::Impl(i) => i.self_ty(db).as_adt().map(|adt| adt.name(db)),
696 hir::ModuleDef::Variant(e) => Some(e.parent_enum(db).name(db)),
701 .map(|name| name.to_string())
704 fn render_path(db: &RootDatabase, module: hir::Module, item_name: Option<String>) -> String {
706 db.crate_graph()[module.krate().into()].display_name.as_ref().map(|it| it.to_string());
707 let module_path = module
711 .flat_map(|it| it.name(db).map(|name| name.to_string()));
712 crate_name.into_iter().chain(module_path).chain(item_name).join("::")
715 fn definition_mod_path(db: &RootDatabase, def: &Definition) -> Option<String> {
716 if let Definition::GenericParam(_) = def {
719 def.module(db).map(|module| render_path(db, module, definition_owner_name(db, def)))
722 pub(crate) fn hover_for_definition(
723 sema: &Semantics<RootDatabase>,
725 definition: Definition,
727 config: &HoverConfig,
728 ) -> Option<HoverResult> {
729 let famous_defs = match &definition {
730 Definition::ModuleDef(hir::ModuleDef::BuiltinType(_)) => {
731 Some(FamousDefs(&sema, sema.scope(&node).krate()))
735 if let Some(markup) = markup_for_definition(sema.db, definition, famous_defs.as_ref(), config) {
736 let mut res = HoverResult::default();
737 res.markup = process_markup(sema.db, definition, &markup, config);
738 if let Some(action) = show_implementations_action(sema.db, definition) {
739 res.actions.push(action);
742 if let Some(action) = show_fn_references_action(sema.db, definition) {
743 res.actions.push(action);
746 if let Some(action) = runnable_action(&sema, definition, file_id) {
747 res.actions.push(action);
750 if let Some(action) = goto_type_action_for_def(sema.db, definition) {
751 res.actions.push(action);
758 fn markup_for_definition(
761 famous_defs: Option<&FamousDefs>,
762 config: &HoverConfig,
763 ) -> Option<Markup> {
764 let mod_path = definition_mod_path(db, &def);
765 let (label, docs) = match def {
766 Definition::Macro(it) => (
767 match &it.source(db)?.value {
768 Either::Left(mac) => macro_label(mac),
769 Either::Right(mac_fn) => fn_as_proc_macro_label(mac_fn),
773 Definition::Field(def) => label_and_docs(db, def),
774 Definition::ModuleDef(it) => match it {
775 hir::ModuleDef::Module(it) => label_and_docs(db, it),
776 hir::ModuleDef::Function(it) => label_and_docs(db, it),
777 hir::ModuleDef::Adt(it) => label_and_docs(db, it),
778 hir::ModuleDef::Variant(it) => label_and_docs(db, it),
779 hir::ModuleDef::Const(it) => label_and_docs(db, it),
780 hir::ModuleDef::Static(it) => label_and_docs(db, it),
781 hir::ModuleDef::Trait(it) => label_and_docs(db, it),
782 hir::ModuleDef::TypeAlias(it) => label_and_docs(db, it),
783 hir::ModuleDef::BuiltinType(it) => {
785 .and_then(|fd| hover_for_builtin(fd, it))
786 .or_else(|| Some(Markup::fenced_block(&it.name())))
789 Definition::Local(it) => return hover_for_local(it, db),
790 Definition::SelfType(impl_def) => {
791 impl_def.self_ty(db).as_adt().map(|adt| label_and_docs(db, adt))?
793 Definition::GenericParam(it) => label_and_docs(db, it),
794 Definition::Label(it) => return Some(Markup::fenced_block(&it.name(db))),
798 docs.filter(|_| config.documentation.is_some()).map(Into::into),
803 fn label_and_docs<D>(db: &RootDatabase, def: D) -> (String, Option<hir::Documentation>)
805 D: HasAttrs + HirDisplay,
807 let label = def.display(db).to_string();
808 let docs = def.attrs(db).docs();
813 fn hover_for_local(it: hir::Local, db: &RootDatabase) -> Option<Markup> {
815 let ty = ty.display(db);
816 let is_mut = if it.is_mut(db) { "mut " } else { "" };
817 let desc = match it.source(db).value {
818 Either::Left(ident) => {
819 let name = it.name(db).unwrap();
820 let let_kw = if ident
823 .map_or(false, |p| p.kind() == LET_STMT || p.kind() == CONDITION)
829 format!("{}{}{}: {}", let_kw, is_mut, name, ty)
831 Either::Right(_) => format!("{}self: {}", is_mut, ty),
833 hover_markup(None, desc, None)
836 fn hover_for_keyword(
837 sema: &Semantics<RootDatabase>,
838 config: &HoverConfig,
840 ) -> Option<RangeInfo<HoverResult>> {
841 if !token.kind().is_keyword() || !config.documentation.is_some() {
844 let famous_defs = FamousDefs(sema, sema.scope(&token.parent()?).krate());
845 // std exposes {}_keyword modules with docstrings on the root to document keywords
846 let keyword_mod = format!("{}_keyword", token.text());
847 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?;
848 let docs = doc_owner.attrs(sema.db).docs()?;
849 let markup = process_markup(
851 Definition::ModuleDef(doc_owner.into()),
852 &hover_markup(Some(docs.into()), token.text().into(), None)?,
855 Some(RangeInfo::new(token.text_range(), HoverResult { markup, actions: Default::default() }))
858 fn hover_for_builtin(famous_defs: &FamousDefs, builtin: hir::BuiltinType) -> Option<Markup> {
859 // std exposes prim_{} modules with docstrings on the root to document the builtins
860 let primitive_mod = format!("prim_{}", builtin.name());
861 let doc_owner = find_std_module(famous_defs, &primitive_mod)?;
862 let docs = doc_owner.attrs(famous_defs.0.db).docs()?;
863 hover_markup(Some(docs.into()), builtin.name().to_string(), None)
866 fn find_std_module(famous_defs: &FamousDefs, name: &str) -> Option<hir::Module> {
867 let db = famous_defs.0.db;
868 let std_crate = famous_defs.std()?;
869 let std_root_module = std_crate.root_module(db);
872 .find(|module| module.name(db).map_or(false, |module| module.to_string() == name))
877 use expect_test::{expect, Expect};
878 use ide_db::base_db::{FileLoader, FileRange};
879 use syntax::TextRange;
881 use crate::{fixture, hover::HoverDocFormat, HoverConfig};
883 fn check_hover_no_result(ra_fixture: &str) {
884 let (analysis, position) = fixture::position(ra_fixture);
888 links_in_hover: true,
889 documentation: Some(HoverDocFormat::Markdown),
891 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
894 assert!(hover.is_none(), "hover not expected but found: {:?}", hover.unwrap());
897 fn check(ra_fixture: &str, expect: Expect) {
898 let (analysis, position) = fixture::position(ra_fixture);
902 links_in_hover: true,
903 documentation: Some(HoverDocFormat::Markdown),
905 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
910 let content = analysis.db.file_text(position.file_id);
911 let hovered_element = &content[hover.range];
913 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
914 expect.assert_eq(&actual)
917 fn check_hover_no_links(ra_fixture: &str, expect: Expect) {
918 let (analysis, position) = fixture::position(ra_fixture);
922 links_in_hover: false,
923 documentation: Some(HoverDocFormat::Markdown),
925 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
930 let content = analysis.db.file_text(position.file_id);
931 let hovered_element = &content[hover.range];
933 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
934 expect.assert_eq(&actual)
937 fn check_hover_no_markdown(ra_fixture: &str, expect: Expect) {
938 let (analysis, position) = fixture::position(ra_fixture);
942 links_in_hover: true,
943 documentation: Some(HoverDocFormat::PlainText),
945 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
950 let content = analysis.db.file_text(position.file_id);
951 let hovered_element = &content[hover.range];
953 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
954 expect.assert_eq(&actual)
957 fn check_actions(ra_fixture: &str, expect: Expect) {
958 let (analysis, file_id, position) = fixture::range_or_position(ra_fixture);
962 links_in_hover: true,
963 documentation: Some(HoverDocFormat::Markdown),
965 FileRange { file_id, range: position.range_or_empty() },
969 expect.assert_debug_eq(&hover.info.actions)
972 fn check_hover_range(ra_fixture: &str, expect: Expect) {
973 let (analysis, range) = fixture::range(ra_fixture);
977 links_in_hover: false,
978 documentation: Some(HoverDocFormat::Markdown),
984 expect.assert_eq(hover.info.markup.as_str())
987 fn check_hover_range_no_results(ra_fixture: &str) {
988 let (analysis, range) = fixture::range(ra_fixture);
992 links_in_hover: false,
993 documentation: Some(HoverDocFormat::Markdown),
998 assert!(hover.is_none());
1002 fn hover_descend_macros_avoids_duplicates() {
1005 macro_rules! dupe_use {
1029 fn hover_shows_all_macro_descends() {
1078 fn hover_shows_type_of_an_expression() {
1081 pub fn foo() -> u32 { 1 }
1084 let foo_test = foo()$0;
1097 fn hover_remove_markdown_if_configured() {
1098 check_hover_no_markdown(
1100 pub fn foo() -> u32 { 1 }
1103 let foo_test = foo()$0;
1114 fn hover_shows_long_type_of_an_expression() {
1117 struct Scan<A, B, C> { a: A, b: B, c: C }
1118 struct Iter<I> { inner: I }
1119 enum Option<T> { Some(T), None }
1121 struct OtherStruct<T> { i: T }
1123 fn scan<A, B, C>(a: A, b: B, c: C) -> Iter<Scan<OtherStruct<A>, B, C>> {
1124 Iter { inner: Scan { a, b, c } }
1129 let closure = |memo: &mut u32, value: &u32, _another: &mut u32| -> Option<u32> {
1130 Option::Some(*memo + value)
1133 let mut iter$0 = scan(OtherStruct { i: num }, closure, number);
1140 let mut iter: Iter<Scan<OtherStruct<OtherStruct<i32>>, |&mut u32, &u32, &mut u32| -> Option<u32>, u32>>
1147 fn hover_shows_fn_signature() {
1148 // Single file with result
1151 pub fn foo() -> u32 { 1 }
1153 fn main() { let foo_test = fo$0o(); }
1168 // Multiple candidates but results are ambiguous.
1172 pub fn foo() -> u32 { 1 }
1175 pub fn foo() -> &str { "" }
1178 pub fn foo(a: u32, b: u32) {}
1185 fn main() { let foo_test = fo$0o(); }
1195 // Use literal `crate` in path
1200 fn foo() -> crate::X { X }
1202 fn main() { f$0oo(); }
1212 fn foo() -> crate::X
1217 // Check `super` in path
1222 mod m { pub fn foo() -> super::X { super::X } }
1224 fn main() { m::f$0oo(); }
1234 pub fn foo() -> super::X
1241 fn hover_shows_fn_signature_with_type_params() {
1244 pub fn foo<'a, T: AsRef<str>>(b: &'a T) -> &'a str { }
1246 fn main() { let foo_test = fo$0o(); }
1256 pub fn foo<'a, T>(b: &'a T) -> &'a str
1265 fn hover_shows_fn_signature_on_fn_name() {
1268 pub fn foo$0(a: u32, b: u32) -> u32 {}
1280 pub fn foo(a: u32, b: u32) -> u32
1287 fn hover_shows_fn_doc() {
1292 /// # use std::path::Path;
1294 /// foo(Path::new("hello, world!"))
1296 pub fn foo$0(_: &Path) {}
1308 pub fn foo(_: &Path)
1316 # use std::path::Path;
1318 foo(Path::new("hello, world!"))
1325 fn hover_shows_fn_doc_attr_raw_string() {
1328 #[doc = r#"Raw string doc attr"#]
1329 pub fn foo$0(_: &Path) {}
1341 pub fn foo(_: &Path)
1352 fn hover_shows_struct_field_info() {
1353 // Hovering over the field when instantiating
1356 struct Foo { field_a: u32 }
1359 let foo = Foo { field_a$0: 0, };
1375 // Hovering over the field in the definition
1378 struct Foo { field_a$0: u32 }
1381 let foo = Foo { field_a: 0 };
1399 fn hover_const_static() {
1401 r#"const foo$0: u32 = 123;"#,
1415 r#"static foo$0: u32 = 456;"#,
1431 fn hover_default_generic_types() {
1434 struct Test<K, T = u8> { k: K, t: T }
1437 let zz$0 = Test { t: 23u8, k: 33 };
1443 let zz: Test<i32, u8>
1453 enum Option<T> { Some(T) }
1456 fn main() { So$0me(12); }
1473 enum Option<T> { Some(T) }
1476 fn main() { let b$0ar = Some(12); }
1482 let bar: Option<i32>
1489 fn hover_enum_variant() {
1493 /// The None variant
1517 /// The Some variant
1521 let s = Option::Som$0e(12);
1543 fn hover_for_local_variable() {
1545 r#"fn func(foo: i32) { fo$0o; }"#,
1557 fn hover_for_local_variable_pat() {
1559 r#"fn func(fo$0o: i32) {}"#,
1571 fn hover_local_var_edge() {
1573 r#"fn func(foo: i32) { if true { $0foo; }; }"#,
1585 fn hover_for_param_edge() {
1587 r#"fn func($0foo: i32) {}"#,
1599 fn hover_for_param_with_multiple_traits() {
1604 type Target: ?Sized;
1607 type Target: ?Sized;
1609 fn f(_x$0: impl Deref<Target=u8> + DerefMut<Target=u8>) {}"#,
1614 _x: impl Deref<Target = u8> + DerefMut<Target = u8>
1621 fn test_hover_infer_associated_method_result() {
1624 struct Thing { x: u32 }
1627 fn new() -> Thing { Thing { x: 0 } }
1630 fn main() { let foo_$0test = Thing::new(); }
1643 fn test_hover_infer_associated_method_exact() {
1647 struct Thing { x: u32 }
1650 fn new() -> Thing { Thing { x: 0 } }
1654 fn main() { let foo_test = wrapper::Thing::new$0(); }
1660 test::wrapper::Thing
1671 fn test_hover_infer_associated_const_in_pattern() {
1702 fn test_hover_self() {
1705 struct Thing { x: u32 }
1707 fn new() -> Self { Self$0 { x: 0 } }
1724 struct Thing { x: u32 }
1726 fn new() -> Self$0 { Self { x: 0 } }
1745 pub fn new() -> Self$0 { Thing::A }
1764 pub fn thing(a: Self$0) {}
1782 fn test_hover_shadowing_pat() {
1803 fn test_hover_macro_invocation() {
1806 macro_rules! foo { () => {} }
1808 fn f() { fo$0o!(); }
1825 fn test_hover_macro2_invocation() {
1833 fn f() { fo$0o!(); }
1856 fn test_hover_tuple_field() {
1858 r#"struct TS(String, i32$0);"#,
1870 fn test_hover_through_macro() {
1873 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1876 fn bar() { fo$0o(); }
1894 fn test_hover_through_attr() {
1897 //- proc_macros: identity
1898 #[proc_macros::identity]
1916 fn test_hover_through_expr_in_macro() {
1919 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1920 fn foo(bar:u32) { let a = id!(ba$0r); }
1933 fn test_hover_through_expr_in_macro_recursive() {
1936 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1937 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1938 fn foo(bar:u32) { let a = id!(ba$0r); }
1951 fn test_hover_through_func_in_macro_recursive() {
1954 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1955 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1956 fn bar() -> u32 { 0 }
1957 fn foo() { let a = id!([0u32, bar($0)] ); }
1969 fn test_hover_through_literal_string_in_macro() {
1972 macro_rules! arr { ($($tt:tt)*) => { [$($tt)*)] } }
1974 let mastered_for_itunes = "";
1975 let _ = arr!("Tr$0acks", &mastered_for_itunes);
1988 fn test_hover_through_assert_macro() {
1991 #[rustc_builtin_macro]
1992 macro_rules! assert {}
1994 fn bar() -> bool { true }
2014 fn test_hover_through_literal_string_in_builtin_macro() {
2015 check_hover_no_result(
2017 #[rustc_builtin_macro]
2018 macro_rules! format {}
2021 format!("hel$0lo {}", 0);
2028 fn test_hover_non_ascii_space_doc() {
2031 /// <- `\u{3000}` here
2034 fn bar() { fo$0o(); }
2055 fn test_hover_function_show_qualifiers() {
2057 r#"async fn foo$0() {}"#,
2071 r#"pub const unsafe fn foo$0() {}"#,
2080 pub const unsafe fn foo()
2084 // Top level `pub(crate)` will be displayed as no visibility.
2086 r#"mod m { pub(crate) async unsafe extern "C" fn foo$0() {} }"#,
2095 pub(crate) async unsafe extern "C" fn foo()
2102 fn test_hover_trait_show_qualifiers() {
2104 r"unsafe trait foo$0() {}",
2121 fn test_hover_extern_crate() {
2124 //- /main.rs crate:main deps:std
2126 //- /std/lib.rs crate:std
2127 //! Standard library for this test
2141 Standard library for this test
2149 //- /main.rs crate:main deps:std
2150 extern crate std as ab$0c;
2151 //- /std/lib.rs crate:std
2152 //! Standard library for this test
2166 Standard library for this test
2175 fn test_hover_mod_with_same_name_as_function() {
2178 use self::m$0y::Bar;
2179 mod my { pub struct Bar; }
2198 fn test_hover_struct_doc_comment() {
2201 /// This is an example
2209 /// assert_eq!(6, my_crate::add_one(5));
2213 fn foo() { let bar = Ba$0r; }
2236 assert_eq!(6, my_crate::add_one(5));
2243 fn test_hover_struct_doc_attr() {
2249 fn foo() { let bar = Ba$0r; }
2270 fn test_hover_struct_doc_attr_multiple_and_mixed() {
2274 #[doc = "bar docs 1"]
2275 #[doc = "bar docs 2"]
2278 fn foo() { let bar = Ba$0r; }
2301 fn test_hover_external_url() {
2305 /// [external](https://www.google.com)
2321 [external](https://www.google.com)
2326 // Check that we don't rewrite links which we can't identify
2328 fn test_hover_unknown_target() {
2354 fn test_hover_no_links() {
2355 check_hover_no_links(
2358 /// case 1. bare URL: https://www.example.com/
2359 /// case 2. inline URL with title: [example](https://www.example.com/)
2360 /// case 3. code reference: [`Result`]
2361 /// case 4. code reference but miss footnote: [`String`]
2362 /// case 5. autolink: <http://www.example.com/>
2363 /// case 6. email address: <test@example.com>
2364 /// case 7. reference: [example][example]
2365 /// case 8. collapsed link: [example][]
2366 /// case 9. shortcut link: [example]
2367 /// case 10. inline without URL: [example]()
2368 /// case 11. reference: [foo][foo]
2369 /// case 12. reference: [foo][bar]
2370 /// case 13. collapsed link: [foo][]
2371 /// case 14. shortcut link: [foo]
2372 /// case 15. inline without URL: [foo]()
2373 /// case 16. just escaped text: \[foo]
2374 /// case 17. inline link: [Foo](foo::Foo)
2376 /// [`Result`]: ../../std/result/enum.Result.html
2377 /// [^example]: https://www.example.com/
2394 case 1. bare URL: https://www.example.com/
2395 case 2. inline URL with title: [example](https://www.example.com/)
2396 case 3. code reference: `Result`
2397 case 4. code reference but miss footnote: `String`
2398 case 5. autolink: http://www.example.com/
2399 case 6. email address: test@example.com
2400 case 7. reference: example
2401 case 8. collapsed link: example
2402 case 9. shortcut link: example
2403 case 10. inline without URL: example
2404 case 11. reference: foo
2405 case 12. reference: foo
2406 case 13. collapsed link: foo
2407 case 14. shortcut link: foo
2408 case 15. inline without URL: foo
2409 case 16. just escaped text: \[foo\]
2410 case 17. inline link: Foo
2412 [^example]: https://www.example.com/
2418 fn test_hover_macro_generated_struct_fn_doc_comment() {
2419 cov_mark::check!(hover_macro_generated_struct_fn_doc_comment);
2435 fn foo() { let bar = Bar; bar.fo$0o(); }
2456 fn test_hover_macro_generated_struct_fn_doc_attr() {
2457 cov_mark::check!(hover_macro_generated_struct_fn_doc_attr);
2465 #[doc = "Do the foo"]
2473 fn foo() { let bar = Bar; bar.fo$0o(); }
2494 fn test_hover_trait_has_impl_action() {
2496 r#"trait foo$0() {}"#,
2513 fn test_hover_struct_has_impl_action() {
2515 r"struct foo$0() {}",
2532 fn test_hover_union_has_impl_action() {
2534 r#"union foo$0() {}"#,
2551 fn test_hover_enum_has_impl_action() {
2553 r"enum foo$0() { A, B }",
2570 fn test_hover_self_has_impl_action() {
2572 r#"struct foo where Self$0:;"#,
2589 fn test_hover_test_has_action() {
2607 use_name_in_title: false,
2608 nav: NavigationTarget {
2613 focus_range: 11..19,
2634 fn test_hover_test_mod_has_action() {
2646 use_name_in_title: false,
2647 nav: NavigationTarget {
2655 description: "mod tests",
2669 fn test_hover_struct_has_goto_type_action() {
2674 fn main() { let s$0t = S{ f1:0 }; }
2681 mod_path: "test::S",
2682 nav: NavigationTarget {
2690 description: "struct S",
2701 fn test_hover_generic_struct_has_goto_type_actions() {
2705 struct S<T>{ f1: T }
2707 fn main() { let s$0t = S{ f1:Arg(0) }; }
2714 mod_path: "test::S",
2715 nav: NavigationTarget {
2720 focus_range: 24..25,
2723 description: "struct S<T>",
2727 mod_path: "test::Arg",
2728 nav: NavigationTarget {
2736 description: "struct Arg",
2747 fn test_hover_generic_struct_has_flattened_goto_type_actions() {
2751 struct S<T>{ f1: T }
2753 fn main() { let s$0t = S{ f1: S{ f1: Arg(0) } }; }
2760 mod_path: "test::S",
2761 nav: NavigationTarget {
2766 focus_range: 24..25,
2769 description: "struct S<T>",
2773 mod_path: "test::Arg",
2774 nav: NavigationTarget {
2782 description: "struct Arg",
2793 fn test_hover_tuple_has_goto_type_actions() {
2802 fn main() { let s$0t = (A(1), B(2), M::C(3) ); }
2809 mod_path: "test::A",
2810 nav: NavigationTarget {
2818 description: "struct A",
2822 mod_path: "test::B",
2823 nav: NavigationTarget {
2828 focus_range: 22..23,
2831 description: "struct B",
2835 mod_path: "test::M::C",
2836 nav: NavigationTarget {
2841 focus_range: 53..54,
2844 description: "pub struct C",
2855 fn test_hover_return_impl_trait_has_goto_type_action() {
2859 fn foo() -> impl Foo {}
2861 fn main() { let s$0t = foo(); }
2868 mod_path: "test::Foo",
2869 nav: NavigationTarget {
2877 description: "trait Foo",
2888 fn test_hover_generic_return_impl_trait_has_goto_type_action() {
2893 fn foo() -> impl Foo<S> {}
2895 fn main() { let s$0t = foo(); }
2902 mod_path: "test::Foo",
2903 nav: NavigationTarget {
2911 description: "trait Foo<T>",
2915 mod_path: "test::S",
2916 nav: NavigationTarget {
2921 focus_range: 23..24,
2924 description: "struct S",
2935 fn test_hover_return_impl_traits_has_goto_type_action() {
2940 fn foo() -> impl Foo + Bar {}
2942 fn main() { let s$0t = foo(); }
2949 mod_path: "test::Foo",
2950 nav: NavigationTarget {
2958 description: "trait Foo",
2962 mod_path: "test::Bar",
2963 nav: NavigationTarget {
2968 focus_range: 19..22,
2971 description: "trait Bar",
2982 fn test_hover_generic_return_impl_traits_has_goto_type_action() {
2990 fn foo() -> impl Foo<S1> + Bar<S2> {}
2992 fn main() { let s$0t = foo(); }
2999 mod_path: "test::Foo",
3000 nav: NavigationTarget {
3008 description: "trait Foo<T>",
3012 mod_path: "test::Bar",
3013 nav: NavigationTarget {
3018 focus_range: 22..25,
3021 description: "trait Bar<T>",
3025 mod_path: "test::S1",
3026 nav: NavigationTarget {
3031 focus_range: 39..41,
3034 description: "struct S1",
3038 mod_path: "test::S2",
3039 nav: NavigationTarget {
3044 focus_range: 52..54,
3047 description: "struct S2",
3058 fn test_hover_arg_impl_trait_has_goto_type_action() {
3062 fn foo(ar$0g: &impl Foo) {}
3069 mod_path: "test::Foo",
3070 nav: NavigationTarget {
3078 description: "trait Foo",
3089 fn test_hover_arg_impl_traits_has_goto_type_action() {
3096 fn foo(ar$0g: &impl Foo + Bar<S>) {}
3103 mod_path: "test::Foo",
3104 nav: NavigationTarget {
3112 description: "trait Foo",
3116 mod_path: "test::Bar",
3117 nav: NavigationTarget {
3122 focus_range: 19..22,
3125 description: "trait Bar<T>",
3129 mod_path: "test::S",
3130 nav: NavigationTarget {
3135 focus_range: 36..37,
3138 description: "struct S",
3149 fn test_hover_async_block_impl_trait_has_goto_type_action() {
3152 //- minicore: future
3155 let fo$0o = async { S };
3163 mod_path: "core::future::Future",
3164 nav: NavigationTarget {
3168 full_range: 254..436,
3169 focus_range: 293..299,
3172 description: "pub trait Future",
3176 mod_path: "test::S",
3177 nav: NavigationTarget {
3185 description: "struct S",
3196 fn test_hover_arg_generic_impl_trait_has_goto_type_action() {
3201 fn foo(ar$0g: &impl Foo<S>) {}
3208 mod_path: "test::Foo",
3209 nav: NavigationTarget {
3217 description: "trait Foo<T>",
3221 mod_path: "test::S",
3222 nav: NavigationTarget {
3227 focus_range: 23..24,
3230 description: "struct S",
3241 fn test_hover_dyn_return_has_goto_type_action() {
3249 fn foo() -> B<dyn Foo> {}
3251 fn main() { let s$0t = foo(); }
3258 mod_path: "test::B",
3259 nav: NavigationTarget {
3264 focus_range: 49..50,
3267 description: "struct B<T>",
3271 mod_path: "test::Foo",
3272 nav: NavigationTarget {
3280 description: "trait Foo",
3291 fn test_hover_dyn_arg_has_goto_type_action() {
3295 fn foo(ar$0g: &dyn Foo) {}
3302 mod_path: "test::Foo",
3303 nav: NavigationTarget {
3311 description: "trait Foo",
3322 fn test_hover_generic_dyn_arg_has_goto_type_action() {
3327 fn foo(ar$0g: &dyn Foo<S>) {}
3334 mod_path: "test::Foo",
3335 nav: NavigationTarget {
3343 description: "trait Foo<T>",
3347 mod_path: "test::S",
3348 nav: NavigationTarget {
3353 focus_range: 23..24,
3356 description: "struct S",
3367 fn test_hover_goto_type_action_links_order() {
3370 trait ImplTrait<T> {}
3371 trait DynTrait<T> {}
3375 fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
3382 mod_path: "test::ImplTrait",
3383 nav: NavigationTarget {
3391 description: "trait ImplTrait<T>",
3395 mod_path: "test::B",
3396 nav: NavigationTarget {
3401 focus_range: 50..51,
3404 description: "struct B<T>",
3408 mod_path: "test::DynTrait",
3409 nav: NavigationTarget {
3414 focus_range: 28..36,
3417 description: "trait DynTrait<T>",
3421 mod_path: "test::S",
3422 nav: NavigationTarget {
3427 focus_range: 65..66,
3430 description: "struct S",
3441 fn test_hover_associated_type_has_goto_type_action() {
3446 fn get(self) -> Self::Item {}
3452 impl Foo for S { type Item = Bar; }
3454 fn test() -> impl Foo { S {} }
3456 fn main() { let s$0t = test().get(); }
3463 mod_path: "test::Foo",
3464 nav: NavigationTarget {
3472 description: "trait Foo",
3483 fn test_hover_const_param_has_goto_type_action() {
3487 struct Foo<const BAR: Bar>;
3489 impl<const BAR: Bar> Foo<BAR$0> {}
3496 mod_path: "test::Bar",
3497 nav: NavigationTarget {
3505 description: "struct Bar",
3516 fn test_hover_type_param_has_goto_type_action() {
3521 fn foo<T: Foo>(t: T$0){}
3528 mod_path: "test::Foo",
3529 nav: NavigationTarget {
3537 description: "trait Foo",
3548 fn test_hover_self_has_go_to_type() {
3561 mod_path: "test::Foo",
3562 nav: NavigationTarget {
3570 description: "struct Foo",
3581 fn hover_displays_normalized_crate_names() {
3584 //- /lib.rs crate:name-with-dashes
3586 pub struct Thing { x: u32 }
3589 pub fn new() -> Thing { Thing { x: 0 } }
3593 //- /main.rs crate:main deps:name-with-dashes
3594 fn main() { let foo_test = name_with_dashes::wrapper::Thing::new$0(); }
3600 name_with_dashes::wrapper::Thing
3604 pub fn new() -> Thing
3611 fn hover_field_pat_shorthand_ref_match_ergonomics() {
3634 fn hover_self_param_shows_type() {
3653 fn hover_self_param_shows_type_for_arbitrary_self_type() {
3659 fn bar(sel$0f: Arc<Foo>) {}
3673 fn hover_doc_outer_inner() {
3680 /// This comment belongs to the function
3704 fn hover_doc_outer_inner_attribue() {
3707 #[doc = "Be quick;"]
3709 #![doc = "time is mana"]
3711 #[doc = "This comment belongs to the function"]
3735 fn hover_doc_block_style_indentend() {
3769 fn hover_comments_dont_highlight_parent() {
3770 cov_mark::check!(no_highlight_on_comment_hover);
3771 check_hover_no_result(
3799 fn hover_lifetime() {
3801 r#"fn foo<'lifetime>(_: &'lifetime$0 ()) {}"#,
3813 fn hover_type_param() {
3820 impl<T: TraitA + TraitB> Foo<T$0> where T: Sized {}
3844 // lifetimes bounds arent being tracked yet
3849 impl<T: 'static> Foo<T$0> {}
3862 fn hover_type_param_sized_bounds() {
3863 // implicit `: Sized` bound
3869 impl<T: Trait> Foo<T$0> {}
3884 impl<T: Trait + ?Sized> Foo<T$0> {}
3896 mod type_param_sized_bounds {
3900 fn single_implicit() {
3917 fn single_explicit() {
3921 fn foo<T$0: Sized>() {}
3934 fn single_relaxed() {
3938 fn foo<T$0: ?Sized>() {}
3951 fn multiple_implicit() {
3956 fn foo<T$0: Trait>() {}
3969 fn multiple_explicit() {
3974 fn foo<T$0: Trait + Sized>() {}
3987 fn multiple_relaxed() {
3992 fn foo<T$0: Trait + ?Sized>() {}
4009 fn foo<T$0: ?Sized + Sized + Sized>() {}
4023 fn foo<T$0: Sized + ?Sized + Sized + Trait>() {}
4037 fn hover_const_param() {
4040 struct Foo<const LEN: usize>;
4041 impl<const LEN: usize> Foo<LEN$0> {}
4054 fn hover_const_pat() {
4058 const FOO: usize = 3;
4085 fn hover_mod_def() {
4112 fn hover_self_in_use() {
4115 //! This should not appear
4117 /// But this should appear
4120 use foo::bar::{self$0};
4135 But this should appear
4141 fn hover_keyword() {
4144 //- /main.rs crate:main deps:std
4145 fn f() { retur$0n; }
4146 //- /libstd.rs crate:std
4147 /// Docs for return_keyword
4148 mod return_keyword {}
4159 Docs for return_keyword
4165 fn hover_builtin() {
4168 //- /main.rs crate:main deps:std
4169 cosnt _: &str$0 = ""; }
4171 //- /libstd.rs crate:std
4172 /// Docs for prim_str
4190 fn hover_macro_expanded_function() {
4193 struct S<'a, T>(&'a T);
4197 fn bar<'t, T: Clone + 't>(s: &mut S<'t, T>, t: u32) -> *mut u32 where
4199 for<'a> T: Clone + 'a
4218 fn bar<'t, T>(s: &mut S<'t, T>, t: u32) -> *mut u32
4222 for<'a> T: Clone + 'a,
4229 fn hover_intra_doc_links() {
4234 /// This is the item. Cool!
4238 /// Gives you a [`TheItem$0`].
4240 /// [`TheItem`]: theitem::TheItem
4241 pub fn gimme() -> theitem::TheItem {
4258 This is the item. Cool!
4264 fn hover_generic_assoc() {
4267 fn foo<T: A>() where T::Assoc$0: {}
4287 let _: <T>::Assoc$0;
4327 fn string_shadowed_with_inner_items() {
4330 //- /main.rs crate:main deps:alloc
4332 /// Custom `String` type.
4341 //- /alloc.rs crate:alloc
4346 /// This is `alloc::String`.
4363 Custom `String` type.
4369 fn function_doesnt_shadow_crate_in_use_tree() {
4372 //- /main.rs crate:main deps:foo
4375 //- /foo.rs crate:foo
4389 fn hover_feature() {
4391 r#"#![feature(box_syntax$0)]"#,
4401 The tracking issue for this feature is: [#49733]
4403 [#49733]: https://github.com/rust-lang/rust/issues/49733
4405 See also [`box_patterns`](box-patterns.md)
4407 ------------------------
4409 Currently the only stable way to create a `Box` is via the `Box::new` method.
4410 Also it is not possible in stable Rust to destructure a `Box` in a match
4411 pattern. The unstable `box` keyword can be used to create a `Box`. An example
4415 #![feature(box_syntax)]
4429 r#"#![allow(arithmetic_overflow$0)]"#,
4431 *arithmetic_overflow*
4437 arithmetic operation overflows
4443 fn hover_clippy_lint() {
4445 r#"#![allow(clippy::almost_swapped$0)]"#,
4449 clippy::almost_swapped
4453 Checks for `foo = bar; bar = foo` sequences.
4459 fn hover_attr_path_qualifier() {
4460 cov_mark::check!(name_ref_classify_attr_path_qualifier);
4463 //- /foo.rs crate:foo
4465 //- /lib.rs crate:main.rs deps:foo
4496 use bar::{self as foo$0};
4539 fn hover_attribute_in_macro() {
4542 macro_rules! identity {
4547 #[rustc_builtin_macro]
4569 fn hover_derive_input() {
4572 #[rustc_builtin_macro]
4592 #[rustc_builtin_macro]
4595 #[derive(foo::Copy$0)]
4613 fn hover_range_math() {
4616 fn f() { let expr = $01 + 2 * 3$0 }
4626 fn f() { let expr = 1 $0+ 2 * $03 }
4636 fn f() { let expr = 1 + $02 * 3$0 }
4646 fn hover_range_arrays() {
4649 fn f() { let expr = $0[1, 2, 3, 4]$0 }
4659 fn f() { let expr = [1, 2, $03, 4]$0 }
4669 fn f() { let expr = [1, 2, $03$0, 4] }
4679 fn hover_range_functions() {
4682 fn f<T>(a: &[T]) { }
4683 fn b() { $0f$0(&[1, 2, 3, 4, 5]); }
4693 fn f<T>(a: &[T]) { }
4694 fn b() { f($0&[1, 2, 3, 4, 5]$0); }
4704 fn hover_range_shows_nothing_when_invalid() {
4705 check_hover_range_no_results(
4707 fn f<T>(a: &[T]) { }
4708 fn b()$0 { f(&[1, 2, 3, 4, 5]); }$0
4712 check_hover_range_no_results(
4714 fn f<T>$0(a: &[T]) { }
4715 fn b() { f(&[1, 2, 3,$0 4, 5]); }
4719 check_hover_range_no_results(
4721 fn $0f() { let expr = [1, 2, 3, 4]$0 }
4727 fn hover_range_shows_unit_for_statements() {
4730 fn f<T>(a: &[T]) { }
4731 fn b() { $0f(&[1, 2, 3, 4, 5]); }$0
4741 fn f() { let expr$0 = $0[1, 2, 3, 4] }
4751 fn hover_range_for_pat() {
4778 fn hover_range_shows_coercions_if_applicable_expr() {
4782 let x: &u32 = $0&&&&&0$0;
4795 let x: *const u32 = $0&0$0;
4801 Coerced to: *const u32
4808 fn hover_range_shows_type_actions() {
4813 let x: &Foo = $0&&&&&Foo$0;
4821 mod_path: "test::Foo",
4822 nav: NavigationTarget {
4830 description: "struct Foo",
4841 fn hover_try_expr_res() {
4847 fn foo() -> Result<(), FooError> {
4848 Ok($0Result::<(), FooError>::Ok(())?$0)
4862 fn foo() -> Result<(), FooError> {
4863 Ok($0Result::<(), BarError>::Ok(())?$0)
4868 Try Error Type: BarError
4869 Propagated as: FooError
4876 fn hover_try_expr() {
4879 struct NotResult<T, U>(T, U);
4883 fn foo() -> NotResult<(), Looooong> {
4884 $0NotResult((), Short)?$0;
4889 Try Target Type: NotResult<(), Short>
4890 Propagated as: NotResult<(), Looooong>
4896 struct NotResult<T, U>(T, U);
4900 fn foo() -> NotResult<(), Short> {
4901 $0NotResult((), Looooong)?$0;
4906 Try Target Type: NotResult<(), Looooong>
4907 Propagated as: NotResult<(), Short>
4914 fn hover_try_expr_option() {
4915 cov_mark::check!(hover_try_expr_opt_opt);
4918 //- minicore: option, try
4920 fn foo() -> Option<()> {
4927 <Option<i32> as Try>::Output
4933 fn hover_deref_expr() {
4937 use core::ops::Deref;
4939 struct DerefExample<T> {
4943 impl<T> Deref for DerefExample<T> {
4946 fn deref(&self) -> &Self::Target {
4952 let x = DerefExample { value: 0 };
4953 let y: i32 = $0*x$0;
4958 Dereferenced from: DerefExample<i32>
4966 fn hover_deref_expr_with_coercion() {
4970 use core::ops::Deref;
4972 struct DerefExample<T> {
4976 impl<T> Deref for DerefExample<T> {
4979 fn deref(&self) -> &Self::Target {
4985 let x = DerefExample { value: &&&&&0 };
4986 let y: &i32 = $0*x$0;
4991 Dereferenced from: DerefExample<&&&&&i32>