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
159#[allow(clippy::field_reassign_with_default)]
160fn hover_offset(
161    sema: &Semantics<'_, RootDatabase>,
162    FilePosition { file_id, offset }: FilePosition,
163    file: SyntaxNode,
164    config: &HoverConfig<'_>,
165    edition: Edition,
166    display_target: DisplayTarget,
167) -> Option<RangeInfo<HoverResult>> {
168    let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
169        IDENT
170        | INT_NUMBER
171        | LIFETIME_IDENT
172        | T![self]
173        | T![super]
174        | T![crate]
175        | T![Self]
176        | T![_] => 4,
177        // index and prefix ops and closure pipe
178        T!['['] | T![']'] | T![?] | T![*] | T![-] | T![!] | T![|] => 3,
179        kind if kind.is_keyword(edition) => 2,
180        T!['('] | T![')'] => 2,
181        kind if kind.is_trivia() => 0,
182        _ => 1,
183    })?;
184
185    if ast::Comment::can_cast(original_token.kind()) {
186        cov_mark::hit!(no_highlight_on_comment_hover);
187        return None;
188    }
189
190    if let Some(doc_comment) = token_as_doc_comment(&original_token) {
191        return doc_comment.get_definition_with_descend_at(sema, offset, |def, node, range| {
192            let res = hover_for_definition(
193                sema,
194                file_id,
195                def,
196                None,
197                &node,
198                None,
199                false,
200                config,
201                edition,
202                display_target,
203            );
204            Some(RangeInfo::new(range, res))
205        });
206    }
207
208    if let Some((range, _, _, resolution)) =
209        sema.check_for_format_args_template(original_token.clone(), offset)
210    {
211        let res = hover_for_definition(
212            sema,
213            file_id,
214            Definition::from(resolution?),
215            None,
216            &original_token.parent()?,
217            None,
218            false,
219            config,
220            edition,
221            display_target,
222        );
223        return Some(RangeInfo::new(range, res));
224    }
225
226    if let Some(literal) = ast::String::cast(original_token.clone())
227        && let Some((analysis, fixture_analysis)) =
228            Analysis::from_ra_fixture(sema, literal.clone(), &literal, &config.ra_fixture)
229    {
230        let (virtual_file_id, virtual_offset) = fixture_analysis.map_offset_down(offset)?;
231        return analysis
232            .hover(
233                config,
234                FileRange { file_id: virtual_file_id, range: TextRange::empty(virtual_offset) },
235            )
236            .ok()??
237            .upmap_from_ra_fixture(&fixture_analysis, virtual_file_id, file_id)
238            .ok();
239    }
240
241    // prefer descending the same token kind in attribute expansions, in normal macros text
242    // equivalency is more important
243    let mut descended = sema.descend_into_macros(original_token.clone());
244
245    let ranker = Ranker::from_token(&original_token);
246
247    descended.sort_by_cached_key(|tok| !ranker.rank_token(tok));
248
249    let mut res = vec![];
250    for token in descended {
251        let is_same_kind = token.kind() == ranker.kind;
252        let lint_hover = (|| {
253            // FIXME: Definition should include known lints and the like instead of having this special case here
254            let attr = token.parent_ancestors().find_map(ast::Attr::cast)?;
255            render::try_for_lint(&attr, &token)
256        })();
257        if let Some(lint_hover) = lint_hover {
258            res.push(lint_hover);
259            continue;
260        }
261        let definitions = (|| {
262            Some(
263                'a: {
264                    let node = token.parent()?;
265
266                    // special case macro calls, we wanna render the invoked arm index
267                    if let Some(name) = ast::NameRef::cast(node.clone())
268                        && let Some(path_seg) =
269                            name.syntax().parent().and_then(ast::PathSegment::cast)
270                            && let Some(macro_call) = path_seg
271                                .parent_path()
272                                .syntax()
273                                .parent()
274                                .and_then(ast::MacroCall::cast)
275                                && let Some(macro_) = sema.resolve_macro_call(&macro_call) {
276                                    break 'a vec![(
277                                        (Definition::Macro(macro_), None),
278                                        sema.resolve_macro_call_arm(&macro_call),
279                                        false,
280                                        node,
281                                    )];
282                                }
283
284                    match IdentClass::classify_node(sema, &node)? {
285                        // It's better for us to fall back to the keyword hover here,
286                        // rendering poll is very confusing
287                        IdentClass::Operator(OperatorClass::Await(_)) => return None,
288
289                        IdentClass::NameRefClass(NameRefClass::ExternCrateShorthand {
290                            decl,
291                            ..
292                        }) => {
293                            vec![((Definition::ExternCrateDecl(decl), None), None, false, node)]
294                        }
295
296                        class => {
297                            let render_extras = matches!(class, IdentClass::NameClass(_))
298                                // Render extra information for `Self` keyword as well
299                                || ast::NameRef::cast(node.clone()).is_some_and(|name_ref| name_ref.token_kind() == SyntaxKind::SELF_TYPE_KW);
300                            multizip((
301                                class.definitions(),
302                                iter::repeat(None),
303                                iter::repeat(render_extras),
304                                iter::repeat(node),
305                            ))
306                            .collect::<Vec<_>>()
307                        }
308                    }
309                }
310                .into_iter()
311                .unique_by(|&((def, _), _, _, _)| def)
312                .map(|((def, subst), macro_arm, hovered_definition, node)| {
313                    hover_for_definition(
314                        sema,
315                        file_id,
316                        def,
317                        subst,
318                        &node,
319                        macro_arm,
320                        hovered_definition,
321                        config,
322                        edition,
323                        display_target,
324                    )
325                })
326                .collect::<Vec<_>>(),
327            )
328        })();
329        if let Some(definitions) = definitions {
330            res.extend(definitions);
331            continue;
332        }
333        let keywords = || render::keyword(sema, config, &token, edition, display_target);
334        let underscore = || {
335            if !is_same_kind {
336                return None;
337            }
338            render::underscore(sema, config, &token, edition, display_target)
339        };
340        let rest_pat = || {
341            if !is_same_kind || token.kind() != DOT2 {
342                return None;
343            }
344
345            let rest_pat = token.parent().and_then(ast::RestPat::cast)?;
346            let record_pat_field_list =
347                rest_pat.syntax().parent().and_then(ast::RecordPatFieldList::cast)?;
348
349            let record_pat =
350                record_pat_field_list.syntax().parent().and_then(ast::RecordPat::cast)?;
351
352            Some(render::struct_rest_pat(sema, config, &record_pat, edition, display_target))
353        };
354        let call = || {
355            if !is_same_kind || token.kind() != T!['('] && token.kind() != T![')'] {
356                return None;
357            }
358            let arg_list = token.parent().and_then(ast::ArgList::cast)?.syntax().parent()?;
359            let call_expr = syntax::match_ast! {
360                match arg_list {
361                    ast::CallExpr(expr) => expr.into(),
362                    ast::MethodCallExpr(expr) => expr.into(),
363                    _ => return None,
364                }
365            };
366            render::type_info_of(sema, config, &Either::Left(call_expr), edition, display_target)
367        };
368        let closure = || {
369            if !is_same_kind || token.kind() != T![|] {
370                return None;
371            }
372            let c = token.parent().and_then(|x| x.parent()).and_then(ast::ClosureExpr::cast)?;
373            render::closure_expr(sema, config, c, edition, display_target)
374        };
375        let literal = || {
376            render::literal(sema, original_token.clone(), display_target)
377                .map(|markup| HoverResult { markup, actions: vec![] })
378        };
379        if let Some(result) = keywords()
380            .or_else(underscore)
381            .or_else(rest_pat)
382            .or_else(call)
383            .or_else(closure)
384            .or_else(literal)
385        {
386            res.push(result)
387        }
388    }
389
390    res.into_iter()
391        .unique()
392        .reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
393            acc.actions.extend(actions);
394            acc.markup = Markup::from(format!("{}\n\n---\n{markup}", acc.markup));
395            acc
396        })
397        .map(|mut res: HoverResult| {
398            res.actions = dedupe_or_merge_hover_actions(res.actions);
399            RangeInfo::new(original_token.text_range(), res)
400        })
401}
402
403fn hover_ranged(
404    sema: &Semantics<'_, RootDatabase>,
405    FileRange { file_id, range }: FileRange,
406    file: SyntaxNode,
407    config: &HoverConfig<'_>,
408    edition: Edition,
409    display_target: DisplayTarget,
410) -> Option<RangeInfo<HoverResult>> {
411    // FIXME: make this work in attributes
412    let expr_or_pat = file
413        .covering_element(range)
414        .ancestors()
415        .take_while(|it| ast::MacroCall::can_cast(it.kind()) || !ast::Item::can_cast(it.kind()))
416        .find_map(Either::<ast::Expr, ast::Pat>::cast)?;
417    let res = match &expr_or_pat {
418        Either::Left(ast::Expr::TryExpr(try_expr)) => {
419            render::try_expr(sema, config, try_expr, edition, display_target)
420        }
421        Either::Left(ast::Expr::PrefixExpr(prefix_expr))
422            if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
423        {
424            render::deref_expr(sema, config, prefix_expr, edition, display_target)
425        }
426        Either::Left(ast::Expr::Literal(literal)) => {
427            if let Some(literal) = ast::String::cast(literal.token())
428                && let Some((analysis, fixture_analysis)) =
429                    Analysis::from_ra_fixture(sema, literal.clone(), &literal, &config.ra_fixture)
430            {
431                let (virtual_file_id, virtual_range) = fixture_analysis.map_range_down(range)?;
432                return analysis
433                    .hover(config, FileRange { file_id: virtual_file_id, range: virtual_range })
434                    .ok()??
435                    .upmap_from_ra_fixture(&fixture_analysis, virtual_file_id, file_id)
436                    .ok();
437            }
438            None
439        }
440        _ => None,
441    };
442    let res =
443        res.or_else(|| render::type_info_of(sema, config, &expr_or_pat, edition, display_target));
444    res.map(|it| {
445        let range = match expr_or_pat {
446            Either::Left(it) => it.syntax().text_range(),
447            Either::Right(it) => it.syntax().text_range(),
448        };
449        RangeInfo::new(range, it)
450    })
451}
452
453// FIXME: Why is this pub(crate)?
454pub(crate) fn hover_for_definition(
455    sema: &Semantics<'_, RootDatabase>,
456    file_id: FileId,
457    def: Definition<'_>,
458    subst: Option<GenericSubstitution<'_>>,
459    scope_node: &SyntaxNode,
460    macro_arm: Option<u32>,
461    render_extras: bool,
462    config: &HoverConfig<'_>,
463    edition: Edition,
464    display_target: DisplayTarget,
465) -> HoverResult {
466    let famous_defs = match &def {
467        Definition::BuiltinType(_) => sema.scope(scope_node).map(|it| FamousDefs(sema, it.krate())),
468        _ => None,
469    };
470
471    let db = sema.db;
472    let def_ty = match def {
473        Definition::Local(it) => Some(it.ty(db)),
474        Definition::GenericParam(hir::GenericParam::ConstParam(it)) => Some(it.ty(db)),
475        Definition::GenericParam(hir::GenericParam::TypeParam(it)) => Some(it.ty(db)),
476        Definition::Field(field) => Some(field.ty(db)),
477        Definition::TupleField(it) => Some(it.ty(db)),
478        Definition::Function(it) => Some(it.ty(db)),
479        Definition::Adt(it) => Some(it.ty(db)),
480        Definition::Const(it) => Some(it.ty(db)),
481        Definition::Static(it) => Some(it.ty(db)),
482        Definition::TypeAlias(it) => Some(it.ty(db)),
483        Definition::BuiltinType(it) => Some(it.ty(db)),
484        _ => None,
485    };
486    let notable_traits = def_ty.map(|ty| notable_traits(db, &ty)).unwrap_or_default();
487    let subst_types = subst.map(|subst| subst.types(db));
488    let render_private_fields = sema.scope(scope_node).is_some_and(|scope| {
489        def.krate(db)
490            .is_some_and(|def_crate| should_render_private_fields(db, def_crate, scope.krate()))
491    });
492
493    let (markup, range_map) = render::definition(
494        sema.db,
495        def,
496        famous_defs.as_ref(),
497        &notable_traits,
498        macro_arm,
499        render_extras,
500        render_private_fields,
501        subst_types.as_ref(),
502        config,
503        edition,
504        display_target,
505    );
506    HoverResult {
507        markup: render::process_markup(sema.db, def, &markup, range_map, config),
508        actions: [
509            show_fn_references_action(sema, def),
510            show_implementations_action(sema, def),
511            runnable_action(sema, def, file_id),
512            goto_type_action_for_def(sema, def, &notable_traits, subst_types, edition),
513        ]
514        .into_iter()
515        .flatten()
516        .collect(),
517    }
518}
519
520/// | Hover location | Definition location | Render private fields? |
521/// |---|---:|---:|
522/// | Workspace crate | Workspace crate | Yes |
523/// | Workspace crate | External/library crate | No |
524/// | External/library crate | Same external/library crate | Yes |
525/// | External/library crate | Different external/library crate | No |
526/// | Anywhere | Same crate as definition | Yes |
527fn should_render_private_fields(
528    db: &RootDatabase,
529    def_crate: hir::Crate,
530    hover_crate: hir::Crate,
531) -> bool {
532    let is_workspace_crate = |db: &RootDatabase, krate: hir::Crate| {
533        let origin = krate.origin(db);
534        !origin.is_lib() && !origin.is_lang()
535    };
536
537    def_crate == hover_crate
538        || is_workspace_crate(db, def_crate) && is_workspace_crate(db, hover_crate)
539}
540
541fn notable_traits<'db>(
542    db: &'db RootDatabase,
543    ty: &hir::Type<'db>,
544) -> Vec<(hir::Trait, Vec<(Option<hir::Type<'db>>, hir::Name)>)> {
545    if ty.is_unknown() {
546        // The trait solver returns "yes" to the question whether the error type
547        // impls any trait, and we don't want to show it as having any notable trait.
548        return Vec::new();
549    }
550
551    ty.krate(db)
552        .notable_traits_in_deps(db)
553        .filter_map(move |&trait_| {
554            let trait_ = trait_.into();
555            ty.impls_trait(db, trait_, &[]).then(|| {
556                (
557                    trait_,
558                    trait_
559                        .items(db)
560                        .into_iter()
561                        .filter_map(hir::AssocItem::as_type_alias)
562                        .map(|alias| {
563                            (ty.normalize_trait_assoc_type(db, &[], alias), alias.name(db))
564                        })
565                        .collect::<Vec<_>>(),
566                )
567            })
568        })
569        .sorted_by_cached_key(|(trait_, _)| trait_.name(db))
570        .collect::<Vec<_>>()
571}
572
573fn show_implementations_action(
574    sema: &Semantics<'_, RootDatabase>,
575    def: Definition<'_>,
576) -> Option<HoverAction> {
577    fn to_action(nav_target: NavigationTarget) -> HoverAction {
578        HoverAction::Implementation(FilePosition {
579            file_id: nav_target.file_id,
580            offset: nav_target.focus_or_full_range().start(),
581        })
582    }
583
584    let adt = match def {
585        Definition::Trait(it) => {
586            return it.try_to_nav(sema).map(UpmappingResult::call_site).map(to_action);
587        }
588        Definition::Adt(it) => Some(it),
589        Definition::SelfType(it) => it.self_ty(sema.db).as_adt(),
590        _ => None,
591    }?;
592    adt.try_to_nav(sema).map(UpmappingResult::call_site).map(to_action)
593}
594
595fn show_fn_references_action(
596    sema: &Semantics<'_, RootDatabase>,
597    def: Definition<'_>,
598) -> Option<HoverAction> {
599    match def {
600        Definition::Function(it) => {
601            it.try_to_nav(sema).map(UpmappingResult::call_site).map(|nav_target| {
602                HoverAction::Reference(FilePosition {
603                    file_id: nav_target.file_id,
604                    offset: nav_target.focus_or_full_range().start(),
605                })
606            })
607        }
608        _ => None,
609    }
610}
611
612fn runnable_action(
613    sema: &hir::Semantics<'_, RootDatabase>,
614    def: Definition<'_>,
615    file_id: FileId,
616) -> Option<HoverAction> {
617    match def {
618        Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
619        Definition::Function(func) => {
620            let src = func.source(sema.db)?;
621            if src.file_id.file_id().is_none_or(|f| f.file_id(sema.db) != file_id) {
622                cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
623                cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
624                return None;
625            }
626
627            runnable_fn(sema, func).map(HoverAction::Runnable)
628        }
629        _ => None,
630    }
631}
632
633fn goto_type_action_for_def(
634    sema: &Semantics<'_, RootDatabase>,
635    def: Definition<'_>,
636    notable_traits: &[(hir::Trait, Vec<(Option<hir::Type<'_>>, hir::Name)>)],
637    subst_types: Option<Vec<(hir::Symbol, hir::Type<'_>)>>,
638    edition: Edition,
639) -> Option<HoverAction> {
640    let db = sema.db;
641    let mut targets: Vec<hir::ModuleDef> = Vec::new();
642    let mut push_new_def = |item: hir::ModuleDef| {
643        if !targets.contains(&item) {
644            targets.push(item);
645        }
646    };
647
648    for &(trait_, ref assocs) in notable_traits {
649        push_new_def(trait_.into());
650        assocs.iter().filter_map(|(ty, _)| ty.as_ref()).for_each(|ty| {
651            walk_and_push_ty(db, ty, &mut push_new_def);
652        });
653    }
654
655    if let Ok(generic_def) = GenericDef::try_from(def) {
656        generic_def.type_or_const_params(db).into_iter().for_each(|it| {
657            walk_and_push_ty(db, &it.ty(db), &mut push_new_def);
658        });
659    }
660
661    let ty = match def {
662        Definition::Local(it) => Some(it.ty(db)),
663        Definition::Field(field) => Some(field.ty(db)),
664        Definition::TupleField(field) => Some(field.ty(db)),
665        Definition::Const(it) => Some(it.ty(db)),
666        Definition::Static(it) => Some(it.ty(db)),
667        Definition::Function(func) => {
668            for param in func.assoc_fn_params(db) {
669                walk_and_push_ty(db, param.ty(), &mut push_new_def);
670            }
671            Some(func.ret_type(db))
672        }
673        Definition::GenericParam(hir::GenericParam::ConstParam(it)) => Some(it.ty(db)),
674        Definition::GenericParam(hir::GenericParam::TypeParam(it)) => Some(it.ty(db)),
675        _ => None,
676    };
677    if let Some(ty) = ty {
678        walk_and_push_ty(db, &ty, &mut push_new_def);
679    }
680
681    if let Some(subst_types) = subst_types {
682        for (_, ty) in subst_types {
683            walk_and_push_ty(db, &ty, &mut push_new_def);
684        }
685    }
686
687    HoverAction::goto_type_from_targets(sema, targets, edition)
688}
689
690fn walk_and_push_ty(
691    db: &RootDatabase,
692    ty: &hir::Type<'_>,
693    push_new_def: &mut dyn FnMut(hir::ModuleDef),
694) {
695    ty.walk(db, |t| {
696        if let Some(adt) = t.as_adt() {
697            push_new_def(adt.into());
698        } else if let Some(trait_) = t.as_dyn_trait() {
699            push_new_def(trait_.into());
700        } else if let Some(traits) = t.as_impl_traits(db) {
701            traits.for_each(|it| push_new_def(it.into()));
702        } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
703            push_new_def(trait_.into());
704        } else if let Some(tp) = t.as_type_param(db) {
705            let sized_trait = hir::Trait::lang(db, t.krate(db), hir::LangItem::Sized);
706            tp.trait_bounds(db)
707                .into_iter()
708                .filter(|&it| Some(it) != sized_trait)
709                .for_each(|it| push_new_def(it.into()));
710        }
711    });
712}
713
714fn dedupe_or_merge_hover_actions(actions: Vec<HoverAction>) -> Vec<HoverAction> {
715    let mut deduped_actions = Vec::with_capacity(actions.len());
716    let mut go_to_type_targets = FxIndexSet::default();
717
718    let mut seen_implementation = false;
719    let mut seen_reference = false;
720    let mut seen_runnable = false;
721    for action in actions {
722        match action {
723            HoverAction::GoToType(targets) => {
724                go_to_type_targets.extend(targets);
725            }
726            HoverAction::Implementation(..) => {
727                if !seen_implementation {
728                    seen_implementation = true;
729                    deduped_actions.push(action);
730                }
731            }
732            HoverAction::Reference(..) => {
733                if !seen_reference {
734                    seen_reference = true;
735                    deduped_actions.push(action);
736                }
737            }
738            HoverAction::Runnable(..) => {
739                if !seen_runnable {
740                    seen_runnable = true;
741                    deduped_actions.push(action);
742                }
743            }
744        };
745    }
746
747    if !go_to_type_targets.is_empty() {
748        deduped_actions.push(HoverAction::GoToType(
749            go_to_type_targets.into_iter().sorted_by(|a, b| a.mod_path.cmp(&b.mod_path)).collect(),
750        ));
751    }
752
753    deduped_actions
754}