2 use hir::{AsAssocItem, HasAttrs, HasSource, HirDisplay, Semantics, TypeInfo};
4 base_db::{FileRange, SourceDatabase},
5 defs::{Definition, NameClass, NameRefClass},
7 generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES},
8 pick_best_token, try_resolve_derive_input_at, FamousDefs,
12 use itertools::Itertools;
15 algo, ast, display::fn_as_proc_macro_label, match_ast, AstNode, Direction, SyntaxKind::*,
16 SyntaxNode, SyntaxToken, T,
20 display::{macro_label, TryToNav},
22 doc_attributes, extract_definitions_from_docs, remove_links, resolve_doc_path_for_def,
25 markdown_remove::remove_markdown,
27 runnables::{runnable_fn, runnable_mod},
28 FileId, FilePosition, NavigationTarget, RangeInfo, Runnable,
31 #[derive(Clone, Debug, PartialEq, Eq)]
32 pub struct HoverConfig {
33 pub links_in_hover: bool,
34 pub documentation: Option<HoverDocFormat>,
38 fn markdown(&self) -> bool {
39 matches!(self.documentation, Some(HoverDocFormat::Markdown))
43 #[derive(Clone, Debug, PartialEq, Eq)]
44 pub enum HoverDocFormat {
49 #[derive(Debug, Clone)]
50 pub enum HoverAction {
52 Implementation(FilePosition),
53 Reference(FilePosition),
54 GoToType(Vec<HoverGotoTypeData>),
58 fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
62 Some(HoverGotoTypeData {
63 mod_path: render_path(
66 it.name(db).map(|name| name.to_string()),
68 nav: it.try_to_nav(db)?,
72 HoverAction::GoToType(targets)
76 #[derive(Debug, Clone, Eq, PartialEq)]
77 pub struct HoverGotoTypeData {
79 pub nav: NavigationTarget,
82 /// Contains the results when hovering over an item
83 #[derive(Debug, Default)]
84 pub struct HoverResult {
86 pub actions: Vec<HoverAction>,
91 // Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
92 // Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
94 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
97 FileRange { file_id, range }: FileRange,
99 ) -> Option<RangeInfo<HoverResult>> {
100 let sema = hir::Semantics::new(db);
101 let file = sema.parse(file_id).syntax().clone();
103 if !range.is_empty() {
104 return hover_ranged(&file, range, &sema, config);
106 let offset = range.start();
108 let token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
109 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] => 3,
110 T!['('] | T![')'] => 2,
111 kind if kind.is_trivia() => 0,
114 let token = sema.descend_into_macros(token);
115 let node = token.parent()?;
116 let mut range_override = None;
117 let definition = match_ast! {
119 ast::Name(name) => NameClass::classify(&sema, &name).map(|class| match class {
120 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
121 NameClass::PatFieldShorthand { local_def, field_ref: _ } => Definition::Local(local_def),
123 ast::NameRef(name_ref) => NameRefClass::classify(&sema, &name_ref).map(|class| match class {
124 NameRefClass::Definition(def) => def,
125 NameRefClass::FieldShorthand { local_ref: _, field_ref } => {
126 Definition::Field(field_ref)
129 ast::Lifetime(lifetime) => NameClass::classify_lifetime(&sema, &lifetime).map_or_else(
131 NameRefClass::classify_lifetime(&sema, &lifetime).and_then(|class| match class {
132 NameRefClass::Definition(it) => Some(it),
140 if token.kind() == COMMENT {
141 cov_mark::hit!(no_highlight_on_comment_hover);
142 let (attributes, def) = doc_attributes(&sema, &node)?;
143 let (docs, doc_mapping) = attributes.docs_with_rangemap(db)?;
144 let (idl_range, link, ns) =
145 extract_definitions_from_docs(&docs).into_iter().find_map(|(range, link, ns)| {
146 let mapped = doc_mapping.map(range)?;
147 (mapped.file_id == file_id.into() && mapped.value.contains(offset)).then(||(mapped.value, link, ns))
149 range_override = Some(idl_range);
150 Some(match resolve_doc_path_for_def(db,def, &link,ns)? {
151 Either::Left(it) => Definition::ModuleDef(it),
152 Either::Right(it) => Definition::Macro(it),
154 // attributes, require special machinery as they are mere ident tokens
155 } else if let Some(attr) = token.ancestors().find_map(ast::Attr::cast) {
157 if let res@Some(_) = try_hover_for_lint(&attr, &token) {
161 range_override = Some(token.text_range());
162 try_resolve_derive_input_at(&sema, &attr, &token).map(Definition::Macro)
171 if let Some(definition) = definition {
172 let famous_defs = match &definition {
173 Definition::ModuleDef(hir::ModuleDef::BuiltinType(_)) => {
174 Some(FamousDefs(&sema, sema.scope(&node).krate()))
178 if let Some(markup) = hover_for_definition(db, definition, famous_defs.as_ref(), config) {
179 let mut res = HoverResult::default();
180 res.markup = process_markup(sema.db, definition, &markup, config);
181 if let Some(action) = show_implementations_action(db, definition) {
182 res.actions.push(action);
185 if let Some(action) = show_fn_references_action(db, definition) {
186 res.actions.push(action);
189 if let Some(action) = runnable_action(&sema, definition, file_id) {
190 res.actions.push(action);
193 if let Some(action) = goto_type_action_for_def(db, definition) {
194 res.actions.push(action);
197 let range = range_override.unwrap_or_else(|| sema.original_range(&node).range);
198 return Some(RangeInfo::new(range, res));
202 if let res @ Some(_) = hover_for_keyword(&sema, config, &token) {
206 // No definition below cursor, fall back to showing type hovers.
210 .take_while(|it| !ast::Item::can_cast(it.kind()))
211 .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
213 let expr_or_pat = match_ast! {
215 ast::Expr(it) => Either::Left(it),
216 ast::Pat(it) => Either::Right(it),
217 // If this node is a MACRO_CALL, it means that `descend_into_macros` failed to resolve.
218 // (e.g expanding a builtin macro). So we give up here.
219 ast::MacroCall(_it) => return None,
224 let res = hover_type_info(&sema, config, &expr_or_pat)?;
225 let range = sema.original_range(&node).range;
226 Some(RangeInfo::new(range, res))
231 range: syntax::TextRange,
232 sema: &Semantics<RootDatabase>,
233 config: &HoverConfig,
234 ) -> Option<RangeInfo<HoverResult>> {
235 let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
238 ast::Expr(expr) => Some(Either::Left(expr)),
239 ast::Pat(pat) => Some(Either::Right(pat)),
244 let res = match &expr_or_pat {
245 Either::Left(ast::Expr::TryExpr(try_expr)) => hover_try_expr(sema, config, try_expr),
246 Either::Left(ast::Expr::PrefixExpr(prefix_expr))
247 if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
249 hover_deref_expr(sema, config, prefix_expr)
253 let res = res.or_else(|| hover_type_info(sema, config, &expr_or_pat));
255 let range = match expr_or_pat {
256 Either::Left(it) => it.syntax().text_range(),
257 Either::Right(it) => it.syntax().text_range(),
259 RangeInfo::new(range, it)
264 sema: &Semantics<RootDatabase>,
265 config: &HoverConfig,
266 try_expr: &ast::TryExpr,
267 ) -> Option<HoverResult> {
268 let inner_ty = sema.type_of_expr(&try_expr.expr()?)?.original;
269 let mut ancestors = try_expr.syntax().ancestors();
270 let mut body_ty = loop {
271 let next = ancestors.next()?;
274 ast::Fn(fn_) => sema.to_def(&fn_)?.ret_type(sema.db),
275 ast::Item(__) => return None,
276 ast::ClosureExpr(closure) => sema.type_of_expr(&closure.body()?)?.original,
277 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
278 sema.type_of_expr(&effect.block_expr()?.into())?.original
287 if inner_ty == body_ty {
291 let mut inner_ty = inner_ty;
292 let mut s = "Try Target".to_owned();
294 let adts = inner_ty.as_adt().zip(body_ty.as_adt());
295 if let Some((hir::Adt::Enum(inner), hir::Adt::Enum(body))) = adts {
296 let famous_defs = FamousDefs(sema, sema.scope(&try_expr.syntax()).krate());
297 // special case for two options, there is no value in showing them
298 if let Some(option_enum) = famous_defs.core_option_Option() {
299 if inner == option_enum && body == option_enum {
300 cov_mark::hit!(hover_try_expr_opt_opt);
305 // special case two results to show the error variants only
306 if let Some(result_enum) = famous_defs.core_result_Result() {
307 if inner == result_enum && body == result_enum {
308 let error_type_args =
309 inner_ty.type_arguments().nth(1).zip(body_ty.type_arguments().nth(1));
310 if let Some((inner, body)) = error_type_args {
313 s = "Try Error".to_owned();
319 let mut res = HoverResult::default();
321 let mut targets: Vec<hir::ModuleDef> = Vec::new();
322 let mut push_new_def = |item: hir::ModuleDef| {
323 if !targets.contains(&item) {
327 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
328 walk_and_push_ty(sema.db, &body_ty, &mut push_new_def);
329 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
331 let inner_ty = inner_ty.display(sema.db).to_string();
332 let body_ty = body_ty.display(sema.db).to_string();
333 let ty_len_max = inner_ty.len().max(body_ty.len());
335 let l = "Propagated as: ".len() - " Type: ".len();
336 let static_text_len_diff = l as isize - s.len() as isize;
337 let tpad = static_text_len_diff.max(0) as usize;
338 let ppad = static_text_len_diff.min(0).abs() as usize;
340 res.markup = format!(
341 "{bt_start}{} Type: {:>pad0$}\nPropagated as: {:>pad1$}\n{bt_end}",
345 pad0 = ty_len_max + tpad,
346 pad1 = ty_len_max + ppad,
347 bt_start = if config.markdown() { "```text\n" } else { "" },
348 bt_end = if config.markdown() { "```\n" } else { "" }
355 sema: &Semantics<RootDatabase>,
356 config: &HoverConfig,
357 deref_expr: &ast::PrefixExpr,
358 ) -> Option<HoverResult> {
359 let inner_ty = sema.type_of_expr(&deref_expr.expr()?)?.original;
360 let TypeInfo { original, adjusted } =
361 sema.type_of_expr(&ast::Expr::from(deref_expr.clone()))?;
363 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, &original, &mut push_new_def);
373 res.markup = if let Some(adjusted_ty) = adjusted {
374 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
375 let original = original.display(sema.db).to_string();
376 let adjusted = adjusted_ty.display(sema.db).to_string();
377 let inner = inner_ty.display(sema.db).to_string();
378 let type_len = "Type: ".len();
379 let coerced_len = "Coerced to: ".len();
380 let deref_len = "Dereferenced from: ".len();
381 let max_len = (original.len() + type_len)
382 .max(adjusted.len() + coerced_len)
383 .max(inner.len() + deref_len);
385 "{bt_start}Type: {:>apad$}\nCoerced to: {:>opad$}\nDereferenced from: {:>ipad$}\n{bt_end}",
389 apad = max_len - type_len,
390 opad = max_len - coerced_len,
391 ipad = max_len - deref_len,
392 bt_start = if config.markdown() { "```text\n" } else { "" },
393 bt_end = if config.markdown() { "```\n" } else { "" }
397 let original = original.display(sema.db).to_string();
398 let inner = inner_ty.display(sema.db).to_string();
399 let type_len = "Type: ".len();
400 let deref_len = "Dereferenced from: ".len();
401 let max_len = (original.len() + type_len).max(inner.len() + deref_len);
403 "{bt_start}Type: {:>apad$}\nDereferenced from: {:>ipad$}\n{bt_end}",
406 apad = max_len - type_len,
407 ipad = max_len - deref_len,
408 bt_start = if config.markdown() { "```text\n" } else { "" },
409 bt_end = if config.markdown() { "```\n" } else { "" }
413 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
419 sema: &Semantics<RootDatabase>,
420 config: &HoverConfig,
421 expr_or_pat: &Either<ast::Expr, ast::Pat>,
422 ) -> Option<HoverResult> {
423 let TypeInfo { original, adjusted } = match expr_or_pat {
424 Either::Left(expr) => sema.type_of_expr(expr)?,
425 Either::Right(pat) => sema.type_of_pat(pat)?,
428 let mut res = HoverResult::default();
429 let mut targets: Vec<hir::ModuleDef> = Vec::new();
430 let mut push_new_def = |item: hir::ModuleDef| {
431 if !targets.contains(&item) {
435 walk_and_push_ty(sema.db, &original, &mut push_new_def);
437 res.markup = if let Some(adjusted_ty) = adjusted {
438 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
439 let original = original.display(sema.db).to_string();
440 let adjusted = adjusted_ty.display(sema.db).to_string();
441 let static_text_diff_len = "Coerced to: ".len() - "Type: ".len();
443 "{bt_start}Type: {:>apad$}\nCoerced to: {:>opad$}\n{bt_end}",
446 apad = static_text_diff_len + adjusted.len().max(original.len()),
447 opad = original.len(),
448 bt_start = if config.markdown() { "```text\n" } else { "" },
449 bt_end = if config.markdown() { "```\n" } else { "" }
453 if config.markdown() {
454 Markup::fenced_block(&original.display(sema.db))
456 original.display(sema.db).to_string().into()
459 res.actions.push(HoverAction::goto_type_from_targets(sema.db, targets));
463 fn try_hover_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option<RangeInfo<HoverResult>> {
464 let (path, tt) = attr.as_simple_call()?;
465 if !tt.syntax().text_range().contains(token.text_range().start()) {
468 let (is_clippy, lints) = match &*path {
469 "feature" => (false, FEATURES),
470 "allow" | "deny" | "forbid" | "warn" => {
471 let is_clippy = algo::non_trivia_sibling(token.clone().into(), Direction::Prev)
472 .filter(|t| t.kind() == T![:])
473 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
474 .filter(|t| t.kind() == T![:])
475 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
477 t.kind() == T![ident] && t.into_token().map_or(false, |t| t.text() == "clippy")
482 (false, DEFAULT_LINTS)
489 let needle = if is_clippy {
490 tmp = format!("clippy::{}", token.text());
497 lints.binary_search_by_key(&needle, |lint| lint.label).ok().map(|idx| &lints[idx])?;
501 markup: Markup::from(format!("```\n{}\n```\n___\n\n{}", lint.label, lint.description)),
507 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
508 fn to_action(nav_target: NavigationTarget) -> HoverAction {
509 HoverAction::Implementation(FilePosition {
510 file_id: nav_target.file_id,
511 offset: nav_target.focus_or_full_range().start(),
515 let adt = match def {
516 Definition::ModuleDef(hir::ModuleDef::Trait(it)) => {
517 return it.try_to_nav(db).map(to_action)
519 Definition::ModuleDef(hir::ModuleDef::Adt(it)) => Some(it),
520 Definition::SelfType(it) => it.self_ty(db).as_adt(),
523 adt.try_to_nav(db).map(to_action)
526 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
528 Definition::ModuleDef(hir::ModuleDef::Function(it)) => {
529 it.try_to_nav(db).map(|nav_target| {
530 HoverAction::Reference(FilePosition {
531 file_id: nav_target.file_id,
532 offset: nav_target.focus_or_full_range().start(),
541 sema: &hir::Semantics<RootDatabase>,
544 ) -> Option<HoverAction> {
546 Definition::ModuleDef(it) => match it {
547 hir::ModuleDef::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
548 hir::ModuleDef::Function(func) => {
549 let src = func.source(sema.db)?;
550 if src.file_id != file_id.into() {
551 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
552 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
556 runnable_fn(sema, func).map(HoverAction::Runnable)
564 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
565 let mut targets: Vec<hir::ModuleDef> = Vec::new();
566 let mut push_new_def = |item: hir::ModuleDef| {
567 if !targets.contains(&item) {
572 if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
573 it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
576 Definition::Local(it) => it.ty(db),
577 Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
578 Definition::Field(field) => field.ty(db),
582 walk_and_push_ty(db, &ty, &mut push_new_def);
585 Some(HoverAction::goto_type_from_targets(db, targets))
591 push_new_def: &mut dyn FnMut(hir::ModuleDef),
594 if let Some(adt) = t.as_adt() {
595 push_new_def(adt.into());
596 } else if let Some(trait_) = t.as_dyn_trait() {
597 push_new_def(trait_.into());
598 } else if let Some(traits) = t.as_impl_traits(db) {
599 traits.into_iter().for_each(|it| push_new_def(it.into()));
600 } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
601 push_new_def(trait_.into());
606 fn hover_markup(docs: Option<String>, desc: String, mod_path: Option<String>) -> Option<Markup> {
607 let mut buf = String::new();
609 if let Some(mod_path) = mod_path {
610 if !mod_path.is_empty() {
611 format_to!(buf, "```rust\n{}\n```\n\n", mod_path);
614 format_to!(buf, "```rust\n{}\n```", desc);
616 if let Some(doc) = docs {
617 format_to!(buf, "\n___\n\n{}", doc);
626 config: &HoverConfig,
628 let markup = markup.as_str();
629 let markup = if !config.markdown() {
630 remove_markdown(markup)
631 } else if config.links_in_hover {
632 rewrite_links(db, markup, def)
639 fn definition_owner_name(db: &RootDatabase, def: &Definition) -> Option<String> {
641 Definition::Field(f) => Some(f.parent_def(db).name(db)),
642 Definition::Local(l) => l.parent(db).name(db),
643 Definition::ModuleDef(md) => match md {
644 hir::ModuleDef::Function(f) => match f.as_assoc_item(db)?.container(db) {
645 hir::AssocItemContainer::Trait(t) => Some(t.name(db)),
646 hir::AssocItemContainer::Impl(i) => i.self_ty(db).as_adt().map(|adt| adt.name(db)),
648 hir::ModuleDef::Variant(e) => Some(e.parent_enum(db).name(db)),
653 .map(|name| name.to_string())
656 fn render_path(db: &RootDatabase, module: hir::Module, item_name: Option<String>) -> String {
658 db.crate_graph()[module.krate().into()].display_name.as_ref().map(|it| it.to_string());
659 let module_path = module
663 .flat_map(|it| it.name(db).map(|name| name.to_string()));
664 crate_name.into_iter().chain(module_path).chain(item_name).join("::")
667 fn definition_mod_path(db: &RootDatabase, def: &Definition) -> Option<String> {
668 if let Definition::GenericParam(_) = def {
671 def.module(db).map(|module| render_path(db, module, definition_owner_name(db, def)))
674 fn hover_for_definition(
677 famous_defs: Option<&FamousDefs>,
678 config: &HoverConfig,
679 ) -> Option<Markup> {
680 let mod_path = definition_mod_path(db, &def);
681 let (label, docs) = match def {
682 Definition::Macro(it) => (
683 match &it.source(db)?.value {
684 Either::Left(mac) => macro_label(mac),
685 Either::Right(mac_fn) => fn_as_proc_macro_label(mac_fn),
689 Definition::Field(def) => label_and_docs(db, def),
690 Definition::ModuleDef(it) => match it {
691 hir::ModuleDef::Module(it) => label_and_docs(db, it),
692 hir::ModuleDef::Function(it) => label_and_docs(db, it),
693 hir::ModuleDef::Adt(it) => label_and_docs(db, it),
694 hir::ModuleDef::Variant(it) => label_and_docs(db, it),
695 hir::ModuleDef::Const(it) => label_and_docs(db, it),
696 hir::ModuleDef::Static(it) => label_and_docs(db, it),
697 hir::ModuleDef::Trait(it) => label_and_docs(db, it),
698 hir::ModuleDef::TypeAlias(it) => label_and_docs(db, it),
699 hir::ModuleDef::BuiltinType(it) => {
701 .and_then(|fd| hover_for_builtin(fd, it))
702 .or_else(|| Some(Markup::fenced_block(&it.name())))
705 Definition::Local(it) => return hover_for_local(it, db),
706 Definition::SelfType(impl_def) => {
707 impl_def.self_ty(db).as_adt().map(|adt| label_and_docs(db, adt))?
709 Definition::GenericParam(it) => label_and_docs(db, it),
710 Definition::Label(it) => return Some(Markup::fenced_block(&it.name(db))),
714 docs.filter(|_| config.documentation.is_some()).map(Into::into),
719 fn label_and_docs<D>(db: &RootDatabase, def: D) -> (String, Option<hir::Documentation>)
721 D: HasAttrs + HirDisplay,
723 let label = def.display(db).to_string();
724 let docs = def.attrs(db).docs();
729 fn hover_for_local(it: hir::Local, db: &RootDatabase) -> Option<Markup> {
731 let ty = ty.display(db);
732 let is_mut = if it.is_mut(db) { "mut " } else { "" };
733 let desc = match it.source(db).value {
734 Either::Left(ident) => {
735 let name = it.name(db).unwrap();
736 let let_kw = if ident
739 .map_or(false, |p| p.kind() == LET_STMT || p.kind() == CONDITION)
745 format!("{}{}{}: {}", let_kw, is_mut, name, ty)
747 Either::Right(_) => format!("{}self: {}", is_mut, ty),
749 hover_markup(None, desc, None)
752 fn hover_for_keyword(
753 sema: &Semantics<RootDatabase>,
754 config: &HoverConfig,
756 ) -> Option<RangeInfo<HoverResult>> {
757 if !token.kind().is_keyword() || !config.documentation.is_some() {
760 let famous_defs = FamousDefs(sema, sema.scope(&token.parent()?).krate());
761 // std exposes {}_keyword modules with docstrings on the root to document keywords
762 let keyword_mod = format!("{}_keyword", token.text());
763 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?;
764 let docs = doc_owner.attrs(sema.db).docs()?;
765 let markup = process_markup(
767 Definition::ModuleDef(doc_owner.into()),
768 &hover_markup(Some(docs.into()), token.text().into(), None)?,
771 Some(RangeInfo::new(token.text_range(), HoverResult { markup, actions: Default::default() }))
774 fn hover_for_builtin(famous_defs: &FamousDefs, builtin: hir::BuiltinType) -> Option<Markup> {
775 // std exposes prim_{} modules with docstrings on the root to document the builtins
776 let primitive_mod = format!("prim_{}", builtin.name());
777 let doc_owner = find_std_module(famous_defs, &primitive_mod)?;
778 let docs = doc_owner.attrs(famous_defs.0.db).docs()?;
779 hover_markup(Some(docs.into()), builtin.name().to_string(), None)
782 fn find_std_module(famous_defs: &FamousDefs, name: &str) -> Option<hir::Module> {
783 let db = famous_defs.0.db;
784 let std_crate = famous_defs.std()?;
785 let std_root_module = std_crate.root_module(db);
788 .find(|module| module.name(db).map_or(false, |module| module.to_string() == name))
793 use expect_test::{expect, Expect};
794 use ide_db::base_db::{FileLoader, FileRange};
795 use syntax::TextRange;
797 use crate::{fixture, hover::HoverDocFormat, HoverConfig};
799 fn check_hover_no_result(ra_fixture: &str) {
800 let (analysis, position) = fixture::position(ra_fixture);
804 links_in_hover: true,
805 documentation: Some(HoverDocFormat::Markdown),
807 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
810 assert!(hover.is_none());
813 fn check(ra_fixture: &str, expect: Expect) {
814 let (analysis, position) = fixture::position(ra_fixture);
818 links_in_hover: true,
819 documentation: Some(HoverDocFormat::Markdown),
821 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
826 let content = analysis.db.file_text(position.file_id);
827 let hovered_element = &content[hover.range];
829 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
830 expect.assert_eq(&actual)
833 fn check_hover_no_links(ra_fixture: &str, expect: Expect) {
834 let (analysis, position) = fixture::position(ra_fixture);
838 links_in_hover: false,
839 documentation: Some(HoverDocFormat::Markdown),
841 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
846 let content = analysis.db.file_text(position.file_id);
847 let hovered_element = &content[hover.range];
849 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
850 expect.assert_eq(&actual)
853 fn check_hover_no_markdown(ra_fixture: &str, expect: Expect) {
854 let (analysis, position) = fixture::position(ra_fixture);
858 links_in_hover: true,
859 documentation: Some(HoverDocFormat::PlainText),
861 FileRange { file_id: position.file_id, range: TextRange::empty(position.offset) },
866 let content = analysis.db.file_text(position.file_id);
867 let hovered_element = &content[hover.range];
869 let actual = format!("*{}*\n{}\n", hovered_element, hover.info.markup);
870 expect.assert_eq(&actual)
873 fn check_actions(ra_fixture: &str, expect: Expect) {
874 let (analysis, file_id, position) = fixture::range_or_position(ra_fixture);
878 links_in_hover: true,
879 documentation: Some(HoverDocFormat::Markdown),
881 FileRange { file_id, range: position.range_or_empty() },
885 expect.assert_debug_eq(&hover.info.actions)
888 fn check_hover_range(ra_fixture: &str, expect: Expect) {
889 let (analysis, range) = fixture::range(ra_fixture);
893 links_in_hover: false,
894 documentation: Some(HoverDocFormat::Markdown),
900 expect.assert_eq(hover.info.markup.as_str())
903 fn check_hover_range_no_results(ra_fixture: &str) {
904 let (analysis, range) = fixture::range(ra_fixture);
908 links_in_hover: false,
909 documentation: Some(HoverDocFormat::Markdown),
914 assert!(hover.is_none());
918 fn hover_shows_type_of_an_expression() {
921 pub fn foo() -> u32 { 1 }
924 let foo_test = foo()$0;
937 fn hover_remove_markdown_if_configured() {
938 check_hover_no_markdown(
940 pub fn foo() -> u32 { 1 }
943 let foo_test = foo()$0;
954 fn hover_shows_long_type_of_an_expression() {
957 struct Scan<A, B, C> { a: A, b: B, c: C }
958 struct Iter<I> { inner: I }
959 enum Option<T> { Some(T), None }
961 struct OtherStruct<T> { i: T }
963 fn scan<A, B, C>(a: A, b: B, c: C) -> Iter<Scan<OtherStruct<A>, B, C>> {
964 Iter { inner: Scan { a, b, c } }
969 let closure = |memo: &mut u32, value: &u32, _another: &mut u32| -> Option<u32> {
970 Option::Some(*memo + value)
973 let mut iter$0 = scan(OtherStruct { i: num }, closure, number);
980 let mut iter: Iter<Scan<OtherStruct<OtherStruct<i32>>, |&mut u32, &u32, &mut u32| -> Option<u32>, u32>>
987 fn hover_shows_fn_signature() {
988 // Single file with result
991 pub fn foo() -> u32 { 1 }
993 fn main() { let foo_test = fo$0o(); }
1008 // Multiple candidates but results are ambiguous.
1012 pub fn foo() -> u32 { 1 }
1015 pub fn foo() -> &str { "" }
1018 pub fn foo(a: u32, b: u32) {}
1025 fn main() { let foo_test = fo$0o(); }
1037 fn hover_shows_fn_signature_with_type_params() {
1040 pub fn foo<'a, T: AsRef<str>>(b: &'a T) -> &'a str { }
1042 fn main() { let foo_test = fo$0o(); }
1052 pub fn foo<'a, T>(b: &'a T) -> &'a str
1061 fn hover_shows_fn_signature_on_fn_name() {
1064 pub fn foo$0(a: u32, b: u32) -> u32 {}
1076 pub fn foo(a: u32, b: u32) -> u32
1083 fn hover_shows_fn_doc() {
1088 /// # use std::path::Path;
1090 /// foo(Path::new("hello, world!"))
1092 pub fn foo$0(_: &Path) {}
1104 pub fn foo(_: &Path)
1112 # use std::path::Path;
1114 foo(Path::new("hello, world!"))
1121 fn hover_shows_fn_doc_attr_raw_string() {
1124 #[doc = r#"Raw string doc attr"#]
1125 pub fn foo$0(_: &Path) {}
1137 pub fn foo(_: &Path)
1148 fn hover_shows_struct_field_info() {
1149 // Hovering over the field when instantiating
1152 struct Foo { field_a: u32 }
1155 let foo = Foo { field_a$0: 0, };
1171 // Hovering over the field in the definition
1174 struct Foo { field_a$0: u32 }
1177 let foo = Foo { field_a: 0 };
1195 fn hover_const_static() {
1197 r#"const foo$0: u32 = 123;"#,
1211 r#"static foo$0: u32 = 456;"#,
1227 fn hover_default_generic_types() {
1230 struct Test<K, T = u8> { k: K, t: T }
1233 let zz$0 = Test { t: 23u8, k: 33 };
1239 let zz: Test<i32, u8>
1249 enum Option<T> { Some(T) }
1252 fn main() { So$0me(12); }
1269 enum Option<T> { Some(T) }
1272 fn main() { let b$0ar = Some(12); }
1278 let bar: Option<i32>
1285 fn hover_enum_variant() {
1289 /// The None variant
1313 /// The Some variant
1317 let s = Option::Som$0e(12);
1339 fn hover_for_local_variable() {
1341 r#"fn func(foo: i32) { fo$0o; }"#,
1353 fn hover_for_local_variable_pat() {
1355 r#"fn func(fo$0o: i32) {}"#,
1367 fn hover_local_var_edge() {
1369 r#"fn func(foo: i32) { if true { $0foo; }; }"#,
1381 fn hover_for_param_edge() {
1383 r#"fn func($0foo: i32) {}"#,
1395 fn hover_for_param_with_multiple_traits() {
1400 type Target: ?Sized;
1403 type Target: ?Sized;
1405 fn f(_x$0: impl Deref<Target=u8> + DerefMut<Target=u8>) {}"#,
1410 _x: impl Deref<Target = u8> + DerefMut<Target = u8>
1417 fn test_hover_infer_associated_method_result() {
1420 struct Thing { x: u32 }
1423 fn new() -> Thing { Thing { x: 0 } }
1426 fn main() { let foo_$0test = Thing::new(); }
1439 fn test_hover_infer_associated_method_exact() {
1443 struct Thing { x: u32 }
1446 fn new() -> Thing { Thing { x: 0 } }
1450 fn main() { let foo_test = wrapper::Thing::new$0(); }
1456 test::wrapper::Thing
1467 fn test_hover_infer_associated_const_in_pattern() {
1498 fn test_hover_self() {
1501 struct Thing { x: u32 }
1503 fn new() -> Self { Self$0 { x: 0 } }
1520 struct Thing { x: u32 }
1522 fn new() -> Self$0 { Self { x: 0 } }
1541 pub fn new() -> Self$0 { Thing::A }
1560 pub fn thing(a: Self$0) {}
1578 fn test_hover_shadowing_pat() {
1599 fn test_hover_macro_invocation() {
1602 macro_rules! foo { () => {} }
1604 fn f() { fo$0o!(); }
1621 fn test_hover_macro2_invocation() {
1629 fn f() { fo$0o!(); }
1652 fn test_hover_tuple_field() {
1654 r#"struct TS(String, i32$0);"#,
1666 fn test_hover_through_macro() {
1669 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1672 fn bar() { fo$0o(); }
1690 fn test_hover_through_expr_in_macro() {
1693 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
1694 fn foo(bar:u32) { let a = id!(ba$0r); }
1707 fn test_hover_through_expr_in_macro_recursive() {
1710 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1711 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1712 fn foo(bar:u32) { let a = id!(ba$0r); }
1725 fn test_hover_through_func_in_macro_recursive() {
1728 macro_rules! id_deep { ($($tt:tt)*) => { $($tt)* } }
1729 macro_rules! id { ($($tt:tt)*) => { id_deep!($($tt)*) } }
1730 fn bar() -> u32 { 0 }
1731 fn foo() { let a = id!([0u32, bar($0)] ); }
1743 fn test_hover_through_literal_string_in_macro() {
1746 macro_rules! arr { ($($tt:tt)*) => { [$($tt)*)] } }
1748 let mastered_for_itunes = "";
1749 let _ = arr!("Tr$0acks", &mastered_for_itunes);
1762 fn test_hover_through_assert_macro() {
1765 #[rustc_builtin_macro]
1766 macro_rules! assert {}
1768 fn bar() -> bool { true }
1788 fn test_hover_through_literal_string_in_builtin_macro() {
1789 check_hover_no_result(
1791 #[rustc_builtin_macro]
1792 macro_rules! format {}
1795 format!("hel$0lo {}", 0);
1802 fn test_hover_non_ascii_space_doc() {
1805 /// <- `\u{3000}` here
1808 fn bar() { fo$0o(); }
1829 fn test_hover_function_show_qualifiers() {
1831 r#"async fn foo$0() {}"#,
1845 r#"pub const unsafe fn foo$0() {}"#,
1854 pub const unsafe fn foo()
1858 // Top level `pub(crate)` will be displayed as no visibility.
1860 r#"mod m { pub(crate) async unsafe extern "C" fn foo$0() {} }"#,
1869 pub(crate) async unsafe extern "C" fn foo()
1876 fn test_hover_trait_show_qualifiers() {
1878 r"unsafe trait foo$0() {}",
1895 fn test_hover_extern_crate() {
1898 //- /main.rs crate:main deps:std
1900 //- /std/lib.rs crate:std
1901 //! Standard library for this test
1915 Standard library for this test
1923 //- /main.rs crate:main deps:std
1924 extern crate std as ab$0c;
1925 //- /std/lib.rs crate:std
1926 //! Standard library for this test
1940 Standard library for this test
1949 fn test_hover_mod_with_same_name_as_function() {
1952 use self::m$0y::Bar;
1953 mod my { pub struct Bar; }
1972 fn test_hover_struct_doc_comment() {
1975 /// This is an example
1983 /// assert_eq!(6, my_crate::add_one(5));
1987 fn foo() { let bar = Ba$0r; }
2010 assert_eq!(6, my_crate::add_one(5));
2017 fn test_hover_struct_doc_attr() {
2023 fn foo() { let bar = Ba$0r; }
2044 fn test_hover_struct_doc_attr_multiple_and_mixed() {
2048 #[doc = "bar docs 1"]
2049 #[doc = "bar docs 2"]
2052 fn foo() { let bar = Ba$0r; }
2075 fn test_hover_external_url() {
2079 /// [external](https://www.google.com)
2095 [external](https://www.google.com)
2100 // Check that we don't rewrite links which we can't identify
2102 fn test_hover_unknown_target() {
2128 fn test_hover_no_links() {
2129 check_hover_no_links(
2132 /// case 1. bare URL: https://www.example.com/
2133 /// case 2. inline URL with title: [example](https://www.example.com/)
2134 /// case 3. code reference: [`Result`]
2135 /// case 4. code reference but miss footnote: [`String`]
2136 /// case 5. autolink: <http://www.example.com/>
2137 /// case 6. email address: <test@example.com>
2138 /// case 7. reference: [example][example]
2139 /// case 8. collapsed link: [example][]
2140 /// case 9. shortcut link: [example]
2141 /// case 10. inline without URL: [example]()
2142 /// case 11. reference: [foo][foo]
2143 /// case 12. reference: [foo][bar]
2144 /// case 13. collapsed link: [foo][]
2145 /// case 14. shortcut link: [foo]
2146 /// case 15. inline without URL: [foo]()
2147 /// case 16. just escaped text: \[foo]
2148 /// case 17. inline link: [Foo](foo::Foo)
2150 /// [`Result`]: ../../std/result/enum.Result.html
2151 /// [^example]: https://www.example.com/
2168 case 1. bare URL: https://www.example.com/
2169 case 2. inline URL with title: [example](https://www.example.com/)
2170 case 3. code reference: `Result`
2171 case 4. code reference but miss footnote: `String`
2172 case 5. autolink: http://www.example.com/
2173 case 6. email address: test@example.com
2174 case 7. reference: example
2175 case 8. collapsed link: example
2176 case 9. shortcut link: example
2177 case 10. inline without URL: example
2178 case 11. reference: foo
2179 case 12. reference: foo
2180 case 13. collapsed link: foo
2181 case 14. shortcut link: foo
2182 case 15. inline without URL: foo
2183 case 16. just escaped text: \[foo\]
2184 case 17. inline link: Foo
2186 [^example]: https://www.example.com/
2192 fn test_hover_macro_generated_struct_fn_doc_comment() {
2193 cov_mark::check!(hover_macro_generated_struct_fn_doc_comment);
2209 fn foo() { let bar = Bar; bar.fo$0o(); }
2230 fn test_hover_macro_generated_struct_fn_doc_attr() {
2231 cov_mark::check!(hover_macro_generated_struct_fn_doc_attr);
2239 #[doc = "Do the foo"]
2247 fn foo() { let bar = Bar; bar.fo$0o(); }
2268 fn test_hover_trait_has_impl_action() {
2270 r#"trait foo$0() {}"#,
2287 fn test_hover_struct_has_impl_action() {
2289 r"struct foo$0() {}",
2306 fn test_hover_union_has_impl_action() {
2308 r#"union foo$0() {}"#,
2325 fn test_hover_enum_has_impl_action() {
2327 r"enum foo$0() { A, B }",
2344 fn test_hover_self_has_impl_action() {
2346 r#"struct foo where Self$0:;"#,
2363 fn test_hover_test_has_action() {
2381 use_name_in_title: false,
2382 nav: NavigationTarget {
2387 focus_range: 11..19,
2408 fn test_hover_test_mod_has_action() {
2420 use_name_in_title: false,
2421 nav: NavigationTarget {
2429 description: "mod tests",
2443 fn test_hover_struct_has_goto_type_action() {
2448 fn main() { let s$0t = S{ f1:0 }; }
2455 mod_path: "test::S",
2456 nav: NavigationTarget {
2464 description: "struct S",
2475 fn test_hover_generic_struct_has_goto_type_actions() {
2479 struct S<T>{ f1: T }
2481 fn main() { let s$0t = S{ f1:Arg(0) }; }
2488 mod_path: "test::S",
2489 nav: NavigationTarget {
2494 focus_range: 24..25,
2497 description: "struct S<T>",
2501 mod_path: "test::Arg",
2502 nav: NavigationTarget {
2510 description: "struct Arg",
2521 fn test_hover_generic_struct_has_flattened_goto_type_actions() {
2525 struct S<T>{ f1: T }
2527 fn main() { let s$0t = S{ f1: S{ f1: Arg(0) } }; }
2534 mod_path: "test::S",
2535 nav: NavigationTarget {
2540 focus_range: 24..25,
2543 description: "struct S<T>",
2547 mod_path: "test::Arg",
2548 nav: NavigationTarget {
2556 description: "struct Arg",
2567 fn test_hover_tuple_has_goto_type_actions() {
2576 fn main() { let s$0t = (A(1), B(2), M::C(3) ); }
2583 mod_path: "test::A",
2584 nav: NavigationTarget {
2592 description: "struct A",
2596 mod_path: "test::B",
2597 nav: NavigationTarget {
2602 focus_range: 22..23,
2605 description: "struct B",
2609 mod_path: "test::M::C",
2610 nav: NavigationTarget {
2615 focus_range: 53..54,
2618 description: "pub struct C",
2629 fn test_hover_return_impl_trait_has_goto_type_action() {
2633 fn foo() -> impl Foo {}
2635 fn main() { let s$0t = foo(); }
2642 mod_path: "test::Foo",
2643 nav: NavigationTarget {
2651 description: "trait Foo",
2662 fn test_hover_generic_return_impl_trait_has_goto_type_action() {
2667 fn foo() -> impl Foo<S> {}
2669 fn main() { let s$0t = foo(); }
2676 mod_path: "test::Foo",
2677 nav: NavigationTarget {
2685 description: "trait Foo<T>",
2689 mod_path: "test::S",
2690 nav: NavigationTarget {
2695 focus_range: 23..24,
2698 description: "struct S",
2709 fn test_hover_return_impl_traits_has_goto_type_action() {
2714 fn foo() -> impl Foo + Bar {}
2716 fn main() { let s$0t = foo(); }
2723 mod_path: "test::Foo",
2724 nav: NavigationTarget {
2732 description: "trait Foo",
2736 mod_path: "test::Bar",
2737 nav: NavigationTarget {
2742 focus_range: 19..22,
2745 description: "trait Bar",
2756 fn test_hover_generic_return_impl_traits_has_goto_type_action() {
2764 fn foo() -> impl Foo<S1> + Bar<S2> {}
2766 fn main() { let s$0t = foo(); }
2773 mod_path: "test::Foo",
2774 nav: NavigationTarget {
2782 description: "trait Foo<T>",
2786 mod_path: "test::Bar",
2787 nav: NavigationTarget {
2792 focus_range: 22..25,
2795 description: "trait Bar<T>",
2799 mod_path: "test::S1",
2800 nav: NavigationTarget {
2805 focus_range: 39..41,
2808 description: "struct S1",
2812 mod_path: "test::S2",
2813 nav: NavigationTarget {
2818 focus_range: 52..54,
2821 description: "struct S2",
2832 fn test_hover_arg_impl_trait_has_goto_type_action() {
2836 fn foo(ar$0g: &impl Foo) {}
2843 mod_path: "test::Foo",
2844 nav: NavigationTarget {
2852 description: "trait Foo",
2863 fn test_hover_arg_impl_traits_has_goto_type_action() {
2870 fn foo(ar$0g: &impl Foo + Bar<S>) {}
2877 mod_path: "test::Foo",
2878 nav: NavigationTarget {
2886 description: "trait Foo",
2890 mod_path: "test::Bar",
2891 nav: NavigationTarget {
2896 focus_range: 19..22,
2899 description: "trait Bar<T>",
2903 mod_path: "test::S",
2904 nav: NavigationTarget {
2909 focus_range: 36..37,
2912 description: "struct S",
2923 fn test_hover_async_block_impl_trait_has_goto_type_action() {
2926 //- minicore: future
2929 let fo$0o = async { S };
2937 mod_path: "core::future::Future",
2938 nav: NavigationTarget {
2942 full_range: 254..436,
2943 focus_range: 293..299,
2946 description: "pub trait Future",
2950 mod_path: "test::S",
2951 nav: NavigationTarget {
2959 description: "struct S",
2970 fn test_hover_arg_generic_impl_trait_has_goto_type_action() {
2975 fn foo(ar$0g: &impl Foo<S>) {}
2982 mod_path: "test::Foo",
2983 nav: NavigationTarget {
2991 description: "trait Foo<T>",
2995 mod_path: "test::S",
2996 nav: NavigationTarget {
3001 focus_range: 23..24,
3004 description: "struct S",
3015 fn test_hover_dyn_return_has_goto_type_action() {
3023 fn foo() -> B<dyn Foo> {}
3025 fn main() { let s$0t = foo(); }
3032 mod_path: "test::B",
3033 nav: NavigationTarget {
3038 focus_range: 49..50,
3041 description: "struct B<T>",
3045 mod_path: "test::Foo",
3046 nav: NavigationTarget {
3054 description: "trait Foo",
3065 fn test_hover_dyn_arg_has_goto_type_action() {
3069 fn foo(ar$0g: &dyn Foo) {}
3076 mod_path: "test::Foo",
3077 nav: NavigationTarget {
3085 description: "trait Foo",
3096 fn test_hover_generic_dyn_arg_has_goto_type_action() {
3101 fn foo(ar$0g: &dyn Foo<S>) {}
3108 mod_path: "test::Foo",
3109 nav: NavigationTarget {
3117 description: "trait Foo<T>",
3121 mod_path: "test::S",
3122 nav: NavigationTarget {
3127 focus_range: 23..24,
3130 description: "struct S",
3141 fn test_hover_goto_type_action_links_order() {
3144 trait ImplTrait<T> {}
3145 trait DynTrait<T> {}
3149 fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
3156 mod_path: "test::ImplTrait",
3157 nav: NavigationTarget {
3165 description: "trait ImplTrait<T>",
3169 mod_path: "test::B",
3170 nav: NavigationTarget {
3175 focus_range: 50..51,
3178 description: "struct B<T>",
3182 mod_path: "test::DynTrait",
3183 nav: NavigationTarget {
3188 focus_range: 28..36,
3191 description: "trait DynTrait<T>",
3195 mod_path: "test::S",
3196 nav: NavigationTarget {
3201 focus_range: 65..66,
3204 description: "struct S",
3215 fn test_hover_associated_type_has_goto_type_action() {
3220 fn get(self) -> Self::Item {}
3226 impl Foo for S { type Item = Bar; }
3228 fn test() -> impl Foo { S {} }
3230 fn main() { let s$0t = test().get(); }
3237 mod_path: "test::Foo",
3238 nav: NavigationTarget {
3246 description: "trait Foo",
3257 fn test_hover_const_param_has_goto_type_action() {
3261 struct Foo<const BAR: Bar>;
3263 impl<const BAR: Bar> Foo<BAR$0> {}
3270 mod_path: "test::Bar",
3271 nav: NavigationTarget {
3279 description: "struct Bar",
3290 fn test_hover_type_param_has_goto_type_action() {
3295 fn foo<T: Foo>(t: T$0){}
3302 mod_path: "test::Foo",
3303 nav: NavigationTarget {
3311 description: "trait Foo",
3322 fn test_hover_self_has_go_to_type() {
3335 mod_path: "test::Foo",
3336 nav: NavigationTarget {
3344 description: "struct Foo",
3355 fn hover_displays_normalized_crate_names() {
3358 //- /lib.rs crate:name-with-dashes
3360 pub struct Thing { x: u32 }
3363 pub fn new() -> Thing { Thing { x: 0 } }
3367 //- /main.rs crate:main deps:name-with-dashes
3368 fn main() { let foo_test = name_with_dashes::wrapper::Thing::new$0(); }
3374 name_with_dashes::wrapper::Thing
3378 pub fn new() -> Thing
3385 fn hover_field_pat_shorthand_ref_match_ergonomics() {
3408 fn hover_self_param_shows_type() {
3427 fn hover_self_param_shows_type_for_arbitrary_self_type() {
3433 fn bar(sel$0f: Arc<Foo>) {}
3447 fn hover_doc_outer_inner() {
3454 /// This comment belongs to the function
3478 fn hover_doc_outer_inner_attribue() {
3481 #[doc = "Be quick;"]
3483 #![doc = "time is mana"]
3485 #[doc = "This comment belongs to the function"]
3509 fn hover_doc_block_style_indentend() {
3543 fn hover_comments_dont_highlight_parent() {
3544 cov_mark::check!(no_highlight_on_comment_hover);
3545 check_hover_no_result(
3573 fn hover_lifetime() {
3575 r#"fn foo<'lifetime>(_: &'lifetime$0 ()) {}"#,
3587 fn hover_type_param() {
3594 impl<T: Copy + Clone> Foo<T$0> where T: Sized {}
3617 // lifetimes bounds arent being tracked yet
3621 impl<T: 'static> Foo<T$0> {}
3634 fn hover_type_param_not_sized() {
3641 impl<T: Copy + Clone> Foo<T$0> where T: ?Sized {}
3647 T: Copy + Clone + ?Sized
3654 fn hover_const_param() {
3657 struct Foo<const LEN: usize>;
3658 impl<const LEN: usize> Foo<LEN$0> {}
3671 fn hover_const_pat() {
3675 const FOO: usize = 3;
3702 fn hover_mod_def() {
3729 fn hover_self_in_use() {
3732 //! This should not appear
3734 /// But this should appear
3737 use foo::bar::{self$0};
3752 But this should appear
3758 fn hover_keyword() {
3761 //- /main.rs crate:main deps:std
3762 fn f() { retur$0n; }
3763 //- /libstd.rs crate:std
3764 /// Docs for return_keyword
3765 mod return_keyword {}
3776 Docs for return_keyword
3782 fn hover_builtin() {
3785 //- /main.rs crate:main deps:std
3786 cosnt _: &str$0 = ""; }
3788 //- /libstd.rs crate:std
3789 /// Docs for prim_str
3807 fn hover_macro_expanded_function() {
3810 struct S<'a, T>(&'a T);
3814 fn bar<'t, T: Clone + 't>(s: &mut S<'t, T>, t: u32) -> *mut u32 where
3816 for<'a> T: Clone + 'a
3835 fn bar<'t, T>(s: &mut S<'t, T>, t: u32) -> *mut u32
3839 for<'a> T: Clone + 'a,
3846 fn hover_intra_doc_links() {
3851 /// This is the item. Cool!
3855 /// Gives you a [`TheItem$0`].
3857 /// [`TheItem`]: theitem::TheItem
3858 pub fn gimme() -> theitem::TheItem {
3875 This is the item. Cool!
3881 fn hover_generic_assoc() {
3884 fn foo<T: A>() where T::Assoc$0: {}
3904 let _: <T>::Assoc$0;
3944 fn string_shadowed_with_inner_items() {
3947 //- /main.rs crate:main deps:alloc
3949 /// Custom `String` type.
3958 //- /alloc.rs crate:alloc
3963 /// This is `alloc::String`.
3980 Custom `String` type.
3986 fn function_doesnt_shadow_crate_in_use_tree() {
3989 //- /main.rs crate:main deps:foo
3992 //- /foo.rs crate:foo
4006 fn hover_feature() {
4008 r#"#![feature(box_syntax$0)]"#,
4018 The tracking issue for this feature is: [#49733]
4020 [#49733]: https://github.com/rust-lang/rust/issues/49733
4022 See also [`box_patterns`](box-patterns.md)
4024 ------------------------
4026 Currently the only stable way to create a `Box` is via the `Box::new` method.
4027 Also it is not possible in stable Rust to destructure a `Box` in a match
4028 pattern. The unstable `box` keyword can be used to create a `Box`. An example
4032 #![feature(box_syntax)]
4046 r#"#![allow(arithmetic_overflow$0)]"#,
4048 *arithmetic_overflow*
4054 arithmetic operation overflows
4060 fn hover_clippy_lint() {
4062 r#"#![allow(clippy::almost_swapped$0)]"#,
4066 clippy::almost_swapped
4070 Checks for `foo = bar; bar = foo` sequences.
4076 fn hover_attr_path_qualifier() {
4077 cov_mark::check!(name_ref_classify_attr_path_qualifier);
4080 //- /foo.rs crate:foo
4082 //- /lib.rs crate:main.rs deps:foo
4113 use bar::{self as foo$0};
4156 fn hover_derive_input() {
4159 #[rustc_builtin_macro]
4179 #[rustc_builtin_macro]
4182 #[derive(foo::Copy$0)]
4200 fn hover_range_math() {
4203 fn f() { let expr = $01 + 2 * 3$0 }
4213 fn f() { let expr = 1 $0+ 2 * $03 }
4223 fn f() { let expr = 1 + $02 * 3$0 }
4233 fn hover_range_arrays() {
4236 fn f() { let expr = $0[1, 2, 3, 4]$0 }
4246 fn f() { let expr = [1, 2, $03, 4]$0 }
4256 fn f() { let expr = [1, 2, $03$0, 4] }
4266 fn hover_range_functions() {
4269 fn f<T>(a: &[T]) { }
4270 fn b() { $0f$0(&[1, 2, 3, 4, 5]); }
4280 fn f<T>(a: &[T]) { }
4281 fn b() { f($0&[1, 2, 3, 4, 5]$0); }
4291 fn hover_range_shows_nothing_when_invalid() {
4292 check_hover_range_no_results(
4294 fn f<T>(a: &[T]) { }
4295 fn b()$0 { f(&[1, 2, 3, 4, 5]); }$0
4299 check_hover_range_no_results(
4301 fn f<T>$0(a: &[T]) { }
4302 fn b() { f(&[1, 2, 3,$0 4, 5]); }
4306 check_hover_range_no_results(
4308 fn $0f() { let expr = [1, 2, 3, 4]$0 }
4314 fn hover_range_shows_unit_for_statements() {
4317 fn f<T>(a: &[T]) { }
4318 fn b() { $0f(&[1, 2, 3, 4, 5]); }$0
4328 fn f() { let expr$0 = $0[1, 2, 3, 4] }
4338 fn hover_range_for_pat() {
4365 fn hover_range_shows_coercions_if_applicable_expr() {
4369 let x: &u32 = $0&&&&&0$0;
4382 let x: *const u32 = $0&0$0;
4388 Coerced to: *const u32
4395 fn hover_range_shows_type_actions() {
4400 let x: &Foo = $0&&&&&Foo$0;
4408 mod_path: "test::Foo",
4409 nav: NavigationTarget {
4417 description: "struct Foo",
4428 fn hover_try_expr_res() {
4434 fn foo() -> Result<(), FooError> {
4435 Ok($0Result::<(), FooError>::Ok(())?$0)
4449 fn foo() -> Result<(), FooError> {
4450 Ok($0Result::<(), BarError>::Ok(())?$0)
4455 Try Error Type: BarError
4456 Propagated as: FooError
4463 fn hover_try_expr() {
4466 struct NotResult<T, U>(T, U);
4470 fn foo() -> NotResult<(), Looooong> {
4471 $0NotResult((), Short)?$0;
4476 Try Target Type: NotResult<(), Short>
4477 Propagated as: NotResult<(), Looooong>
4483 struct NotResult<T, U>(T, U);
4487 fn foo() -> NotResult<(), Short> {
4488 $0NotResult((), Looooong)?$0;
4493 Try Target Type: NotResult<(), Looooong>
4494 Propagated as: NotResult<(), Short>
4501 fn hover_try_expr_option() {
4502 cov_mark::check!(hover_try_expr_opt_opt);
4505 //- minicore: option, try
4507 fn foo() -> Option<()> {
4514 <Option<i32> as Try>::Output
4520 fn hover_deref_expr() {
4524 use core::ops::Deref;
4526 struct DerefExample<T> {
4530 impl<T> Deref for DerefExample<T> {
4533 fn deref(&self) -> &Self::Target {
4539 let x = DerefExample { value: 0 };
4540 let y: i32 = $0*x$0;
4546 Dereferenced from: DerefExample<i32>
4553 fn hover_deref_expr_with_coercion() {
4557 use core::ops::Deref;
4559 struct DerefExample<T> {
4563 impl<T> Deref for DerefExample<T> {
4566 fn deref(&self) -> &Self::Target {
4572 let x = DerefExample { value: &&&&&0 };
4573 let y: &i32 = $0*x$0;
4580 Dereferenced from: DerefExample<&&&&&i32>