1mod render;
2
3#[cfg(test)]
4mod tests;
5
6use std::{iter, ops::Not};
7
8use either::Either;
9use hir::{
10 DisplayTarget, GenericDef, GenericSubstitution, HasCrate, HasSource, LangItem, Semantics,
11};
12use ide_db::{
13 FileRange, FxIndexSet, MiniCore, Ranker, RootDatabase,
14 defs::{Definition, IdentClass, NameRefClass, OperatorClass},
15 famous_defs::FamousDefs,
16 helpers::pick_best_token,
17 ra_fixture::UpmapFromRaFixture,
18};
19use itertools::{Itertools, multizip};
20use macros::UpmapFromRaFixture;
21use span::{Edition, TextRange};
22use syntax::{
23 AstNode, AstToken,
24 SyntaxKind::{self, *},
25 SyntaxNode, T, ast,
26};
27
28use crate::{
29 Analysis, FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, TryToNav,
30 doc_links::token_as_doc_comment,
31 markdown_remove::remove_markdown,
32 markup::Markup,
33 navigation_target::UpmappingResult,
34 runnables::{runnable_fn, runnable_mod},
35};
36
37#[derive(Clone, Debug)]
38pub struct HoverConfig<'a> {
39 pub links_in_hover: bool,
40 pub memory_layout: Option<MemoryLayoutHoverConfig>,
41 pub documentation: bool,
42 pub keywords: bool,
43 pub format: HoverDocFormat,
44 pub max_trait_assoc_items_count: Option<usize>,
45 pub max_fields_count: Option<usize>,
46 pub max_enum_variants_count: Option<usize>,
47 pub max_subst_ty_len: SubstTyLen,
48 pub show_drop_glue: bool,
49 pub minicore: MiniCore<'a>,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub enum SubstTyLen {
54 Unlimited,
55 LimitTo(usize),
56 Hide,
57}
58
59#[derive(Copy, Clone, Debug, PartialEq, Eq)]
60pub struct MemoryLayoutHoverConfig {
61 pub size: Option<MemoryLayoutHoverRenderKind>,
62 pub offset: Option<MemoryLayoutHoverRenderKind>,
63 pub alignment: Option<MemoryLayoutHoverRenderKind>,
64 pub padding: Option<MemoryLayoutHoverRenderKind>,
65 pub niches: bool,
66}
67
68#[derive(Copy, Clone, Debug, PartialEq, Eq)]
69pub enum MemoryLayoutHoverRenderKind {
70 Decimal,
71 Hexadecimal,
72 Both,
73}
74
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub enum HoverDocFormat {
77 Markdown,
78 PlainText,
79}
80
81#[derive(Debug, Clone, Hash, PartialEq, Eq, UpmapFromRaFixture)]
82pub enum HoverAction {
83 Runnable(Runnable),
84 Implementation(FilePosition),
85 Reference(FilePosition),
86 GoToType(Vec<HoverGotoTypeData>),
87}
88
89impl HoverAction {
90 fn goto_type_from_targets(
91 sema: &Semantics<'_, RootDatabase>,
92 targets: Vec<hir::ModuleDef>,
93 edition: Edition,
94 ) -> Option<Self> {
95 let db = sema.db;
96 let targets = targets
97 .into_iter()
98 .filter_map(|it| {
99 Some(HoverGotoTypeData {
100 mod_path: render::path(
101 db,
102 it.module(db)?,
103 it.name(db).map(|name| name.display(db, edition).to_string()),
104 edition,
105 ),
106 nav: it.try_to_nav(sema)?.call_site(),
107 })
108 })
109 .collect::<Vec<_>>();
110 targets.is_empty().not().then_some(HoverAction::GoToType(targets))
111 }
112}
113
114#[derive(Debug, Clone, Eq, PartialEq, Hash, UpmapFromRaFixture)]
115pub struct HoverGotoTypeData {
116 pub mod_path: String,
117 pub nav: NavigationTarget,
118}
119
120#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, UpmapFromRaFixture)]
122pub struct HoverResult {
123 pub markup: Markup,
124 pub actions: Vec<HoverAction>,
125}
126
127pub(crate) fn hover(
134 db: &RootDatabase,
135 frange @ FileRange { file_id, range }: FileRange,
136 config: &HoverConfig<'_>,
137) -> Option<RangeInfo<HoverResult>> {
138 let sema = &hir::Semantics::new(db);
139 let file = sema.parse_guess_edition(file_id).syntax().clone();
140 let edition =
141 sema.attach_first_edition(file_id).map(|it| it.edition(db)).unwrap_or(Edition::CURRENT);
142 let display_target = sema.first_crate(file_id)?.to_display_target(db);
143 let mut res = if range.is_empty() {
144 hover_offset(
145 sema,
146 FilePosition { file_id, offset: range.start() },
147 file,
148 config,
149 edition,
150 display_target,
151 )
152 } else {
153 hover_ranged(sema, frange, file, config, edition, display_target)
154 }?;
155
156 if let HoverDocFormat::PlainText = config.format {
157 res.info.markup = remove_markdown(res.info.markup.as_str()).into();
158 }
159 Some(res)
160}
161
162#[allow(clippy::field_reassign_with_default)]
163fn hover_offset(
164 sema: &Semantics<'_, RootDatabase>,
165 FilePosition { file_id, offset }: FilePosition,
166 file: SyntaxNode,
167 config: &HoverConfig<'_>,
168 edition: Edition,
169 display_target: DisplayTarget,
170) -> Option<RangeInfo<HoverResult>> {
171 let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
172 IDENT
173 | INT_NUMBER
174 | LIFETIME_IDENT
175 | T![self]
176 | T![super]
177 | T![crate]
178 | T![Self]
179 | T![_] => 4,
180 T!['['] | T![']'] | T![?] | T![*] | T![-] | T![!] | T![|] => 3,
182 kind if kind.is_keyword(edition) => 2,
183 T!['('] | T![')'] => 2,
184 kind if kind.is_trivia() => 0,
185 _ => 1,
186 })?;
187
188 if let Some(doc_comment) = token_as_doc_comment(&original_token) {
189 cov_mark::hit!(no_highlight_on_comment_hover);
190 return doc_comment.get_definition_with_descend_at(sema, offset, |def, node, range| {
191 let res = hover_for_definition(
192 sema,
193 file_id,
194 def,
195 None,
196 &node,
197 None,
198 false,
199 config,
200 edition,
201 display_target,
202 );
203 Some(RangeInfo::new(range, res))
204 });
205 }
206
207 if let Some((range, _, _, resolution)) =
208 sema.check_for_format_args_template(original_token.clone(), offset)
209 {
210 let res = hover_for_definition(
211 sema,
212 file_id,
213 Definition::from(resolution?),
214 None,
215 &original_token.parent()?,
216 None,
217 false,
218 config,
219 edition,
220 display_target,
221 );
222 return Some(RangeInfo::new(range, res));
223 }
224
225 if let Some(literal) = ast::String::cast(original_token.clone())
226 && let Some((analysis, fixture_analysis)) =
227 Analysis::from_ra_fixture(sema, literal.clone(), &literal, config.minicore)
228 {
229 let (virtual_file_id, virtual_offset) = fixture_analysis.map_offset_down(offset)?;
230 return analysis
231 .hover(
232 config,
233 FileRange { file_id: virtual_file_id, range: TextRange::empty(virtual_offset) },
234 )
235 .ok()??
236 .upmap_from_ra_fixture(&fixture_analysis, virtual_file_id, file_id)
237 .ok();
238 }
239
240 let mut descended = sema.descend_into_macros(original_token.clone());
243
244 let ranker = Ranker::from_token(&original_token);
245
246 descended.sort_by_cached_key(|tok| !ranker.rank_token(tok));
247
248 let mut res = vec![];
249 for token in descended {
250 let is_same_kind = token.kind() == ranker.kind;
251 let lint_hover = (|| {
252 let attr = token.parent_ancestors().find_map(ast::Attr::cast)?;
254 render::try_for_lint(&attr, &token)
255 })();
256 if let Some(lint_hover) = lint_hover {
257 res.push(lint_hover);
258 continue;
259 }
260 let definitions = (|| {
261 Some(
262 'a: {
263 let node = token.parent()?;
264
265 if let Some(name) = ast::NameRef::cast(node.clone())
267 && let Some(path_seg) =
268 name.syntax().parent().and_then(ast::PathSegment::cast)
269 && let Some(macro_call) = path_seg
270 .parent_path()
271 .syntax()
272 .parent()
273 .and_then(ast::MacroCall::cast)
274 && let Some(macro_) = sema.resolve_macro_call(¯o_call) {
275 break 'a vec![(
276 (Definition::Macro(macro_), None),
277 sema.resolve_macro_call_arm(¯o_call),
278 false,
279 node,
280 )];
281 }
282
283 match IdentClass::classify_node(sema, &node)? {
284 IdentClass::Operator(OperatorClass::Await(_)) => return None,
287
288 IdentClass::NameRefClass(NameRefClass::ExternCrateShorthand {
289 decl,
290 ..
291 }) => {
292 vec![((Definition::ExternCrateDecl(decl), None), None, false, node)]
293 }
294
295 class => {
296 let render_extras = matches!(class, IdentClass::NameClass(_))
297 || ast::NameRef::cast(node.clone()).is_some_and(|name_ref| name_ref.token_kind() == SyntaxKind::SELF_TYPE_KW);
299 multizip((
300 class.definitions(),
301 iter::repeat(None),
302 iter::repeat(render_extras),
303 iter::repeat(node),
304 ))
305 .collect::<Vec<_>>()
306 }
307 }
308 }
309 .into_iter()
310 .unique_by(|&((def, _), _, _, _)| def)
311 .map(|((def, subst), macro_arm, hovered_definition, node)| {
312 hover_for_definition(
313 sema,
314 file_id,
315 def,
316 subst,
317 &node,
318 macro_arm,
319 hovered_definition,
320 config,
321 edition,
322 display_target,
323 )
324 })
325 .collect::<Vec<_>>(),
326 )
327 })();
328 if let Some(definitions) = definitions {
329 res.extend(definitions);
330 continue;
331 }
332 let keywords = || render::keyword(sema, config, &token, edition, display_target);
333 let underscore = || {
334 if !is_same_kind {
335 return None;
336 }
337 render::underscore(sema, config, &token, edition, display_target)
338 };
339 let rest_pat = || {
340 if !is_same_kind || token.kind() != DOT2 {
341 return None;
342 }
343
344 let rest_pat = token.parent().and_then(ast::RestPat::cast)?;
345 let record_pat_field_list =
346 rest_pat.syntax().parent().and_then(ast::RecordPatFieldList::cast)?;
347
348 let record_pat =
349 record_pat_field_list.syntax().parent().and_then(ast::RecordPat::cast)?;
350
351 Some(render::struct_rest_pat(sema, config, &record_pat, edition, display_target))
352 };
353 let call = || {
354 if !is_same_kind || token.kind() != T!['('] && token.kind() != T![')'] {
355 return None;
356 }
357 let arg_list = token.parent().and_then(ast::ArgList::cast)?.syntax().parent()?;
358 let call_expr = syntax::match_ast! {
359 match arg_list {
360 ast::CallExpr(expr) => expr.into(),
361 ast::MethodCallExpr(expr) => expr.into(),
362 _ => return None,
363 }
364 };
365 render::type_info_of(sema, config, &Either::Left(call_expr), edition, display_target)
366 };
367 let closure = || {
368 if !is_same_kind || token.kind() != T![|] {
369 return None;
370 }
371 let c = token.parent().and_then(|x| x.parent()).and_then(ast::ClosureExpr::cast)?;
372 render::closure_expr(sema, config, c, edition, display_target)
373 };
374 let literal = || {
375 render::literal(sema, original_token.clone(), display_target)
376 .map(|markup| HoverResult { markup, actions: vec![] })
377 };
378 if let Some(result) = keywords()
379 .or_else(underscore)
380 .or_else(rest_pat)
381 .or_else(call)
382 .or_else(closure)
383 .or_else(literal)
384 {
385 res.push(result)
386 }
387 }
388
389 res.into_iter()
390 .unique()
391 .reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
392 acc.actions.extend(actions);
393 acc.markup = Markup::from(format!("{}\n\n---\n{markup}", acc.markup));
394 acc
395 })
396 .map(|mut res: HoverResult| {
397 res.actions = dedupe_or_merge_hover_actions(res.actions);
398 RangeInfo::new(original_token.text_range(), res)
399 })
400}
401
402fn hover_ranged(
403 sema: &Semantics<'_, RootDatabase>,
404 FileRange { file_id, range }: FileRange,
405 file: SyntaxNode,
406 config: &HoverConfig<'_>,
407 edition: Edition,
408 display_target: DisplayTarget,
409) -> Option<RangeInfo<HoverResult>> {
410 let expr_or_pat = file
412 .covering_element(range)
413 .ancestors()
414 .take_while(|it| ast::MacroCall::can_cast(it.kind()) || !ast::Item::can_cast(it.kind()))
415 .find_map(Either::<ast::Expr, ast::Pat>::cast)?;
416 let res = match &expr_or_pat {
417 Either::Left(ast::Expr::TryExpr(try_expr)) => {
418 render::try_expr(sema, config, try_expr, edition, display_target)
419 }
420 Either::Left(ast::Expr::PrefixExpr(prefix_expr))
421 if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
422 {
423 render::deref_expr(sema, config, prefix_expr, edition, display_target)
424 }
425 Either::Left(ast::Expr::Literal(literal)) => {
426 if let Some(literal) = ast::String::cast(literal.token())
427 && let Some((analysis, fixture_analysis)) =
428 Analysis::from_ra_fixture(sema, literal.clone(), &literal, config.minicore)
429 {
430 let (virtual_file_id, virtual_range) = fixture_analysis.map_range_down(range)?;
431 return analysis
432 .hover(config, FileRange { file_id: virtual_file_id, range: virtual_range })
433 .ok()??
434 .upmap_from_ra_fixture(&fixture_analysis, virtual_file_id, file_id)
435 .ok();
436 }
437 None
438 }
439 _ => None,
440 };
441 let res =
442 res.or_else(|| render::type_info_of(sema, config, &expr_or_pat, edition, display_target));
443 res.map(|it| {
444 let range = match expr_or_pat {
445 Either::Left(it) => it.syntax().text_range(),
446 Either::Right(it) => it.syntax().text_range(),
447 };
448 RangeInfo::new(range, it)
449 })
450}
451
452pub(crate) fn hover_for_definition(
454 sema: &Semantics<'_, RootDatabase>,
455 file_id: FileId,
456 def: Definition,
457 subst: Option<GenericSubstitution<'_>>,
458 scope_node: &SyntaxNode,
459 macro_arm: Option<u32>,
460 render_extras: bool,
461 config: &HoverConfig<'_>,
462 edition: Edition,
463 display_target: DisplayTarget,
464) -> HoverResult {
465 let famous_defs = match &def {
466 Definition::BuiltinType(_) => sema.scope(scope_node).map(|it| FamousDefs(sema, it.krate())),
467 _ => None,
468 };
469
470 let db = sema.db;
471 let def_ty = match def {
472 Definition::Local(it) => Some(it.ty(db)),
473 Definition::GenericParam(hir::GenericParam::ConstParam(it)) => Some(it.ty(db)),
474 Definition::GenericParam(hir::GenericParam::TypeParam(it)) => Some(it.ty(db)),
475 Definition::Field(field) => Some(field.ty(db).to_type(db)),
476 Definition::TupleField(it) => Some(it.ty(db)),
477 Definition::Function(it) => Some(it.ty(db)),
478 Definition::Adt(it) => Some(it.ty(db)),
479 Definition::Const(it) => Some(it.ty(db)),
480 Definition::Static(it) => Some(it.ty(db)),
481 Definition::TypeAlias(it) => Some(it.ty(db)),
482 Definition::BuiltinType(it) => Some(it.ty(db)),
483 _ => None,
484 };
485 let notable_traits = def_ty.map(|ty| notable_traits(db, &ty)).unwrap_or_default();
486 let subst_types = subst.map(|subst| subst.types(db));
487
488 let (markup, range_map) = render::definition(
489 sema.db,
490 def,
491 famous_defs.as_ref(),
492 ¬able_traits,
493 macro_arm,
494 render_extras,
495 subst_types.as_ref(),
496 config,
497 edition,
498 display_target,
499 );
500 HoverResult {
501 markup: render::process_markup(sema.db, def, &markup, range_map, config),
502 actions: [
503 show_fn_references_action(sema, def),
504 show_implementations_action(sema, def),
505 runnable_action(sema, def, file_id),
506 goto_type_action_for_def(sema, def, ¬able_traits, subst_types, edition),
507 ]
508 .into_iter()
509 .flatten()
510 .collect(),
511 }
512}
513
514fn notable_traits<'db>(
515 db: &'db RootDatabase,
516 ty: &hir::Type<'db>,
517) -> Vec<(hir::Trait, Vec<(Option<hir::Type<'db>>, hir::Name)>)> {
518 if ty.is_unknown() {
519 return Vec::new();
522 }
523
524 ty.krate(db)
525 .notable_traits_in_deps(db)
526 .filter_map(move |&trait_| {
527 let trait_ = trait_.into();
528 ty.impls_trait(db, trait_, &[]).then(|| {
529 (
530 trait_,
531 trait_
532 .items(db)
533 .into_iter()
534 .filter_map(hir::AssocItem::as_type_alias)
535 .map(|alias| {
536 (ty.normalize_trait_assoc_type(db, &[], alias), alias.name(db))
537 })
538 .collect::<Vec<_>>(),
539 )
540 })
541 })
542 .sorted_by_cached_key(|(trait_, _)| trait_.name(db))
543 .collect::<Vec<_>>()
544}
545
546fn show_implementations_action(
547 sema: &Semantics<'_, RootDatabase>,
548 def: Definition,
549) -> Option<HoverAction> {
550 fn to_action(nav_target: NavigationTarget) -> HoverAction {
551 HoverAction::Implementation(FilePosition {
552 file_id: nav_target.file_id,
553 offset: nav_target.focus_or_full_range().start(),
554 })
555 }
556
557 let adt = match def {
558 Definition::Trait(it) => {
559 return it.try_to_nav(sema).map(UpmappingResult::call_site).map(to_action);
560 }
561 Definition::Adt(it) => Some(it),
562 Definition::SelfType(it) => it.self_ty(sema.db).as_adt(),
563 _ => None,
564 }?;
565 adt.try_to_nav(sema).map(UpmappingResult::call_site).map(to_action)
566}
567
568fn show_fn_references_action(
569 sema: &Semantics<'_, RootDatabase>,
570 def: Definition,
571) -> Option<HoverAction> {
572 match def {
573 Definition::Function(it) => {
574 it.try_to_nav(sema).map(UpmappingResult::call_site).map(|nav_target| {
575 HoverAction::Reference(FilePosition {
576 file_id: nav_target.file_id,
577 offset: nav_target.focus_or_full_range().start(),
578 })
579 })
580 }
581 _ => None,
582 }
583}
584
585fn runnable_action(
586 sema: &hir::Semantics<'_, RootDatabase>,
587 def: Definition,
588 file_id: FileId,
589) -> Option<HoverAction> {
590 match def {
591 Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
592 Definition::Function(func) => {
593 let src = func.source(sema.db)?;
594 if src.file_id.file_id().is_none_or(|f| f.file_id(sema.db) != file_id) {
595 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
596 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
597 return None;
598 }
599
600 runnable_fn(sema, func).map(HoverAction::Runnable)
601 }
602 _ => None,
603 }
604}
605
606fn goto_type_action_for_def(
607 sema: &Semantics<'_, RootDatabase>,
608 def: Definition,
609 notable_traits: &[(hir::Trait, Vec<(Option<hir::Type<'_>>, hir::Name)>)],
610 subst_types: Option<Vec<(hir::Symbol, hir::Type<'_>)>>,
611 edition: Edition,
612) -> Option<HoverAction> {
613 let db = sema.db;
614 let mut targets: Vec<hir::ModuleDef> = Vec::new();
615 let mut push_new_def = |item: hir::ModuleDef| {
616 if !targets.contains(&item) {
617 targets.push(item);
618 }
619 };
620
621 for &(trait_, ref assocs) in notable_traits {
622 push_new_def(trait_.into());
623 assocs.iter().filter_map(|(ty, _)| ty.as_ref()).for_each(|ty| {
624 walk_and_push_ty(db, ty, &mut push_new_def);
625 });
626 }
627
628 if let Ok(generic_def) = GenericDef::try_from(def) {
629 generic_def.type_or_const_params(db).into_iter().for_each(|it| {
630 walk_and_push_ty(db, &it.ty(db), &mut push_new_def);
631 });
632 }
633
634 let ty = match def {
635 Definition::Local(it) => Some(it.ty(db)),
636 Definition::Field(field) => Some(field.ty(db).to_type(db)),
637 Definition::TupleField(field) => Some(field.ty(db)),
638 Definition::Const(it) => Some(it.ty(db)),
639 Definition::Static(it) => Some(it.ty(db)),
640 Definition::Function(func) => {
641 for param in func.assoc_fn_params(db) {
642 walk_and_push_ty(db, param.ty(), &mut push_new_def);
643 }
644 Some(func.ret_type(db))
645 }
646 Definition::GenericParam(hir::GenericParam::ConstParam(it)) => Some(it.ty(db)),
647 Definition::GenericParam(hir::GenericParam::TypeParam(it)) => Some(it.ty(db)),
648 _ => None,
649 };
650 if let Some(ty) = ty {
651 walk_and_push_ty(db, &ty, &mut push_new_def);
652 }
653
654 if let Some(subst_types) = subst_types {
655 for (_, ty) in subst_types {
656 walk_and_push_ty(db, &ty, &mut push_new_def);
657 }
658 }
659
660 HoverAction::goto_type_from_targets(sema, targets, edition)
661}
662
663fn walk_and_push_ty(
664 db: &RootDatabase,
665 ty: &hir::Type<'_>,
666 push_new_def: &mut dyn FnMut(hir::ModuleDef),
667) {
668 ty.walk(db, |t| {
669 if let Some(adt) = t.as_adt() {
670 push_new_def(adt.into());
671 } else if let Some(trait_) = t.as_dyn_trait() {
672 push_new_def(trait_.into());
673 } else if let Some(traits) = t.as_impl_traits(db) {
674 traits.for_each(|it| push_new_def(it.into()));
675 } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
676 push_new_def(trait_.into());
677 } else if let Some(tp) = t.as_type_param(db) {
678 let sized_trait = LangItem::Sized.resolve_trait(db, t.krate(db).into());
679 tp.trait_bounds(db)
680 .into_iter()
681 .filter(|&it| Some(it.into()) != sized_trait)
682 .for_each(|it| push_new_def(it.into()));
683 }
684 });
685}
686
687fn dedupe_or_merge_hover_actions(actions: Vec<HoverAction>) -> Vec<HoverAction> {
688 let mut deduped_actions = Vec::with_capacity(actions.len());
689 let mut go_to_type_targets = FxIndexSet::default();
690
691 let mut seen_implementation = false;
692 let mut seen_reference = false;
693 let mut seen_runnable = false;
694 for action in actions {
695 match action {
696 HoverAction::GoToType(targets) => {
697 go_to_type_targets.extend(targets);
698 }
699 HoverAction::Implementation(..) => {
700 if !seen_implementation {
701 seen_implementation = true;
702 deduped_actions.push(action);
703 }
704 }
705 HoverAction::Reference(..) => {
706 if !seen_reference {
707 seen_reference = true;
708 deduped_actions.push(action);
709 }
710 }
711 HoverAction::Runnable(..) => {
712 if !seen_runnable {
713 seen_runnable = true;
714 deduped_actions.push(action);
715 }
716 }
717 };
718 }
719
720 if !go_to_type_targets.is_empty() {
721 deduped_actions.push(HoverAction::GoToType(
722 go_to_type_targets.into_iter().sorted_by(|a, b| a.mod_path.cmp(&b.mod_path)).collect(),
723 ));
724 }
725
726 deduped_actions
727}