ide/
hover.rs

1mod render;
2
3#[cfg(test)]
4mod tests;
5
6use std::{iter, ops::Not};
7
8use either::Either;
9use hir::{
10    DisplayTarget, GenericDef, GenericSubstitution, HasCrate, HasSource, LangItem, Semantics,
11    db::DefDatabase,
12};
13use ide_db::{
14    FileRange, FxIndexSet, Ranker, RootDatabase,
15    defs::{Definition, IdentClass, NameRefClass, OperatorClass},
16    famous_defs::FamousDefs,
17    helpers::pick_best_token,
18};
19use itertools::{Itertools, multizip};
20use span::Edition;
21use syntax::{
22    AstNode,
23    SyntaxKind::{self, *},
24    SyntaxNode, T, ast,
25};
26
27use crate::{
28    FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, TryToNav,
29    doc_links::token_as_doc_comment,
30    markdown_remove::remove_markdown,
31    markup::Markup,
32    navigation_target::UpmappingResult,
33    runnables::{runnable_fn, runnable_mod},
34};
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct HoverConfig {
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}
48
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub enum SubstTyLen {
51    Unlimited,
52    LimitTo(usize),
53    Hide,
54}
55
56#[derive(Copy, Clone, Debug, PartialEq, Eq)]
57pub struct MemoryLayoutHoverConfig {
58    pub size: Option<MemoryLayoutHoverRenderKind>,
59    pub offset: Option<MemoryLayoutHoverRenderKind>,
60    pub alignment: Option<MemoryLayoutHoverRenderKind>,
61    pub padding: Option<MemoryLayoutHoverRenderKind>,
62    pub niches: bool,
63}
64
65#[derive(Copy, Clone, Debug, PartialEq, Eq)]
66pub enum MemoryLayoutHoverRenderKind {
67    Decimal,
68    Hexadecimal,
69    Both,
70}
71
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub enum HoverDocFormat {
74    Markdown,
75    PlainText,
76}
77
78#[derive(Debug, Clone, Hash, PartialEq, Eq)]
79pub enum HoverAction {
80    Runnable(Runnable),
81    Implementation(FilePosition),
82    Reference(FilePosition),
83    GoToType(Vec<HoverGotoTypeData>),
84}
85
86impl HoverAction {
87    fn goto_type_from_targets(
88        sema: &Semantics<'_, RootDatabase>,
89        targets: Vec<hir::ModuleDef>,
90        edition: Edition,
91    ) -> Option<Self> {
92        let db = sema.db;
93        let targets = targets
94            .into_iter()
95            .filter_map(|it| {
96                Some(HoverGotoTypeData {
97                    mod_path: render::path(
98                        db,
99                        it.module(db)?,
100                        it.name(db).map(|name| name.display(db, edition).to_string()),
101                        edition,
102                    ),
103                    nav: it.try_to_nav(sema)?.call_site(),
104                })
105            })
106            .collect::<Vec<_>>();
107        targets.is_empty().not().then_some(HoverAction::GoToType(targets))
108    }
109}
110
111#[derive(Debug, Clone, Eq, PartialEq, Hash)]
112pub struct HoverGotoTypeData {
113    pub mod_path: String,
114    pub nav: NavigationTarget,
115}
116
117/// Contains the results when hovering over an item
118#[derive(Clone, Debug, Default, Hash, PartialEq, Eq)]
119pub struct HoverResult {
120    pub markup: Markup,
121    pub actions: Vec<HoverAction>,
122}
123
124// Feature: Hover
125//
126// Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
127// Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
128//
129// ![Hover](https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif)
130pub(crate) fn hover(
131    db: &RootDatabase,
132    frange @ FileRange { file_id, range }: FileRange,
133    config: &HoverConfig,
134) -> Option<RangeInfo<HoverResult>> {
135    let sema = &hir::Semantics::new(db);
136    let file = sema.parse_guess_edition(file_id).syntax().clone();
137    let edition =
138        sema.attach_first_edition(file_id).map(|it| it.edition(db)).unwrap_or(Edition::CURRENT);
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    // prefer descending the same token kind in attribute expansions, in normal macros text
223    // equivalency is more important
224    let mut descended = sema.descend_into_macros(original_token.clone());
225
226    let ranker = Ranker::from_token(&original_token);
227
228    descended.sort_by_cached_key(|tok| !ranker.rank_token(tok));
229
230    let mut res = vec![];
231    for token in descended {
232        let is_same_kind = token.kind() == ranker.kind;
233        let lint_hover = (|| {
234            // FIXME: Definition should include known lints and the like instead of having this special case here
235            let attr = token.parent_ancestors().find_map(ast::Attr::cast)?;
236            render::try_for_lint(&attr, &token)
237        })();
238        if let Some(lint_hover) = lint_hover {
239            res.push(lint_hover);
240            continue;
241        }
242        let definitions = (|| {
243            Some(
244                'a: {
245                    let node = token.parent()?;
246
247                    // special case macro calls, we wanna render the invoked arm index
248                    if let Some(name) = ast::NameRef::cast(node.clone())
249                        && let Some(path_seg) =
250                            name.syntax().parent().and_then(ast::PathSegment::cast)
251                            && let Some(macro_call) = path_seg
252                                .parent_path()
253                                .syntax()
254                                .parent()
255                                .and_then(ast::MacroCall::cast)
256                                && let Some(macro_) = sema.resolve_macro_call(&macro_call) {
257                                    break 'a vec![(
258                                        (Definition::Macro(macro_), None),
259                                        sema.resolve_macro_call_arm(&macro_call),
260                                        false,
261                                        node,
262                                    )];
263                                }
264
265                    match IdentClass::classify_node(sema, &node)? {
266                        // It's better for us to fall back to the keyword hover here,
267                        // rendering poll is very confusing
268                        IdentClass::Operator(OperatorClass::Await(_)) => return None,
269
270                        IdentClass::NameRefClass(NameRefClass::ExternCrateShorthand {
271                            decl,
272                            ..
273                        }) => {
274                            vec![((Definition::ExternCrateDecl(decl), None), None, false, node)]
275                        }
276
277                        class => {
278                            let render_extras = matches!(class, IdentClass::NameClass(_))
279                                // Render extra information for `Self` keyword as well
280                                || ast::NameRef::cast(node.clone()).is_some_and(|name_ref| name_ref.token_kind() == SyntaxKind::SELF_TYPE_KW);
281                            multizip((
282                                class.definitions(),
283                                iter::repeat(None),
284                                iter::repeat(render_extras),
285                                iter::repeat(node),
286                            ))
287                            .collect::<Vec<_>>()
288                        }
289                    }
290                }
291                .into_iter()
292                .unique_by(|&((def, _), _, _, _)| def)
293                .map(|((def, subst), macro_arm, hovered_definition, node)| {
294                    hover_for_definition(
295                        sema,
296                        file_id,
297                        def,
298                        subst,
299                        &node,
300                        macro_arm,
301                        hovered_definition,
302                        config,
303                        edition,
304                        display_target,
305                    )
306                })
307                .collect::<Vec<_>>(),
308            )
309        })();
310        if let Some(definitions) = definitions {
311            res.extend(definitions);
312            continue;
313        }
314        let keywords = || render::keyword(sema, config, &token, edition, display_target);
315        let underscore = || {
316            if !is_same_kind {
317                return None;
318            }
319            render::underscore(sema, config, &token, edition, display_target)
320        };
321        let rest_pat = || {
322            if !is_same_kind || token.kind() != DOT2 {
323                return None;
324            }
325
326            let rest_pat = token.parent().and_then(ast::RestPat::cast)?;
327            let record_pat_field_list =
328                rest_pat.syntax().parent().and_then(ast::RecordPatFieldList::cast)?;
329
330            let record_pat =
331                record_pat_field_list.syntax().parent().and_then(ast::RecordPat::cast)?;
332
333            Some(render::struct_rest_pat(sema, config, &record_pat, edition, display_target))
334        };
335        let call = || {
336            if !is_same_kind || token.kind() != T!['('] && token.kind() != T![')'] {
337                return None;
338            }
339            let arg_list = token.parent().and_then(ast::ArgList::cast)?.syntax().parent()?;
340            let call_expr = syntax::match_ast! {
341                match arg_list {
342                    ast::CallExpr(expr) => expr.into(),
343                    ast::MethodCallExpr(expr) => expr.into(),
344                    _ => return None,
345                }
346            };
347            render::type_info_of(sema, config, &Either::Left(call_expr), edition, display_target)
348        };
349        let closure = || {
350            if !is_same_kind || token.kind() != T![|] {
351                return None;
352            }
353            let c = token.parent().and_then(|x| x.parent()).and_then(ast::ClosureExpr::cast)?;
354            render::closure_expr(sema, config, c, edition, display_target)
355        };
356        let literal = || {
357            render::literal(sema, original_token.clone(), display_target)
358                .map(|markup| HoverResult { markup, actions: vec![] })
359        };
360        if let Some(result) = keywords()
361            .or_else(underscore)
362            .or_else(rest_pat)
363            .or_else(call)
364            .or_else(closure)
365            .or_else(literal)
366        {
367            res.push(result)
368        }
369    }
370
371    res.into_iter()
372        .unique()
373        .reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
374            acc.actions.extend(actions);
375            acc.markup = Markup::from(format!("{}\n\n---\n{markup}", acc.markup));
376            acc
377        })
378        .map(|mut res: HoverResult| {
379            res.actions = dedupe_or_merge_hover_actions(res.actions);
380            RangeInfo::new(original_token.text_range(), res)
381        })
382}
383
384fn hover_ranged(
385    sema: &Semantics<'_, RootDatabase>,
386    FileRange { range, .. }: FileRange,
387    file: SyntaxNode,
388    config: &HoverConfig,
389    edition: Edition,
390    display_target: DisplayTarget,
391) -> Option<RangeInfo<HoverResult>> {
392    // FIXME: make this work in attributes
393    let expr_or_pat = file
394        .covering_element(range)
395        .ancestors()
396        .take_while(|it| ast::MacroCall::can_cast(it.kind()) || !ast::Item::can_cast(it.kind()))
397        .find_map(Either::<ast::Expr, ast::Pat>::cast)?;
398    let res = match &expr_or_pat {
399        Either::Left(ast::Expr::TryExpr(try_expr)) => {
400            render::try_expr(sema, config, try_expr, edition, display_target)
401        }
402        Either::Left(ast::Expr::PrefixExpr(prefix_expr))
403            if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
404        {
405            render::deref_expr(sema, config, prefix_expr, edition, display_target)
406        }
407        _ => None,
408    };
409    let res =
410        res.or_else(|| render::type_info_of(sema, config, &expr_or_pat, edition, display_target));
411    res.map(|it| {
412        let range = match expr_or_pat {
413            Either::Left(it) => it.syntax().text_range(),
414            Either::Right(it) => it.syntax().text_range(),
415        };
416        RangeInfo::new(range, it)
417    })
418}
419
420// FIXME: Why is this pub(crate)?
421pub(crate) fn hover_for_definition(
422    sema: &Semantics<'_, RootDatabase>,
423    file_id: FileId,
424    def: Definition,
425    subst: Option<GenericSubstitution<'_>>,
426    scope_node: &SyntaxNode,
427    macro_arm: Option<u32>,
428    render_extras: bool,
429    config: &HoverConfig,
430    edition: Edition,
431    display_target: DisplayTarget,
432) -> HoverResult {
433    let famous_defs = match &def {
434        Definition::BuiltinType(_) => sema.scope(scope_node).map(|it| FamousDefs(sema, it.krate())),
435        _ => None,
436    };
437
438    let db = sema.db;
439    let def_ty = match def {
440        Definition::Local(it) => Some(it.ty(db)),
441        Definition::GenericParam(hir::GenericParam::ConstParam(it)) => Some(it.ty(db)),
442        Definition::GenericParam(hir::GenericParam::TypeParam(it)) => Some(it.ty(db)),
443        Definition::Field(field) => Some(field.ty(db).to_type(db)),
444        Definition::TupleField(it) => Some(it.ty(db)),
445        Definition::Function(it) => Some(it.ty(db)),
446        Definition::Adt(it) => Some(it.ty(db)),
447        Definition::Const(it) => Some(it.ty(db)),
448        Definition::Static(it) => Some(it.ty(db)),
449        Definition::TypeAlias(it) => Some(it.ty(db)),
450        Definition::BuiltinType(it) => Some(it.ty(db)),
451        _ => None,
452    };
453    let notable_traits = def_ty.map(|ty| notable_traits(db, &ty)).unwrap_or_default();
454    let subst_types = subst.map(|subst| subst.types(db));
455
456    let (markup, range_map) = render::definition(
457        sema.db,
458        def,
459        famous_defs.as_ref(),
460        &notable_traits,
461        macro_arm,
462        render_extras,
463        subst_types.as_ref(),
464        config,
465        edition,
466        display_target,
467    );
468    HoverResult {
469        markup: render::process_markup(sema.db, def, &markup, range_map, config),
470        actions: [
471            show_fn_references_action(sema, def),
472            show_implementations_action(sema, def),
473            runnable_action(sema, def, file_id),
474            goto_type_action_for_def(sema, def, &notable_traits, subst_types, edition),
475        ]
476        .into_iter()
477        .flatten()
478        .collect(),
479    }
480}
481
482fn notable_traits<'db>(
483    db: &'db RootDatabase,
484    ty: &hir::Type<'db>,
485) -> Vec<(hir::Trait, Vec<(Option<hir::Type<'db>>, hir::Name)>)> {
486    if ty.is_unknown() {
487        // The trait solver returns "yes" to the question whether the error type
488        // impls any trait, and we don't want to show it as having any notable trait.
489        return Vec::new();
490    }
491
492    db.notable_traits_in_deps(ty.krate(db).into())
493        .iter()
494        .flat_map(|it| &**it)
495        .filter_map(move |&trait_| {
496            let trait_ = trait_.into();
497            ty.impls_trait(db, trait_, &[]).then(|| {
498                (
499                    trait_,
500                    trait_
501                        .items(db)
502                        .into_iter()
503                        .filter_map(hir::AssocItem::as_type_alias)
504                        .map(|alias| {
505                            (ty.normalize_trait_assoc_type(db, &[], alias), alias.name(db))
506                        })
507                        .collect::<Vec<_>>(),
508                )
509            })
510        })
511        .sorted_by_cached_key(|(trait_, _)| trait_.name(db))
512        .collect::<Vec<_>>()
513}
514
515fn show_implementations_action(
516    sema: &Semantics<'_, RootDatabase>,
517    def: Definition,
518) -> Option<HoverAction> {
519    fn to_action(nav_target: NavigationTarget) -> HoverAction {
520        HoverAction::Implementation(FilePosition {
521            file_id: nav_target.file_id,
522            offset: nav_target.focus_or_full_range().start(),
523        })
524    }
525
526    let adt = match def {
527        Definition::Trait(it) => {
528            return it.try_to_nav(sema).map(UpmappingResult::call_site).map(to_action);
529        }
530        Definition::Adt(it) => Some(it),
531        Definition::SelfType(it) => it.self_ty(sema.db).as_adt(),
532        _ => None,
533    }?;
534    adt.try_to_nav(sema).map(UpmappingResult::call_site).map(to_action)
535}
536
537fn show_fn_references_action(
538    sema: &Semantics<'_, RootDatabase>,
539    def: Definition,
540) -> Option<HoverAction> {
541    match def {
542        Definition::Function(it) => {
543            it.try_to_nav(sema).map(UpmappingResult::call_site).map(|nav_target| {
544                HoverAction::Reference(FilePosition {
545                    file_id: nav_target.file_id,
546                    offset: nav_target.focus_or_full_range().start(),
547                })
548            })
549        }
550        _ => None,
551    }
552}
553
554fn runnable_action(
555    sema: &hir::Semantics<'_, RootDatabase>,
556    def: Definition,
557    file_id: FileId,
558) -> Option<HoverAction> {
559    match def {
560        Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
561        Definition::Function(func) => {
562            let src = func.source(sema.db)?;
563            if src.file_id.file_id().is_none_or(|f| f.file_id(sema.db) != file_id) {
564                cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
565                cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
566                return None;
567            }
568
569            runnable_fn(sema, func).map(HoverAction::Runnable)
570        }
571        _ => None,
572    }
573}
574
575fn goto_type_action_for_def(
576    sema: &Semantics<'_, RootDatabase>,
577    def: Definition,
578    notable_traits: &[(hir::Trait, Vec<(Option<hir::Type<'_>>, hir::Name)>)],
579    subst_types: Option<Vec<(hir::Symbol, hir::Type<'_>)>>,
580    edition: Edition,
581) -> Option<HoverAction> {
582    let db = sema.db;
583    let mut targets: Vec<hir::ModuleDef> = Vec::new();
584    let mut push_new_def = |item: hir::ModuleDef| {
585        if !targets.contains(&item) {
586            targets.push(item);
587        }
588    };
589
590    for &(trait_, ref assocs) in notable_traits {
591        push_new_def(trait_.into());
592        assocs.iter().filter_map(|(ty, _)| ty.as_ref()).for_each(|ty| {
593            walk_and_push_ty(db, ty, &mut push_new_def);
594        });
595    }
596
597    if let Ok(generic_def) = GenericDef::try_from(def) {
598        generic_def.type_or_const_params(db).into_iter().for_each(|it| {
599            walk_and_push_ty(db, &it.ty(db), &mut push_new_def);
600        });
601    }
602
603    let ty = match def {
604        Definition::Local(it) => Some(it.ty(db)),
605        Definition::Field(field) => Some(field.ty(db).to_type(db)),
606        Definition::TupleField(field) => Some(field.ty(db)),
607        Definition::Const(it) => Some(it.ty(db)),
608        Definition::Static(it) => Some(it.ty(db)),
609        Definition::Function(func) => {
610            for param in func.assoc_fn_params(db) {
611                walk_and_push_ty(db, param.ty(), &mut push_new_def);
612            }
613            Some(func.ret_type(db))
614        }
615        Definition::GenericParam(hir::GenericParam::ConstParam(it)) => Some(it.ty(db)),
616        Definition::GenericParam(hir::GenericParam::TypeParam(it)) => Some(it.ty(db)),
617        _ => None,
618    };
619    if let Some(ty) = ty {
620        walk_and_push_ty(db, &ty, &mut push_new_def);
621    }
622
623    if let Some(subst_types) = subst_types {
624        for (_, ty) in subst_types {
625            walk_and_push_ty(db, &ty, &mut push_new_def);
626        }
627    }
628
629    HoverAction::goto_type_from_targets(sema, targets, edition)
630}
631
632fn walk_and_push_ty(
633    db: &RootDatabase,
634    ty: &hir::Type<'_>,
635    push_new_def: &mut dyn FnMut(hir::ModuleDef),
636) {
637    ty.walk(db, |t| {
638        if let Some(adt) = t.as_adt() {
639            push_new_def(adt.into());
640        } else if let Some(trait_) = t.as_dyn_trait() {
641            push_new_def(trait_.into());
642        } else if let Some(traits) = t.as_impl_traits(db) {
643            traits.for_each(|it| push_new_def(it.into()));
644        } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
645            push_new_def(trait_.into());
646        } else if let Some(tp) = t.as_type_param(db) {
647            let sized_trait = LangItem::Sized.resolve_trait(db, t.krate(db).into());
648            tp.trait_bounds(db)
649                .into_iter()
650                .filter(|&it| Some(it.into()) != sized_trait)
651                .for_each(|it| push_new_def(it.into()));
652        }
653    });
654}
655
656fn dedupe_or_merge_hover_actions(actions: Vec<HoverAction>) -> Vec<HoverAction> {
657    let mut deduped_actions = Vec::with_capacity(actions.len());
658    let mut go_to_type_targets = FxIndexSet::default();
659
660    let mut seen_implementation = false;
661    let mut seen_reference = false;
662    let mut seen_runnable = false;
663    for action in actions {
664        match action {
665            HoverAction::GoToType(targets) => {
666                go_to_type_targets.extend(targets);
667            }
668            HoverAction::Implementation(..) => {
669                if !seen_implementation {
670                    seen_implementation = true;
671                    deduped_actions.push(action);
672                }
673            }
674            HoverAction::Reference(..) => {
675                if !seen_reference {
676                    seen_reference = true;
677                    deduped_actions.push(action);
678                }
679            }
680            HoverAction::Runnable(..) => {
681                if !seen_runnable {
682                    seen_runnable = true;
683                    deduped_actions.push(action);
684                }
685            }
686        };
687    }
688
689    if !go_to_type_targets.is_empty() {
690        deduped_actions.push(HoverAction::GoToType(
691            go_to_type_targets.into_iter().sorted_by(|a, b| a.mod_path.cmp(&b.mod_path)).collect(),
692        ));
693    }
694
695    deduped_actions
696}