Skip to content

Commit 7ab0aaa

Browse files
committed
Add option to skip trivial cases
1 parent 45756c8 commit 7ab0aaa

File tree

6 files changed

+178
-49
lines changed

6 files changed

+178
-49
lines changed

crates/ide/src/inlay_hints.rs

Lines changed: 108 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use ide_db::{
44
base_db::FileRange, famous_defs::FamousDefs, syntax_helpers::node_ext::walk_ty, RootDatabase,
55
};
66
use itertools::Itertools;
7-
use rustc_hash::FxHashSet;
7+
use rustc_hash::FxHashMap;
88
use stdx::to_lower_snake_case;
99
use syntax::{
1010
ast::{self, AstNode, HasArgList, HasGenericParams, HasName, UnaryOp},
@@ -20,13 +20,19 @@ pub struct InlayHintsConfig {
2020
pub parameter_hints: bool,
2121
pub chaining_hints: bool,
2222
pub closure_return_type_hints: bool,
23-
// FIXME: ternary option here, on off non-noisy
24-
pub lifetime_elision_hints: bool,
23+
pub lifetime_elision_hints: LifetimeElisionHints,
2524
pub param_names_for_lifetime_elision_hints: bool,
2625
pub hide_named_constructor_hints: bool,
2726
pub max_length: Option<usize>,
2827
}
2928

29+
#[derive(Clone, Debug, PartialEq, Eq)]
30+
pub enum LifetimeElisionHints {
31+
Always,
32+
SkipTrivial,
33+
Never,
34+
}
35+
3036
#[derive(Clone, Debug, PartialEq, Eq)]
3137
pub enum InlayKind {
3238
TypeHint,
@@ -58,6 +64,7 @@ pub struct InlayHint {
5864
// Optionally, one can enable additional hints for
5965
//
6066
// * return types of closure expressions with blocks
67+
// * elided lifetimes
6168
//
6269
// **Note:** VS Code does not have native support for inlay hints https://github.com/microsoft/vscode/issues/16221[yet] and the hints are implemented using decorations.
6370
// This approach has limitations, the caret movement and bracket highlighting near the edges of the hint may be weird:
@@ -132,24 +139,24 @@ fn lifetime_hints(
132139
config: &InlayHintsConfig,
133140
func: ast::Fn,
134141
) -> Option<()> {
135-
if !config.lifetime_elision_hints {
142+
if config.lifetime_elision_hints == LifetimeElisionHints::Never {
136143
return None;
137144
}
138145
let param_list = func.param_list()?;
139146
let generic_param_list = func.generic_param_list();
140147
let ret_type = func.ret_type();
141148
let self_param = param_list.self_param().filter(|it| it.amp_token().is_some());
142149

143-
let used_names: FxHashSet<SmolStr> = generic_param_list
150+
let mut used_names: FxHashMap<SmolStr, usize> = generic_param_list
144151
.iter()
145-
.filter(|_| !config.param_names_for_lifetime_elision_hints)
152+
.filter(|_| config.param_names_for_lifetime_elision_hints)
146153
.flat_map(|gpl| gpl.lifetime_params())
147154
.filter_map(|param| param.lifetime())
148-
.map(|lt| SmolStr::from(lt.text().as_str()))
155+
.filter_map(|lt| Some((SmolStr::from(lt.text().as_str().get(1..)?), 0)))
149156
.collect();
150157

151158
let mut allocated_lifetimes = vec![];
152-
let mut gen_name = {
159+
let mut gen_idx_name = {
153160
let mut gen = (0u8..).map(|idx| match idx {
154161
idx if idx < 10 => SmolStr::from_iter(['\'', (idx + 48) as char]),
155162
idx => format!("'{idx}").into(),
@@ -158,19 +165,27 @@ fn lifetime_hints(
158165
};
159166

160167
let mut potential_lt_refs: Vec<_> = vec![];
161-
param_list.params().filter_map(|it| Some((it.pat(), it.ty()?))).for_each(|(pat, ty)| {
162-
// FIXME: check path types
163-
walk_ty(&ty, &mut |ty| match ty {
164-
ast::Type::RefType(r) => potential_lt_refs.push((
165-
pat.as_ref().and_then(|it| match it {
166-
ast::Pat::IdentPat(p) => p.name(),
167-
_ => None,
168-
}),
169-
r,
170-
)),
171-
_ => (),
168+
param_list
169+
.params()
170+
.filter_map(|it| {
171+
Some((
172+
config.param_names_for_lifetime_elision_hints.then(|| it.pat()).flatten(),
173+
it.ty()?,
174+
))
172175
})
173-
});
176+
.for_each(|(pat, ty)| {
177+
// FIXME: check path types
178+
walk_ty(&ty, &mut |ty| match ty {
179+
ast::Type::RefType(r) => potential_lt_refs.push((
180+
pat.as_ref().and_then(|it| match it {
181+
ast::Pat::IdentPat(p) => p.name(),
182+
_ => None,
183+
}),
184+
r,
185+
)),
186+
_ => (),
187+
})
188+
});
174189

175190
enum LifetimeKind {
176191
Elided,
@@ -195,25 +210,28 @@ fn lifetime_hints(
195210
if let Some(self_param) = &self_param {
196211
if is_elided(self_param.lifetime()) {
197212
allocated_lifetimes.push(if config.param_names_for_lifetime_elision_hints {
213+
// self can't be used as a lifetime, so no need to check for collisions
198214
"'self".into()
199215
} else {
200-
gen_name()
216+
gen_idx_name()
201217
});
202218
}
203219
}
204220
potential_lt_refs.iter().for_each(|(name, it)| {
205221
if is_elided(it.lifetime()) {
206-
allocated_lifetimes.push(
207-
name.as_ref()
208-
.filter(|it| {
209-
config.param_names_for_lifetime_elision_hints
210-
&& !used_names.contains(it.text().as_str())
211-
})
212-
.map_or_else(
213-
|| gen_name(),
214-
|it| SmolStr::from_iter(["\'", it.text().as_str()]),
215-
),
216-
);
222+
let name = match name {
223+
Some(it) => {
224+
if let Some(c) = used_names.get_mut(it.text().as_str()) {
225+
*c += 1;
226+
SmolStr::from(format!("'{text}{c}", text = it.text().as_str()))
227+
} else {
228+
used_names.insert(it.text().as_str().into(), 0);
229+
SmolStr::from_iter(["\'", it.text().as_str()])
230+
}
231+
}
232+
_ => gen_idx_name(),
233+
};
234+
allocated_lifetimes.push(name);
217235
}
218236
});
219237

@@ -236,8 +254,21 @@ fn lifetime_hints(
236254
}
237255
};
238256

239-
// apply hints
257+
if allocated_lifetimes.is_empty() && output.is_none() {
258+
return None;
259+
}
240260

261+
let skip_due_trivial_single = config.lifetime_elision_hints
262+
== LifetimeElisionHints::SkipTrivial
263+
&& (allocated_lifetimes.len() == 1)
264+
&& generic_param_list.as_ref().map_or(true, |it| it.lifetime_params().next().is_none());
265+
266+
if skip_due_trivial_single {
267+
cov_mark::hit!(lifetime_hints_single);
268+
return None;
269+
}
270+
271+
// apply hints
241272
// apply output if required
242273
match (&output, ret_type) {
243274
(Some(output_lt), Some(r)) => {
@@ -800,14 +831,14 @@ mod tests {
800831
use syntax::{TextRange, TextSize};
801832
use test_utils::extract_annotations;
802833

803-
use crate::{fixture, inlay_hints::InlayHintsConfig};
834+
use crate::{fixture, inlay_hints::InlayHintsConfig, LifetimeElisionHints};
804835

805836
const DISABLED_CONFIG: InlayHintsConfig = InlayHintsConfig {
806837
render_colons: false,
807838
type_hints: false,
808839
parameter_hints: false,
809840
chaining_hints: false,
810-
lifetime_elision_hints: false,
841+
lifetime_elision_hints: LifetimeElisionHints::Never,
811842
hide_named_constructor_hints: false,
812843
closure_return_type_hints: false,
813844
param_names_for_lifetime_elision_hints: false,
@@ -818,7 +849,7 @@ mod tests {
818849
parameter_hints: true,
819850
chaining_hints: true,
820851
closure_return_type_hints: true,
821-
lifetime_elision_hints: true,
852+
lifetime_elision_hints: LifetimeElisionHints::Always,
822853
..DISABLED_CONFIG
823854
};
824855

@@ -2037,6 +2068,47 @@ impl () {
20372068
// ^^^<'0, '1>
20382069
// ^'0 ^'1 ^'0
20392070
}
2071+
"#,
2072+
);
2073+
}
2074+
2075+
#[test]
2076+
fn hints_lifetimes_named() {
2077+
check_with_config(
2078+
InlayHintsConfig { param_names_for_lifetime_elision_hints: true, ..TEST_CONFIG },
2079+
r#"
2080+
fn nested_in<'named>(named: & &X< &()>) {}
2081+
// ^'named1, 'named2, 'named3, $
2082+
//^'named1 ^'named2 ^'named3
2083+
"#,
2084+
);
2085+
}
2086+
2087+
#[test]
2088+
fn hints_lifetimes_skingle_skip() {
2089+
cov_mark::check!(lifetime_hints_single);
2090+
check_with_config(
2091+
InlayHintsConfig {
2092+
lifetime_elision_hints: LifetimeElisionHints::SkipTrivial,
2093+
..TEST_CONFIG
2094+
},
2095+
r#"
2096+
fn single(a: &()) -> &() {}
2097+
2098+
fn double(a: &(), b: &()) {}
2099+
// ^^^^^^<'0, '1>
2100+
// ^'0 ^'1
2101+
fn partial<'a>(a: &'a (), b: &()) {}
2102+
//^'0, $ ^'0
2103+
fn partial2<'a>(a: &'a ()) -> &() {}
2104+
//^'a
2105+
2106+
impl () {
2107+
fn foo(&self) -> &() {}
2108+
fn foo(&self, a: &()) -> &() {}
2109+
// ^^^<'0, '1>
2110+
// ^'0 ^'1 ^'0
2111+
}
20402112
"#,
20412113
);
20422114
}

crates/ide/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ pub use crate::{
8181
folding_ranges::{Fold, FoldKind},
8282
highlight_related::{HighlightRelatedConfig, HighlightedRange},
8383
hover::{HoverAction, HoverConfig, HoverDocFormat, HoverGotoTypeData, HoverResult},
84-
inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
84+
inlay_hints::{InlayHint, InlayHintsConfig, InlayKind, LifetimeElisionHints},
8585
join_lines::JoinLinesConfig,
8686
markup::Markup,
8787
moniker::{MonikerKind, MonikerResult, PackageInformation},

crates/ide/src/static_index.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,14 @@ use ide_db::{
1212
use rustc_hash::FxHashSet;
1313
use syntax::{AstNode, SyntaxKind::*, SyntaxToken, TextRange, T};
1414

15-
use crate::moniker::{crate_for_file, def_to_moniker, MonikerResult};
1615
use crate::{
1716
hover::hover_for_definition, Analysis, Fold, HoverConfig, HoverDocFormat, HoverResult,
1817
InlayHint, InlayHintsConfig, TryToNav,
1918
};
19+
use crate::{
20+
moniker::{crate_for_file, def_to_moniker, MonikerResult},
21+
LifetimeElisionHints,
22+
};
2023

2124
/// A static representation of fully analyzed source code.
2225
///
@@ -110,7 +113,7 @@ impl StaticIndex<'_> {
110113
parameter_hints: true,
111114
chaining_hints: true,
112115
closure_return_type_hints: true,
113-
lifetime_elision_hints: false,
116+
lifetime_elision_hints: LifetimeElisionHints::Never,
114117
hide_named_constructor_hints: false,
115118
param_names_for_lifetime_elision_hints: false,
116119
max_length: Some(25),

crates/rust-analyzer/src/config.rs

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ use std::{ffi::OsString, iter, path::PathBuf};
1212
use flycheck::FlycheckConfig;
1313
use ide::{
1414
AssistConfig, CompletionConfig, DiagnosticsConfig, ExprFillDefaultMode, HighlightRelatedConfig,
15-
HoverConfig, HoverDocFormat, InlayHintsConfig, JoinLinesConfig, Snippet, SnippetScope,
15+
HoverConfig, HoverDocFormat, InlayHintsConfig, JoinLinesConfig, LifetimeElisionHints, Snippet,
16+
SnippetScope,
1617
};
1718
use ide_db::{
1819
imports::insert_use::{ImportGranularity, InsertUseConfig, PrefixKind},
@@ -248,19 +249,19 @@ config_data! {
248249
inlayHints_maxLength: Option<usize> = "25",
249250
/// Whether to show function parameter name inlay hints at the call
250251
/// site.
251-
inlayHints_parameterHints: bool = "true",
252+
inlayHints_parameterHints: bool = "true",
252253
/// Whether to show inlay type hints for variables.
253-
inlayHints_typeHints: bool = "true",
254+
inlayHints_typeHints: bool = "true",
254255
/// Whether to show inlay type hints for method chains.
255-
inlayHints_chainingHints: bool = "true",
256+
inlayHints_chainingHints: bool = "true",
256257
/// Whether to show inlay type hints for return types of closures with blocks.
257-
inlayHints_closureReturnTypeHints: bool = "false",
258+
inlayHints_closureReturnTypeHints: bool = "false",
258259
/// Whether to show inlay type hints for elided lifetimes in function signatures.
259-
inlayHints_lifetimeElisionHints: bool = "false",
260+
inlayHints_lifetimeElisionHints: LifetimeElisionDef = "\"never\"",
260261
/// Whether to show prefer using parameter names as the name for elided lifetime hints.
261-
inlayHints_paramNamesForLifetimeElisionHints: bool = "false",
262+
inlayHints_paramNamesForLifetimeElisionHints: bool = "false",
262263
/// Whether to hide inlay hints for constructors.
263-
inlayHints_hideNamedConstructorHints: bool = "false",
264+
inlayHints_hideNamedConstructorHints: bool = "false",
264265

265266
/// Join lines inserts else between consecutive ifs.
266267
joinLines_joinElseIf: bool = "true",
@@ -859,7 +860,11 @@ impl Config {
859860
parameter_hints: self.data.inlayHints_parameterHints,
860861
chaining_hints: self.data.inlayHints_chainingHints,
861862
closure_return_type_hints: self.data.inlayHints_closureReturnTypeHints,
862-
lifetime_elision_hints: self.data.inlayHints_lifetimeElisionHints,
863+
lifetime_elision_hints: match self.data.inlayHints_lifetimeElisionHints {
864+
LifetimeElisionDef::Always => LifetimeElisionHints::Always,
865+
LifetimeElisionDef::Never => LifetimeElisionHints::Never,
866+
LifetimeElisionDef::SkipTrivial => LifetimeElisionHints::SkipTrivial,
867+
},
863868
hide_named_constructor_hints: self.data.inlayHints_hideNamedConstructorHints,
864869
param_names_for_lifetime_elision_hints: self
865870
.data
@@ -1133,6 +1138,16 @@ enum ImportGranularityDef {
11331138
Module,
11341139
}
11351140

1141+
#[derive(Deserialize, Debug, Clone)]
1142+
#[serde(rename_all = "snake_case")]
1143+
enum LifetimeElisionDef {
1144+
#[serde(alias = "true")]
1145+
Always,
1146+
#[serde(alias = "false")]
1147+
Never,
1148+
SkipTrivial,
1149+
}
1150+
11361151
#[derive(Deserialize, Debug, Clone)]
11371152
#[serde(rename_all = "snake_case")]
11381153
enum ImportPrefixDef {
@@ -1385,7 +1400,16 @@ fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json
13851400
"minimum": 0,
13861401
"maximum": 255
13871402
},
1388-
_ => panic!("{}: {}", ty, default),
1403+
"LifetimeElisionDef" => set! {
1404+
"type": "string",
1405+
"enum": ["always", "never", "skip_trivial"],
1406+
"enumDescriptions": [
1407+
"Always show lifetime elision hints.",
1408+
"Never show lifetime elision hints.",
1409+
"Always show lifetime elision hints but skip them for trivial single input to output mapping."
1410+
],
1411+
},
1412+
_ => panic!("missing entry for {}: {}", ty, default),
13891413
}
13901414

13911415
map.into()

docs/user/generated_config.adoc

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,16 @@ Whether to show inlay type hints for method chains.
378378
--
379379
Whether to show inlay type hints for return types of closures with blocks.
380380
--
381+
[[rust-analyzer.inlayHints.lifetimeElisionHints]]rust-analyzer.inlayHints.lifetimeElisionHints (default: `"never"`)::
382+
+
383+
--
384+
Whether to show inlay type hints for elided lifetimes in function signatures.
385+
--
386+
[[rust-analyzer.inlayHints.paramNamesForLifetimeElisionHints]]rust-analyzer.inlayHints.paramNamesForLifetimeElisionHints (default: `false`)::
387+
+
388+
--
389+
Whether to show prefer using parameter names as the name for elided lifetime hints.
390+
--
381391
[[rust-analyzer.inlayHints.hideNamedConstructorHints]]rust-analyzer.inlayHints.hideNamedConstructorHints (default: `false`)::
382392
+
383393
--

0 commit comments

Comments
 (0)