Skip to main content

ide/
hover.rs

1mod render;
2
3#[cfg(test)]
4mod tests;
5
6use std::{iter, ops::Not};
7
8use either::Either;
9use hir::{DisplayTarget, GenericDef, GenericSubstitution, HasCrate, HasSource, Semantics};
10use ide_db::{
11    FileRange, FxIndexSet, Ranker, RootDatabase,
12    defs::{Definition, IdentClass, NameRefClass, OperatorClass},
13    famous_defs::FamousDefs,
14    helpers::pick_best_token,
15    ra_fixture::{RaFixtureConfig, UpmapFromRaFixture},
16};
17use itertools::{Itertools, multizip};
18use macros::UpmapFromRaFixture;
19use span::{Edition, TextRange};
20use syntax::{
21    AstNode, AstToken,
22    SyntaxKind::{self, *},
23    SyntaxNode, T, ast,
24};
25
26use crate::{
27    Analysis, FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, TryToNav,
28    doc_links::token_as_doc_comment,
29    markdown_remove::remove_markdown,
30    markup::Markup,
31    navigation_target::UpmappingResult,
32    runnables::{runnable_fn, runnable_mod},
33};
34
35#[derive(Clone, Debug)]
36pub struct HoverConfig<'a> {
37    pub links_in_hover: bool,
38    pub memory_layout: Option<MemoryLayoutHoverConfig>,
39    pub documentation: bool,
40    pub keywords: bool,
41    pub format: HoverDocFormat,
42    pub max_trait_assoc_items_count: Option<usize>,
43    pub max_fields_count: Option<usize>,
44    pub max_enum_variants_count: Option<usize>,
45    pub max_subst_ty_len: SubstTyLen,
46    pub show_drop_glue: bool,
47    pub ra_fixture: RaFixtureConfig<'a>,
48}
49
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub enum SubstTyLen {
52    Unlimited,
53    LimitTo(usize),
54    Hide,
55}
56
57#[derive(Copy, Clone, Debug, PartialEq, Eq)]
58pub struct MemoryLayoutHoverConfig {
59    pub size: Option<MemoryLayoutHoverRenderKind>,
60    pub offset: Option<MemoryLayoutHoverRenderKind>,
61    pub alignment: Option<MemoryLayoutHoverRenderKind>,
62    pub padding: Option<MemoryLayoutHoverRenderKind>,
63    pub niches: bool,
64}
65
66#[derive(Copy, Clone, Debug, PartialEq, Eq)]
67pub enum MemoryLayoutHoverRenderKind {
68    Decimal,
69    Hexadecimal,
70    Both,
71}
72
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub enum HoverDocFormat {
75    Markdown,
76    PlainText,
77}
78
79#[derive(Debug, Clone, Hash, PartialEq, Eq, UpmapFromRaFixture)]
80pub enum HoverAction {
81    Runnable(Runnable),
82    Implementation(FilePosition),
83    Reference(FilePosition),
84    GoToType(Vec<HoverGotoTypeData>),
85}
86
87impl HoverAction {
88    fn goto_type_from_targets(
89        sema: &Semantics<'_, RootDatabase>,
90        targets: Vec<hir::ModuleDef>,
91        edition: Edition,
92    ) -> Option<Self> {
93        let db = sema.db;
94        let targets = targets
95            .into_iter()
96            .filter_map(|it| {
97                Some(HoverGotoTypeData {
98                    mod_path: render::path(
99                        db,
100                        it.module(db)?,
101                        it.name(db).map(|name| name.display(db, edition).to_string()),
102                        edition,
103                    ),
104                    nav: it.try_to_nav(sema)?.call_site(),
105                })
106            })
107            .collect::<Vec<_>>();
108        targets.is_empty().not().then_some(HoverAction::GoToType(targets))
109    }
110}
111
112#[derive(Debug, Clone, Eq, PartialEq, Hash, UpmapFromRaFixture)]
113pub struct HoverGotoTypeData {
114    pub mod_path: String,
115    pub nav: NavigationTarget,
116}
117
118/// Contains the results when hovering over an item
119#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, UpmapFromRaFixture)]
120pub struct HoverResult {
121    pub markup: Markup,
122    pub actions: Vec<HoverAction>,
123}
124
125// Feature: Hover
126//
127// Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
128// Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
129//
130// ![Hover](https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif)
131pub(crate) fn hover(
132    db: &RootDatabase,
133    frange @ FileRange { file_id, range }: FileRange,
134    config: &HoverConfig<'_>,
135) -> Option<RangeInfo<HoverResult>> {
136    let sema = &hir::Semantics::new(db);
137    let file = sema.parse_guess_edition(file_id).syntax().clone();
138    let edition = sema.attach_first_edition(file_id).edition(db);
139    let display_target = sema.first_crate(file_id)?.to_display_target(db);
140    let mut res = if range.is_empty() {
141        hover_offset(
142            sema,
143            FilePosition { file_id, offset: range.start() },
144            file,
145            config,
146            edition,
147            display_target,
148        )
149    } else {
150        hover_ranged(sema, frange, file, config, edition, display_target)
151    }?;
152
153    if let HoverDocFormat::PlainText = config.format {
154        res.info.markup = remove_markdown(res.info.markup.as_str()).into();
155    }
156    Some(res)
157}
158
159fn hover_offset(
160    sema: &Semantics<'_, RootDatabase>,
161    FilePosition { file_id, offset }: FilePosition,
162    file: SyntaxNode,
163    config: &HoverConfig<'_>,
164    edition: Edition,
165    display_target: DisplayTarget,
166) -> Option<RangeInfo<HoverResult>> {
167    let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
168        IDENT
169        | INT_NUMBER
170        | LIFETIME_IDENT
171        | T![self]
172        | T![super]
173        | T![crate]
174        | T![Self]
175        | T![_] => 4,
176        // index and prefix ops and closure pipe
177        T!['['] | T![']'] | T![?] | T![*] | T![-] | T![!] | T![|] => 3,
178        kind if kind.is_keyword(edition) => 2,
179        T!['('] | T![')'] => 2,
180        kind if kind.is_trivia() => 0,
181        _ => 1,
182    })?;
183
184    if ast::Comment::can_cast(original_token.kind()) {
185        cov_mark::hit!(no_highlight_on_comment_hover);
186        return None;
187    }
188
189    if let Some(doc_comment) = token_as_doc_comment(&original_token) {
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.ra_fixture)
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    // prefer descending the same token kind in attribute expansions, in normal macros text
241    // equivalency is more important
242    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            // FIXME: Definition should include known lints and the like instead of having this special case here
253            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                    // special case macro calls, we wanna render the invoked arm index
266                    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(&macro_call) {
275                                    break 'a vec![(
276                                        (Definition::Macro(macro_), None),
277                                        sema.resolve_macro_call_arm(&macro_call),
278                                        false,
279                                        node,
280                                    )];
281                                }
282
283                    match IdentClass::classify_node(sema, &node)? {
284                        // It's better for us to fall back to the keyword hover here,
285                        // rendering poll is very confusing
286                        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                                // Render extra information for `Self` keyword as well
298                                || 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    // FIXME: make this work in attributes
411    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.ra_fixture)
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
452// FIXME: Why is this pub(crate)?
453pub(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)),
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    let render_private_fields = sema.scope(scope_node).is_some_and(|scope| {
488        def.krate(db)
489            .is_some_and(|def_crate| should_render_private_fields(db, def_crate, scope.krate()))
490    });
491
492    let (markup, range_map) = render::definition(
493        sema.db,
494        def,
495        famous_defs.as_ref(),
496        &notable_traits,
497        macro_arm,
498        render_extras,
499        render_private_fields,
500        subst_types.as_ref(),
501        config,
502        edition,
503        display_target,
504    );
505    HoverResult {
506        markup: render::process_markup(sema.db, def, &markup, range_map, config),
507        actions: [
508            show_fn_references_action(sema, def),
509            show_implementations_action(sema, def),
510            runnable_action(sema, def, file_id),
511            goto_type_action_for_def(sema, def, &notable_traits, subst_types, edition),
512        ]
513        .into_iter()
514        .flatten()
515        .collect(),
516    }
517}
518
519/// | Hover location | Definition location | Render private fields? |
520/// |---|---:|---:|
521/// | Workspace crate | Workspace crate | Yes |
522/// | Workspace crate | External/library crate | No |
523/// | External/library crate | Same external/library crate | Yes |
524/// | External/library crate | Different external/library crate | No |
525/// | Anywhere | Same crate as definition | Yes |
526fn should_render_private_fields(
527    db: &RootDatabase,
528    def_crate: hir::Crate,
529    hover_crate: hir::Crate,
530) -> bool {
531    let is_workspace_crate = |db: &RootDatabase, krate: hir::Crate| {
532        let origin = krate.origin(db);
533        !origin.is_lib() && !origin.is_lang()
534    };
535
536    def_crate == hover_crate
537        || is_workspace_crate(db, def_crate) && is_workspace_crate(db, hover_crate)
538}
539
540fn notable_traits<'db>(
541    db: &'db RootDatabase,
542    ty: &hir::Type<'db>,
543) -> Vec<(hir::Trait, Vec<(Option<hir::Type<'db>>, hir::Name)>)> {
544    if ty.is_unknown() {
545        // The trait solver returns "yes" to the question whether the error type
546        // impls any trait, and we don't want to show it as having any notable trait.
547        return Vec::new();
548    }
549
550    ty.krate(db)
551        .notable_traits_in_deps(db)
552        .filter_map(move |&trait_| {
553            let trait_ = trait_.into();
554            ty.impls_trait(db, trait_, &[]).then(|| {
555                (
556                    trait_,
557                    trait_
558                        .items(db)
559                        .into_iter()
560                        .filter_map(hir::AssocItem::as_type_alias)
561                        .map(|alias| {
562                            (ty.normalize_trait_assoc_type(db, &[], alias), alias.name(db))
563                        })
564                        .collect::<Vec<_>>(),
565                )
566            })
567        })
568        .sorted_by_cached_key(|(trait_, _)| trait_.name(db))
569        .collect::<Vec<_>>()
570}
571
572fn show_implementations_action(
573    sema: &Semantics<'_, RootDatabase>,
574    def: Definition<'_>,
575) -> Option<HoverAction> {
576    fn to_action(nav_target: NavigationTarget) -> HoverAction {
577        HoverAction::Implementation(FilePosition {
578            file_id: nav_target.file_id,
579            offset: nav_target.focus_or_full_range().start(),
580        })
581    }
582
583    let adt = match def {
584        Definition::Trait(it) => {
585            return it.try_to_nav(sema).map(UpmappingResult::call_site).map(to_action);
586        }
587        Definition::Adt(it) => Some(it),
588        Definition::SelfType(it) => it.self_ty(sema.db).as_adt(),
589        _ => None,
590    }?;
591    adt.try_to_nav(sema).map(UpmappingResult::call_site).map(to_action)
592}
593
594fn show_fn_references_action(
595    sema: &Semantics<'_, RootDatabase>,
596    def: Definition<'_>,
597) -> Option<HoverAction> {
598    match def {
599        Definition::Function(it) => {
600            it.try_to_nav(sema).map(UpmappingResult::call_site).map(|nav_target| {
601                HoverAction::Reference(FilePosition {
602                    file_id: nav_target.file_id,
603                    offset: nav_target.focus_or_full_range().start(),
604                })
605            })
606        }
607        _ => None,
608    }
609}
610
611fn runnable_action(
612    sema: &hir::Semantics<'_, RootDatabase>,
613    def: Definition<'_>,
614    file_id: FileId,
615) -> Option<HoverAction> {
616    match def {
617        Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
618        Definition::Function(func) => {
619            let src = func.source(sema.db)?;
620            if src.file_id.file_id().is_none_or(|f| f.file_id(sema.db) != file_id) {
621                cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
622                cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
623                return None;
624            }
625
626            runnable_fn(sema, func).map(HoverAction::Runnable)
627        }
628        _ => None,
629    }
630}
631
632fn goto_type_action_for_def(
633    sema: &Semantics<'_, RootDatabase>,
634    def: Definition<'_>,
635    notable_traits: &[(hir::Trait, Vec<(Option<hir::Type<'_>>, hir::Name)>)],
636    subst_types: Option<Vec<(hir::Symbol, hir::Type<'_>)>>,
637    edition: Edition,
638) -> Option<HoverAction> {
639    let db = sema.db;
640    let mut targets: Vec<hir::ModuleDef> = Vec::new();
641    let mut push_new_def = |item: hir::ModuleDef| {
642        if !targets.contains(&item) {
643            targets.push(item);
644        }
645    };
646
647    for &(trait_, ref assocs) in notable_traits {
648        push_new_def(trait_.into());
649        assocs.iter().filter_map(|(ty, _)| ty.as_ref()).for_each(|ty| {
650            walk_and_push_ty(db, ty, &mut push_new_def);
651        });
652    }
653
654    if let Ok(generic_def) = GenericDef::try_from(def) {
655        generic_def.type_or_const_params(db).into_iter().for_each(|it| {
656            walk_and_push_ty(db, &it.ty(db), &mut push_new_def);
657        });
658    }
659
660    let ty = match def {
661        Definition::Local(it) => Some(it.ty(db)),
662        Definition::Field(field) => Some(field.ty(db)),
663        Definition::TupleField(field) => Some(field.ty(db)),
664        Definition::Const(it) => Some(it.ty(db)),
665        Definition::Static(it) => Some(it.ty(db)),
666        Definition::Function(func) => {
667            for param in func.assoc_fn_params(db) {
668                walk_and_push_ty(db, param.ty(), &mut push_new_def);
669            }
670            Some(func.ret_type(db))
671        }
672        Definition::GenericParam(hir::GenericParam::ConstParam(it)) => Some(it.ty(db)),
673        Definition::GenericParam(hir::GenericParam::TypeParam(it)) => Some(it.ty(db)),
674        _ => None,
675    };
676    if let Some(ty) = ty {
677        walk_and_push_ty(db, &ty, &mut push_new_def);
678    }
679
680    if let Some(subst_types) = subst_types {
681        for (_, ty) in subst_types {
682            walk_and_push_ty(db, &ty, &mut push_new_def);
683        }
684    }
685
686    HoverAction::goto_type_from_targets(sema, targets, edition)
687}
688
689fn walk_and_push_ty(
690    db: &RootDatabase,
691    ty: &hir::Type<'_>,
692    push_new_def: &mut dyn FnMut(hir::ModuleDef),
693) {
694    ty.walk(db, |t| {
695        if let Some(adt) = t.as_adt() {
696            push_new_def(adt.into());
697        } else if let Some(trait_) = t.as_dyn_trait() {
698            push_new_def(trait_.into());
699        } else if let Some(traits) = t.as_impl_traits(db) {
700            traits.for_each(|it| push_new_def(it.into()));
701        } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
702            push_new_def(trait_.into());
703        } else if let Some(tp) = t.as_type_param(db) {
704            let sized_trait = hir::Trait::lang(db, t.krate(db), hir::LangItem::Sized);
705            tp.trait_bounds(db)
706                .into_iter()
707                .filter(|&it| Some(it) != sized_trait)
708                .for_each(|it| push_new_def(it.into()));
709        }
710    });
711}
712
713fn dedupe_or_merge_hover_actions(actions: Vec<HoverAction>) -> Vec<HoverAction> {
714    let mut deduped_actions = Vec::with_capacity(actions.len());
715    let mut go_to_type_targets = FxIndexSet::default();
716
717    let mut seen_implementation = false;
718    let mut seen_reference = false;
719    let mut seen_runnable = false;
720    for action in actions {
721        match action {
722            HoverAction::GoToType(targets) => {
723                go_to_type_targets.extend(targets);
724            }
725            HoverAction::Implementation(..) => {
726                if !seen_implementation {
727                    seen_implementation = true;
728                    deduped_actions.push(action);
729                }
730            }
731            HoverAction::Reference(..) => {
732                if !seen_reference {
733                    seen_reference = true;
734                    deduped_actions.push(action);
735                }
736            }
737            HoverAction::Runnable(..) => {
738                if !seen_runnable {
739                    seen_runnable = true;
740                    deduped_actions.push(action);
741                }
742            }
743        };
744    }
745
746    if !go_to_type_targets.is_empty() {
747        deduped_actions.push(HoverAction::GoToType(
748            go_to_type_targets.into_iter().sorted_by(|a, b| a.mod_path.cmp(&b.mod_path)).collect(),
749        ));
750    }
751
752    deduped_actions
753}