Auto merge of #15938 - Young-Flash:display_trait_item_when_hover, r=Veykril

feat: add hover display for trait assoc items

This PR enable preview assoc items when hover on `trait`

![image](https://github.com/rust-lang/rust-analyzer/assets/71162630/d9c3949c-33cf-4a32-aa97-3af46b28033a)

inspired by https://github.com/rust-lang/rust-analyzer/pull/15847
This commit is contained in:
bors 2024-03-05 08:26:53 +00:00
commit ce3216e0ae
9 changed files with 206 additions and 28 deletions

View file

@ -63,6 +63,7 @@ pub struct HirFormatter<'a> {
buf: String, buf: String,
curr_size: usize, curr_size: usize,
pub(crate) max_size: Option<usize>, pub(crate) max_size: Option<usize>,
pub limited_size: Option<usize>,
omit_verbose_types: bool, omit_verbose_types: bool,
closure_style: ClosureStyle, closure_style: ClosureStyle,
display_target: DisplayTarget, display_target: DisplayTarget,
@ -86,6 +87,7 @@ pub trait HirDisplay {
&'a self, &'a self,
db: &'a dyn HirDatabase, db: &'a dyn HirDatabase,
max_size: Option<usize>, max_size: Option<usize>,
limited_size: Option<usize>,
omit_verbose_types: bool, omit_verbose_types: bool,
display_target: DisplayTarget, display_target: DisplayTarget,
closure_style: ClosureStyle, closure_style: ClosureStyle,
@ -101,6 +103,7 @@ pub trait HirDisplay {
db, db,
t: self, t: self,
max_size, max_size,
limited_size,
omit_verbose_types, omit_verbose_types,
display_target, display_target,
closure_style, closure_style,
@ -117,6 +120,7 @@ pub trait HirDisplay {
db, db,
t: self, t: self,
max_size: None, max_size: None,
limited_size: None,
omit_verbose_types: false, omit_verbose_types: false,
closure_style: ClosureStyle::ImplFn, closure_style: ClosureStyle::ImplFn,
display_target: DisplayTarget::Diagnostics, display_target: DisplayTarget::Diagnostics,
@ -137,6 +141,28 @@ pub trait HirDisplay {
db, db,
t: self, t: self,
max_size, max_size,
limited_size: None,
omit_verbose_types: true,
closure_style: ClosureStyle::ImplFn,
display_target: DisplayTarget::Diagnostics,
}
}
/// Returns a `Display`able type that is human-readable and tries to limit the item inside this type.
/// Use this for showing types which may contain two many item when user hover on, like `trait`, `struct`, `enum`
fn display_limited<'a>(
&'a self,
db: &'a dyn HirDatabase,
limited_size: Option<usize>,
) -> HirDisplayWrapper<'a, Self>
where
Self: Sized,
{
HirDisplayWrapper {
db,
t: self,
max_size: None,
limited_size,
omit_verbose_types: true, omit_verbose_types: true,
closure_style: ClosureStyle::ImplFn, closure_style: ClosureStyle::ImplFn,
display_target: DisplayTarget::Diagnostics, display_target: DisplayTarget::Diagnostics,
@ -158,6 +184,7 @@ pub trait HirDisplay {
buf: String::with_capacity(20), buf: String::with_capacity(20),
curr_size: 0, curr_size: 0,
max_size: None, max_size: None,
limited_size: None,
omit_verbose_types: false, omit_verbose_types: false,
closure_style: ClosureStyle::ImplFn, closure_style: ClosureStyle::ImplFn,
display_target: DisplayTarget::SourceCode { module_id, allow_opaque }, display_target: DisplayTarget::SourceCode { module_id, allow_opaque },
@ -178,6 +205,7 @@ pub trait HirDisplay {
db, db,
t: self, t: self,
max_size: None, max_size: None,
limited_size: None,
omit_verbose_types: false, omit_verbose_types: false,
closure_style: ClosureStyle::ImplFn, closure_style: ClosureStyle::ImplFn,
display_target: DisplayTarget::Test, display_target: DisplayTarget::Test,
@ -295,6 +323,7 @@ pub struct HirDisplayWrapper<'a, T> {
db: &'a dyn HirDatabase, db: &'a dyn HirDatabase,
t: &'a T, t: &'a T,
max_size: Option<usize>, max_size: Option<usize>,
limited_size: Option<usize>,
omit_verbose_types: bool, omit_verbose_types: bool,
closure_style: ClosureStyle, closure_style: ClosureStyle,
display_target: DisplayTarget, display_target: DisplayTarget,
@ -323,6 +352,7 @@ impl<T: HirDisplay> HirDisplayWrapper<'_, T> {
buf: String::with_capacity(20), buf: String::with_capacity(20),
curr_size: 0, curr_size: 0,
max_size: self.max_size, max_size: self.max_size,
limited_size: self.limited_size,
omit_verbose_types: self.omit_verbose_types, omit_verbose_types: self.omit_verbose_types,
display_target: self.display_target, display_target: self.display_target,
closure_style: self.closure_style, closure_style: self.closure_style,

View file

@ -17,10 +17,10 @@ use hir_ty::{
}; };
use crate::{ use crate::{
Adt, AsAssocItem, AssocItemContainer, Const, ConstParam, Enum, ExternCrateDecl, Field, Adt, AsAssocItem, AssocItem, AssocItemContainer, Const, ConstParam, Enum, ExternCrateDecl,
Function, GenericParam, HasCrate, HasVisibility, LifetimeParam, Macro, Module, SelfParam, Field, Function, GenericParam, HasCrate, HasVisibility, LifetimeParam, Macro, Module,
Static, Struct, Trait, TraitAlias, TupleField, TyBuilder, Type, TypeAlias, TypeOrConstParam, SelfParam, Static, Struct, Trait, TraitAlias, TupleField, TyBuilder, Type, TypeAlias,
TypeParam, Union, Variant, TypeOrConstParam, TypeParam, Union, Variant,
}; };
impl HirDisplay for Function { impl HirDisplay for Function {
@ -595,6 +595,36 @@ impl HirDisplay for Trait {
let def_id = GenericDefId::TraitId(self.id); let def_id = GenericDefId::TraitId(self.id);
write_generic_params(def_id, f)?; write_generic_params(def_id, f)?;
write_where_clause(def_id, f)?; write_where_clause(def_id, f)?;
let assoc_items = self.items(f.db);
let assoc_items_size = assoc_items.len();
let limited_size = f.limited_size.unwrap_or(assoc_items_size);
if assoc_items.is_empty() {
f.write_str(" {}")?;
} else {
f.write_str(" {\n")?;
for (index, item) in assoc_items.iter().enumerate() {
f.write_str(" ")?;
match item {
AssocItem::Function(func) => {
func.hir_fmt(f)?;
}
AssocItem::Const(cst) => {
cst.hir_fmt(f)?;
}
AssocItem::TypeAlias(type_alias) => {
type_alias.hir_fmt(f)?;
}
};
f.write_str(",\n")?;
if index + 1 == limited_size && index + 1 != assoc_items_size {
f.write_str(" ...\n")?;
break;
}
}
f.write_str("}")?;
}
Ok(()) Ok(())
} }
} }

View file

@ -32,6 +32,7 @@ pub struct HoverConfig {
pub documentation: bool, pub documentation: bool,
pub keywords: bool, pub keywords: bool,
pub format: HoverDocFormat, pub format: HoverDocFormat,
pub trait_assoc_items_size: Option<usize>,
} }
#[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(Copy, Clone, Debug, PartialEq, Eq)]

View file

@ -406,7 +406,12 @@ pub(super) fn definition(
config: &HoverConfig, config: &HoverConfig,
) -> Markup { ) -> Markup {
let mod_path = definition_mod_path(db, &def); let mod_path = definition_mod_path(db, &def);
let label = def.label(db); let label = match def {
Definition::Trait(trait_) => {
trait_.display_limited(db, config.trait_assoc_items_size).to_string()
}
_ => def.label(db),
};
let docs = def.docs(db, famous_defs); let docs = def.docs(db, famous_defs);
let value = (|| match def { let value = (|| match def {
Definition::Variant(it) => { Definition::Variant(it) => {

View file

@ -17,6 +17,7 @@ const HOVER_BASE_CONFIG: HoverConfig = HoverConfig {
documentation: true, documentation: true,
format: HoverDocFormat::Markdown, format: HoverDocFormat::Markdown,
keywords: true, keywords: true,
trait_assoc_items_size: None,
}; };
fn check_hover_no_result(ra_fixture: &str) { fn check_hover_no_result(ra_fixture: &str) {
@ -411,7 +412,7 @@ fn main() {
name: "FnOnce", name: "FnOnce",
kind: Trait, kind: Trait,
container_name: "function", container_name: "function",
description: "pub trait FnOnce<Args>\nwhere\n Args: Tuple,", description: "pub trait FnOnce<Args>\nwhere\n Args: Tuple, {\n pub type Output,\n pub extern \"rust-call\" fn call_once(self, args: Args) -> Self::Output,\n}",
}, },
}, },
], ],
@ -2685,7 +2686,7 @@ fn main() { let s$0t = foo(); }
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo", description: "trait Foo {}",
}, },
}, },
], ],
@ -2719,7 +2720,7 @@ fn main() { let s$0t = foo(); }
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo<T>", description: "trait Foo<T> {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -2766,7 +2767,7 @@ fn main() { let s$0t = foo(); }
focus_range: 19..22, focus_range: 19..22,
name: "Bar", name: "Bar",
kind: Trait, kind: Trait,
description: "trait Bar", description: "trait Bar {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -2779,7 +2780,7 @@ fn main() { let s$0t = foo(); }
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo", description: "trait Foo {}",
}, },
}, },
], ],
@ -2816,7 +2817,7 @@ fn main() { let s$0t = foo(); }
focus_range: 22..25, focus_range: 22..25,
name: "Bar", name: "Bar",
kind: Trait, kind: Trait,
description: "trait Bar<T>", description: "trait Bar<T> {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -2829,7 +2830,7 @@ fn main() { let s$0t = foo(); }
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo<T>", description: "trait Foo<T> {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -2886,7 +2887,7 @@ fn foo(ar$0g: &impl Foo) {}
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo", description: "trait Foo {}",
}, },
}, },
], ],
@ -2920,7 +2921,7 @@ fn foo(ar$0g: &impl Foo + Bar<S>) {}
focus_range: 19..22, focus_range: 19..22,
name: "Bar", name: "Bar",
kind: Trait, kind: Trait,
description: "trait Bar<T>", description: "trait Bar<T> {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -2933,7 +2934,7 @@ fn foo(ar$0g: &impl Foo + Bar<S>) {}
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo", description: "trait Foo {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -2988,7 +2989,7 @@ pub mod future {
name: "Future", name: "Future",
kind: Trait, kind: Trait,
container_name: "future", container_name: "future",
description: "pub trait Future", description: "pub trait Future {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -3033,7 +3034,7 @@ fn foo(ar$0g: &impl Foo<S>) {}
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo<T>", description: "trait Foo<T> {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -3096,7 +3097,7 @@ fn main() { let s$0t = foo(); }
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo", description: "trait Foo {}",
}, },
}, },
], ],
@ -3127,7 +3128,7 @@ fn foo(ar$0g: &dyn Foo) {}
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo", description: "trait Foo {}",
}, },
}, },
], ],
@ -3159,7 +3160,7 @@ fn foo(ar$0g: &dyn Foo<S>) {}
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo<T>", description: "trait Foo<T> {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -3220,7 +3221,7 @@ fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
focus_range: 28..36, focus_range: 28..36,
name: "DynTrait", name: "DynTrait",
kind: Trait, kind: Trait,
description: "trait DynTrait<T>", description: "trait DynTrait<T> {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -3233,7 +3234,7 @@ fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
focus_range: 6..15, focus_range: 6..15,
name: "ImplTrait", name: "ImplTrait",
kind: Trait, kind: Trait,
description: "trait ImplTrait<T>", description: "trait ImplTrait<T> {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -3288,7 +3289,7 @@ fn main() { let s$0t = test().get(); }
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo", description: "trait Foo {\n type Item,\n fn get(self) -> Self::Item,\n}",
}, },
}, },
], ],
@ -3353,7 +3354,7 @@ fn foo<T: Foo>(t: T$0){}
focus_range: 6..9, focus_range: 6..9,
name: "Foo", name: "Foo",
kind: Trait, kind: Trait,
description: "trait Foo", description: "trait Foo {}",
}, },
}, },
], ],
@ -6327,6 +6328,99 @@ impl T for () {
); );
} }
#[test]
fn hover_trait_show_assoc_items() {
check(
r#"
trait T {}
impl T$0 for () {}
"#,
expect![[r#"
*T*
```rust
test
```
```rust
trait T {}
```
"#]],
);
check(
r#"
trait T {
fn func() {}
}
impl T$0 for () {}
"#,
expect![[r#"
*T*
```rust
test
```
```rust
trait T {
fn func(),
}
```
"#]],
);
check(
r#"
trait T {
fn func() {}
const FLAG: i32 = 34;
}
impl T$0 for () {}
"#,
expect![[r#"
*T*
```rust
test
```
```rust
trait T {
fn func(),
const FLAG: i32,
}
```
"#]],
);
check(
r#"
trait T {
fn func() {}
const FLAG: i32 = 34;
type Bar;
}
impl T$0 for () {}
"#,
expect![[r#"
*T*
```rust
test
```
```rust
trait T {
fn func(),
const FLAG: i32,
type Bar,
}
```
"#]],
);
}
#[test] #[test]
fn hover_ranged_macro_call() { fn hover_ranged_macro_call() {
check_hover_range( check_hover_range(
@ -7438,7 +7532,7 @@ impl Iterator for S {
name: "Future", name: "Future",
kind: Trait, kind: Trait,
container_name: "future", container_name: "future",
description: "pub trait Future", description: "pub trait Future {\n pub type Output,\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>,\n}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -7452,7 +7546,7 @@ impl Iterator for S {
name: "Iterator", name: "Iterator",
kind: Trait, kind: Trait,
container_name: "iterator", container_name: "iterator",
description: "pub trait Iterator", description: "pub trait Iterator {\n pub type Item,\n pub fn next(&mut self) -> Option<Self::Item>,\n pub fn nth(&mut self, n: usize) -> Option<Self::Item>,\n pub fn by_ref(&mut self) -> &mut Self\nwhere\n Self: Sized,,\n}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {
@ -7465,7 +7559,7 @@ impl Iterator for S {
focus_range: 49..56, focus_range: 49..56,
name: "Notable", name: "Notable",
kind: Trait, kind: Trait,
description: "trait Notable", description: "trait Notable {}",
}, },
}, },
HoverGotoTypeData { HoverGotoTypeData {

View file

@ -166,6 +166,7 @@ impl StaticIndex<'_> {
documentation: true, documentation: true,
keywords: true, keywords: true,
format: crate::HoverDocFormat::Markdown, format: crate::HoverDocFormat::Markdown,
trait_assoc_items_size: None,
}; };
let tokens = tokens.filter(|token| { let tokens = tokens.filter(|token| {
matches!( matches!(

View file

@ -375,6 +375,9 @@ config_data! {
/// How to render the size information in a memory layout hover. /// How to render the size information in a memory layout hover.
hover_memoryLayout_size: Option<MemoryLayoutHoverRenderKindDef> = "\"both\"", hover_memoryLayout_size: Option<MemoryLayoutHoverRenderKindDef> = "\"both\"",
/// How many associated items of a trait to display when hovering a trait.
hover_show_traitAssocItems: Option<usize> = "null",
/// Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file. /// Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file.
imports_granularity_enforce: bool = "false", imports_granularity_enforce: bool = "false",
/// How imports should be grouped into use statements. /// How imports should be grouped into use statements.
@ -518,7 +521,6 @@ config_data! {
/// Exclude tests from find-all-references. /// Exclude tests from find-all-references.
references_excludeTests: bool = "false", references_excludeTests: bool = "false",
/// Command to be executed instead of 'cargo' for runnables. /// Command to be executed instead of 'cargo' for runnables.
runnables_command: Option<String> = "null", runnables_command: Option<String> = "null",
/// Additional arguments to be passed to cargo for runnables such as /// Additional arguments to be passed to cargo for runnables such as
@ -1680,6 +1682,7 @@ impl Config {
} }
}, },
keywords: self.data.hover_documentation_keywords_enable, keywords: self.data.hover_documentation_keywords_enable,
trait_assoc_items_size: self.data.hover_show_traitAssocItems,
} }
} }

View file

@ -515,6 +515,11 @@ How to render the offset information in a memory layout hover.
-- --
How to render the size information in a memory layout hover. How to render the size information in a memory layout hover.
-- --
[[rust-analyzer.hover.show.traitAssocItems]]rust-analyzer.hover.show.traitAssocItems (default: `null`)::
+
--
How many associated items of a trait to display when hovering a trait.
--
[[rust-analyzer.imports.granularity.enforce]]rust-analyzer.imports.granularity.enforce (default: `false`):: [[rust-analyzer.imports.granularity.enforce]]rust-analyzer.imports.granularity.enforce (default: `false`)::
+ +
-- --

View file

@ -1134,6 +1134,15 @@
} }
] ]
}, },
"rust-analyzer.hover.show.traitAssocItems": {
"markdownDescription": "How many associated items of a trait to display when hovering a trait.",
"default": null,
"type": [
"null",
"integer"
],
"minimum": 0
},
"rust-analyzer.imports.granularity.enforce": { "rust-analyzer.imports.granularity.enforce": {
"markdownDescription": "Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file.", "markdownDescription": "Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file.",
"default": false, "default": false,