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