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 cfg_predicate = || {
375            let predicate = token.parent().and_then(ast::CfgPredicate::cast)?;
376            render::cfg_predicate(sema, predicate)
377                .map(|markup| HoverResult { markup, actions: vec![] })
378        };
379        let literal = || {
380            render::literal(sema, original_token.clone(), display_target)
381                .map(|markup| HoverResult { markup, actions: vec![] })
382        };
383        if let Some(result) = keywords()
384            .or_else(underscore)
385            .or_else(rest_pat)
386            .or_else(call)
387            .or_else(closure)
388            .or_else(cfg_predicate)
389            .or_else(literal)
390        {
391            res.push(result)
392        }
393    }
394
395    res.into_iter()
396        .unique()
397        .reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
398            acc.actions.extend(actions);
399            acc.markup = Markup::from(format!("{}\n\n---\n{markup}", acc.markup));
400            acc
401        })
402        .map(|mut res: HoverResult| {
403            res.actions = dedupe_or_merge_hover_actions(res.actions);
404            RangeInfo::new(original_token.text_range(), res)
405        })
406}
407
408fn hover_ranged(
409    sema: &Semantics<'_, RootDatabase>,
410    FileRange { file_id, range }: FileRange,
411    file: SyntaxNode,
412    config: &HoverConfig<'_>,
413    edition: Edition,
414    display_target: DisplayTarget,
415) -> Option<RangeInfo<HoverResult>> {
416    // FIXME: make this work in attributes
417    let expr_or_pat = file
418        .covering_element(range)
419        .ancestors()
420        .take_while(|it| ast::MacroCall::can_cast(it.kind()) || !ast::Item::can_cast(it.kind()))
421        .find_map(Either::<ast::Expr, ast::Pat>::cast)?;
422    let res = match &expr_or_pat {
423        Either::Left(ast::Expr::TryExpr(try_expr)) => {
424            render::try_expr(sema, config, try_expr, edition, display_target)
425        }
426        Either::Left(ast::Expr::PrefixExpr(prefix_expr))
427            if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
428        {
429            render::deref_expr(sema, config, prefix_expr, edition, display_target)
430        }
431        Either::Left(ast::Expr::Literal(literal)) => {
432            if let Some(literal) = ast::String::cast(literal.token())
433                && let Some((analysis, fixture_analysis)) =
434                    Analysis::from_ra_fixture(sema, literal.clone(), &literal, &config.ra_fixture)
435            {
436                let (virtual_file_id, virtual_range) = fixture_analysis.map_range_down(range)?;
437                return analysis
438                    .hover(config, FileRange { file_id: virtual_file_id, range: virtual_range })
439                    .ok()??
440                    .upmap_from_ra_fixture(&fixture_analysis, virtual_file_id, file_id)
441                    .ok();
442            }
443            None
444        }
445        _ => None,
446    };
447    let res =
448        res.or_else(|| render::type_info_of(sema, config, &expr_or_pat, edition, display_target));
449    res.map(|it| {
450        let range = match expr_or_pat {
451            Either::Left(it) => it.syntax().text_range(),
452            Either::Right(it) => it.syntax().text_range(),
453        };
454        RangeInfo::new(range, it)
455    })
456}
457
458// FIXME: Why is this pub(crate)?
459pub(crate) fn hover_for_definition(
460    sema: &Semantics<'_, RootDatabase>,
461    file_id: FileId,
462    def: Definition<'_>,
463    subst: Option<GenericSubstitution<'_>>,
464    scope_node: &SyntaxNode,
465    macro_arm: Option<u32>,
466    render_extras: bool,
467    config: &HoverConfig<'_>,
468    edition: Edition,
469    display_target: DisplayTarget,
470) -> HoverResult {
471    let famous_defs = match &def {
472        Definition::BuiltinType(_) => sema.scope(scope_node).map(|it| FamousDefs(sema, it.krate())),
473        _ => None,
474    };
475
476    let db = sema.db;
477    let def_ty = match def {
478        Definition::Local(it) => Some(it.ty(db)),
479        Definition::GenericParam(hir::GenericParam::ConstParam(it)) => Some(it.ty(db)),
480        Definition::GenericParam(hir::GenericParam::TypeParam(it)) => Some(it.ty(db)),
481        Definition::Field(field) => Some(field.ty(db)),
482        Definition::TupleField(it) => Some(it.ty(db)),
483        Definition::Function(it) => Some(it.ty(db)),
484        Definition::Adt(it) => Some(it.ty(db)),
485        Definition::Const(it) => Some(it.ty(db)),
486        Definition::Static(it) => Some(it.ty(db)),
487        Definition::TypeAlias(it) => Some(it.ty(db)),
488        Definition::BuiltinType(it) => Some(it.ty(db)),
489        _ => None,
490    };
491    let notable_traits = def_ty.map(|ty| notable_traits(db, &ty)).unwrap_or_default();
492    let subst_types = subst.map(|subst| subst.types(db));
493    let render_private_fields = sema.scope(scope_node).is_some_and(|scope| {
494        def.krate(db)
495            .is_some_and(|def_crate| should_render_private_fields(db, def_crate, scope.krate()))
496    });
497
498    let (markup, range_map) = render::definition(
499        sema.db,
500        def,
501        famous_defs.as_ref(),
502        &notable_traits,
503        macro_arm,
504        render_extras,
505        render_private_fields,
506        subst_types.as_ref(),
507        config,
508        edition,
509        display_target,
510    );
511    HoverResult {
512        markup: render::process_markup(sema.db, def, &markup, range_map, config),
513        actions: [
514            show_fn_references_action(sema, def),
515            show_implementations_action(sema, def),
516            runnable_action(sema, def, file_id),
517            goto_type_action_for_def(sema, def, &notable_traits, subst_types, edition),
518        ]
519        .into_iter()
520        .flatten()
521        .collect(),
522    }
523}
524
525/// | Hover location | Definition location | Render private fields? |
526/// |---|---:|---:|
527/// | Workspace crate | Workspace crate | Yes |
528/// | Workspace crate | External/library crate | No |
529/// | External/library crate | Same external/library crate | Yes |
530/// | External/library crate | Different external/library crate | No |
531/// | Anywhere | Same crate as definition | Yes |
532fn should_render_private_fields(
533    db: &RootDatabase,
534    def_crate: hir::Crate,
535    hover_crate: hir::Crate,
536) -> bool {
537    let is_workspace_crate = |db: &RootDatabase, krate: hir::Crate| {
538        let origin = krate.origin(db);
539        !origin.is_lib() && !origin.is_lang()
540    };
541
542    def_crate == hover_crate
543        || is_workspace_crate(db, def_crate) && is_workspace_crate(db, hover_crate)
544}
545
546fn notable_traits<'db>(
547    db: &'db RootDatabase,
548    ty: &hir::Type<'db>,
549) -> Vec<(hir::Trait, Vec<(Option<hir::Type<'db>>, hir::Name)>)> {
550    if ty.is_unknown() {
551        // The trait solver returns "yes" to the question whether the error type
552        // impls any trait, and we don't want to show it as having any notable trait.
553        return Vec::new();
554    }
555
556    ty.krate(db)
557        .notable_traits_in_deps(db)
558        .filter_map(move |&trait_| {
559            let trait_ = trait_.into();
560            ty.impls_trait(db, trait_, &[]).then(|| {
561                (
562                    trait_,
563                    trait_
564                        .items(db)
565                        .into_iter()
566                        .filter_map(hir::AssocItem::as_type_alias)
567                        .map(|alias| {
568                            (ty.normalize_trait_assoc_type(db, &[], alias), alias.name(db))
569                        })
570                        .collect::<Vec<_>>(),
571                )
572            })
573        })
574        .sorted_by_cached_key(|(trait_, _)| trait_.name(db))
575        .collect::<Vec<_>>()
576}
577
578fn show_implementations_action(
579    sema: &Semantics<'_, RootDatabase>,
580    def: Definition<'_>,
581) -> Option<HoverAction> {
582    fn to_action(nav_target: NavigationTarget) -> HoverAction {
583        HoverAction::Implementation(FilePosition {
584            file_id: nav_target.file_id,
585            offset: nav_target.focus_or_full_range().start(),
586        })
587    }
588
589    let adt = match def {
590        Definition::Trait(it) => {
591            return it.try_to_nav(sema).map(UpmappingResult::call_site).map(to_action);
592        }
593        Definition::Adt(it) => Some(it),
594        Definition::SelfType(it) => it.self_ty(sema.db).as_adt(),
595        _ => None,
596    }?;
597    adt.try_to_nav(sema).map(UpmappingResult::call_site).map(to_action)
598}
599
600fn show_fn_references_action(
601    sema: &Semantics<'_, RootDatabase>,
602    def: Definition<'_>,
603) -> Option<HoverAction> {
604    match def {
605        Definition::Function(it) => {
606            it.try_to_nav(sema).map(UpmappingResult::call_site).map(|nav_target| {
607                HoverAction::Reference(FilePosition {
608                    file_id: nav_target.file_id,
609                    offset: nav_target.focus_or_full_range().start(),
610                })
611            })
612        }
613        _ => None,
614    }
615}
616
617fn runnable_action(
618    sema: &hir::Semantics<'_, RootDatabase>,
619    def: Definition<'_>,
620    file_id: FileId,
621) -> Option<HoverAction> {
622    match def {
623        Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
624        Definition::Function(func) => {
625            let src = func.source(sema.db)?;
626            if src.file_id.file_id().is_none_or(|f| f.file_id(sema.db) != file_id) {
627                cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
628                cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
629                return None;
630            }
631
632            runnable_fn(sema, func).map(HoverAction::Runnable)
633        }
634        _ => None,
635    }
636}
637
638fn goto_type_action_for_def(
639    sema: &Semantics<'_, RootDatabase>,
640    def: Definition<'_>,
641    notable_traits: &[(hir::Trait, Vec<(Option<hir::Type<'_>>, hir::Name)>)],
642    subst_types: Option<Vec<(hir::Symbol, hir::Type<'_>)>>,
643    edition: Edition,
644) -> Option<HoverAction> {
645    let db = sema.db;
646    let mut targets: Vec<hir::ModuleDef> = Vec::new();
647    let mut push_new_def = |item: hir::ModuleDef| {
648        if !targets.contains(&item) {
649            targets.push(item);
650        }
651    };
652
653    for &(trait_, ref assocs) in notable_traits {
654        push_new_def(trait_.into());
655        assocs.iter().filter_map(|(ty, _)| ty.as_ref()).for_each(|ty| {
656            walk_and_push_ty(db, ty, &mut push_new_def);
657        });
658    }
659
660    if let Ok(generic_def) = GenericDef::try_from(def) {
661        generic_def.type_or_const_params(db).into_iter().for_each(|it| {
662            walk_and_push_ty(db, &it.ty(db), &mut push_new_def);
663        });
664    }
665
666    let ty = match def {
667        Definition::Local(it) => Some(it.ty(db)),
668        Definition::Field(field) => Some(field.ty(db)),
669        Definition::TupleField(field) => Some(field.ty(db)),
670        Definition::Const(it) => Some(it.ty(db)),
671        Definition::Static(it) => Some(it.ty(db)),
672        Definition::Function(func) => {
673            for param in func.assoc_fn_params(db) {
674                walk_and_push_ty(db, param.ty(), &mut push_new_def);
675            }
676            Some(func.ret_type(db))
677        }
678        Definition::GenericParam(hir::GenericParam::ConstParam(it)) => Some(it.ty(db)),
679        Definition::GenericParam(hir::GenericParam::TypeParam(it)) => Some(it.ty(db)),
680        _ => None,
681    };
682    if let Some(ty) = ty {
683        walk_and_push_ty(db, &ty, &mut push_new_def);
684    }
685
686    if let Some(subst_types) = subst_types {
687        for (_, ty) in subst_types {
688            walk_and_push_ty(db, &ty, &mut push_new_def);
689        }
690    }
691
692    HoverAction::goto_type_from_targets(sema, targets, edition)
693}
694
695fn walk_and_push_ty(
696    db: &RootDatabase,
697    ty: &hir::Type<'_>,
698    push_new_def: &mut dyn FnMut(hir::ModuleDef),
699) {
700    ty.walk(db, |t| {
701        if let Some(adt) = t.as_adt() {
702            push_new_def(adt.into());
703        } else if let Some(trait_) = t.as_dyn_trait() {
704            push_new_def(trait_.into());
705        } else if let Some(traits) = t.as_impl_traits(db) {
706            traits.for_each(|it| push_new_def(it.into()));
707        } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
708            push_new_def(trait_.into());
709        } else if let Some(tp) = t.as_type_param(db) {
710            let sized_trait = hir::Trait::lang(db, t.krate(db), hir::LangItem::Sized);
711            tp.trait_bounds(db)
712                .into_iter()
713                .filter(|&it| Some(it) != sized_trait)
714                .for_each(|it| push_new_def(it.into()));
715        }
716    });
717}
718
719fn dedupe_or_merge_hover_actions(actions: Vec<HoverAction>) -> Vec<HoverAction> {
720    let mut deduped_actions = Vec::with_capacity(actions.len());
721    let mut go_to_type_targets = FxIndexSet::default();
722
723    let mut seen_implementation = false;
724    let mut seen_reference = false;
725    let mut seen_runnable = false;
726    for action in actions {
727        match action {
728            HoverAction::GoToType(targets) => {
729                go_to_type_targets.extend(targets);
730            }
731            HoverAction::Implementation(..) => {
732                if !seen_implementation {
733                    seen_implementation = true;
734                    deduped_actions.push(action);
735                }
736            }
737            HoverAction::Reference(..) => {
738                if !seen_reference {
739                    seen_reference = true;
740                    deduped_actions.push(action);
741                }
742            }
743            HoverAction::Runnable(..) => {
744                if !seen_runnable {
745                    seen_runnable = true;
746                    deduped_actions.push(action);
747                }
748            }
749        };
750    }
751
752    if !go_to_type_targets.is_empty() {
753        deduped_actions.push(HoverAction::GoToType(
754            go_to_type_targets.into_iter().sorted_by(|a, b| a.mod_path.cmp(&b.mod_path)).collect(),
755        ));
756    }
757
758    deduped_actions
759}