internal: Cleanup lifetime elision hints

This commit is contained in:
Lukas Wirth 2022-05-17 12:18:07 +02:00
parent ce9b174f8a
commit 12d5343993

View File

@ -47,13 +47,13 @@ pub enum ReborrowHints {
pub enum InlayKind { pub enum InlayKind {
BindingModeHint, BindingModeHint,
ChainingHint, ChainingHint,
ClosingBraceHint,
ClosureReturnTypeHint, ClosureReturnTypeHint,
GenericParamListHint, GenericParamListHint,
ImplicitReborrowHint, ImplicitReborrowHint,
LifetimeHint, LifetimeHint,
ParameterHint, ParameterHint,
TypeHint, TypeHint,
ClosingBraceHint,
} }
#[derive(Debug)] #[derive(Debug)]
@ -127,28 +127,33 @@ fn hints(
}; };
closing_brace_hints(hints, sema, config, node.clone()); closing_brace_hints(hints, sema, config, node.clone());
match_ast! {
if let Some(expr) = ast::Expr::cast(node.clone()) { match node {
chaining_hints(hints, sema, &famous_defs, config, &expr); ast::Expr(expr) => {
match expr { chaining_hints(hints, sema, &famous_defs, config, &expr);
ast::Expr::CallExpr(it) => param_name_hints(hints, sema, config, ast::Expr::from(it)), match expr {
ast::Expr::MethodCallExpr(it) => { ast::Expr::CallExpr(it) => param_name_hints(hints, sema, config, ast::Expr::from(it)),
param_name_hints(hints, sema, config, ast::Expr::from(it)) ast::Expr::MethodCallExpr(it) => {
} param_name_hints(hints, sema, config, ast::Expr::from(it))
ast::Expr::ClosureExpr(it) => closure_ret_hints(hints, sema, &famous_defs, config, it), }
// We could show reborrows for all expressions, but usually that is just noise to the user ast::Expr::ClosureExpr(it) => closure_ret_hints(hints, sema, &famous_defs, config, it),
// and the main point here is to show why "moving" a mutable reference doesn't necessarily move it // We could show reborrows for all expressions, but usually that is just noise to the user
ast::Expr::PathExpr(_) => reborrow_hints(hints, sema, config, &expr), // and the main point here is to show why "moving" a mutable reference doesn't necessarily move it
_ => None, ast::Expr::PathExpr(_) => reborrow_hints(hints, sema, config, &expr),
}; _ => None,
} else if let Some(it) = ast::Pat::cast(node.clone()) { }
binding_mode_hints(hints, sema, config, &it); },
if let ast::Pat::IdentPat(it) = it { ast::Pat(it) => {
bind_pat_hints(hints, sema, config, &it); binding_mode_hints(hints, sema, config, &it);
if let ast::Pat::IdentPat(it) = it {
bind_pat_hints(hints, sema, config, &it);
}
Some(())
},
ast::Fn(it) => lifetime_fn_hints(hints, config, it),
_ => Some(()),
} }
} else if let Some(it) = ast::Fn::cast(node) { };
lifetime_hints(hints, config, it);
}
} }
fn closing_brace_hints( fn closing_brace_hints(
@ -249,7 +254,7 @@ fn closing_brace_hints(
None None
} }
fn lifetime_hints( fn lifetime_fn_hints(
acc: &mut Vec<InlayHint>, acc: &mut Vec<InlayHint>,
config: &InlayHintsConfig, config: &InlayHintsConfig,
func: ast::Fn, func: ast::Fn,
@ -262,15 +267,41 @@ fn lifetime_hints(
let ret_type = func.ret_type(); let ret_type = func.ret_type();
let self_param = param_list.self_param().filter(|it| it.amp_token().is_some()); let self_param = param_list.self_param().filter(|it| it.amp_token().is_some());
let mut used_names: FxHashMap<SmolStr, usize> = generic_param_list let is_elided = |lt: &Option<ast::Lifetime>| match lt {
.iter() Some(lt) => matches!(lt.text().as_str(), "'_"),
.filter(|_| config.param_names_for_lifetime_elision_hints) None => true,
.flat_map(|gpl| gpl.lifetime_params()) };
.filter_map(|param| param.lifetime())
.filter_map(|lt| Some((SmolStr::from(lt.text().as_str().get(1..)?), 0)))
.collect();
let mut allocated_lifetimes = vec![]; let potential_lt_refs = {
let mut acc: Vec<_> = vec![];
if let Some(self_param) = &self_param {
let lifetime = self_param.lifetime();
let is_elided = is_elided(&lifetime);
acc.push((None, self_param.amp_token(), lifetime, is_elided));
}
param_list.params().filter_map(|it| Some((it.pat(), it.ty()?))).for_each(|(pat, ty)| {
// FIXME: check path types
walk_ty(&ty, &mut |ty| match ty {
ast::Type::RefType(r) => {
let lifetime = r.lifetime();
let is_elided = is_elided(&lifetime);
acc.push((
pat.as_ref().and_then(|it| match it {
ast::Pat::IdentPat(p) => p.name(),
_ => None,
}),
r.amp_token(),
lifetime,
is_elided,
))
}
_ => (),
})
});
acc
};
// allocate names
let mut gen_idx_name = { let mut gen_idx_name = {
let mut gen = (0u8..).map(|idx| match idx { let mut gen = (0u8..).map(|idx| match idx {
idx if idx < 10 => SmolStr::from_iter(['\'', (idx + 48) as char]), idx if idx < 10 => SmolStr::from_iter(['\'', (idx + 48) as char]),
@ -278,64 +309,33 @@ fn lifetime_hints(
}); });
move || gen.next().unwrap_or_default() move || gen.next().unwrap_or_default()
}; };
let mut allocated_lifetimes = vec![];
let mut potential_lt_refs: Vec<_> = vec![]; let mut used_names: FxHashMap<SmolStr, usize> =
param_list match config.param_names_for_lifetime_elision_hints {
.params() true => generic_param_list
.filter_map(|it| { .iter()
Some(( .flat_map(|gpl| gpl.lifetime_params())
config.param_names_for_lifetime_elision_hints.then(|| it.pat()).flatten(), .filter_map(|param| param.lifetime())
it.ty()?, .filter_map(|lt| Some((SmolStr::from(lt.text().as_str().get(1..)?), 0)))
)) .collect(),
}) false => Default::default(),
.for_each(|(pat, ty)| { };
// FIXME: check path types {
walk_ty(&ty, &mut |ty| match ty { let mut potential_lt_refs = potential_lt_refs.iter().filter(|&&(.., is_elided)| is_elided);
ast::Type::RefType(r) => potential_lt_refs.push(( if let Some(_) = &self_param {
pat.as_ref().and_then(|it| match it { if let Some(_) = potential_lt_refs.next() {
ast::Pat::IdentPat(p) => p.name(), allocated_lifetimes.push(if config.param_names_for_lifetime_elision_hints {
_ => None, // self can't be used as a lifetime, so no need to check for collisions
}), "'self".into()
r, } else {
)), gen_idx_name()
_ => (), });
}) }
});
enum LifetimeKind {
Elided,
Named(SmolStr),
Static,
}
let fetch_lt_text = |lt: Option<ast::Lifetime>| match lt {
Some(lt) => match lt.text().as_str() {
"'_" => LifetimeKind::Elided,
"'static" => LifetimeKind::Static,
name => LifetimeKind::Named(name.into()),
},
None => LifetimeKind::Elided,
};
let is_elided = |lt: Option<ast::Lifetime>| match lt {
Some(lt) => matches!(lt.text().as_str(), "'_"),
None => true,
};
// allocate names
if let Some(self_param) = &self_param {
if is_elided(self_param.lifetime()) {
allocated_lifetimes.push(if config.param_names_for_lifetime_elision_hints {
// self can't be used as a lifetime, so no need to check for collisions
"'self".into()
} else {
gen_idx_name()
});
} }
} potential_lt_refs.for_each(|(name, ..)| {
potential_lt_refs.iter().for_each(|(name, it)| {
if is_elided(it.lifetime()) {
let name = match name { let name = match name {
Some(it) => { Some(it) if config.param_names_for_lifetime_elision_hints => {
if let Some(c) = used_names.get_mut(it.text().as_str()) { if let Some(c) = used_names.get_mut(it.text().as_str()) {
*c += 1; *c += 1;
SmolStr::from(format!("'{text}{c}", text = it.text().as_str())) SmolStr::from(format!("'{text}{c}", text = it.text().as_str()))
@ -347,26 +347,22 @@ fn lifetime_hints(
_ => gen_idx_name(), _ => gen_idx_name(),
}; };
allocated_lifetimes.push(name); allocated_lifetimes.push(name);
} });
}); }
// fetch output lifetime if elision rule applies // fetch output lifetime if elision rule applies
let output = match potential_lt_refs.as_slice() {
let output = if let Some(self_param) = &self_param { [(_, _, lifetime, _), ..] if self_param.is_some() || potential_lt_refs.len() == 1 => {
match fetch_lt_text(self_param.lifetime()) { match lifetime {
LifetimeKind::Elided => allocated_lifetimes.get(0).cloned(), Some(lt) => match lt.text().as_str() {
LifetimeKind::Named(name) => Some(name), "'_" => allocated_lifetimes.get(0).cloned(),
LifetimeKind::Static => None, "'static" => None,
} name => Some(name.into()),
} else { },
match potential_lt_refs.as_slice() { None => allocated_lifetimes.get(0).cloned(),
[(_, r)] => match fetch_lt_text(r.lifetime()) { }
LifetimeKind::Elided => allocated_lifetimes.get(0).cloned(),
LifetimeKind::Named(name) => Some(name),
LifetimeKind::Static => None,
},
[..] => None,
} }
[..] => None,
}; };
if allocated_lifetimes.is_empty() && output.is_none() { if allocated_lifetimes.is_empty() && output.is_none() {
@ -398,27 +394,12 @@ fn lifetime_hints(
return None; return None;
} }
let mut idx = match &self_param { let mut a = allocated_lifetimes.iter();
Some(self_param) if is_elided(self_param.lifetime()) => { for (_, amp_token, _, is_elided) in potential_lt_refs {
if let Some(amp) = self_param.amp_token() { if is_elided {
let lt = allocated_lifetimes[0].clone(); let t = amp_token?;
acc.push(InlayHint { let lt = a.next()?.clone();
range: amp.text_range(),
kind: InlayKind::LifetimeHint,
label: lt,
});
}
1
}
_ => 0,
};
for (_, p) in potential_lt_refs.iter() {
if is_elided(p.lifetime()) {
let t = p.amp_token()?;
let lt = allocated_lifetimes[idx].clone();
acc.push(InlayHint { range: t.text_range(), kind: InlayKind::LifetimeHint, label: lt }); acc.push(InlayHint { range: t.text_range(), kind: InlayKind::LifetimeHint, label: lt });
idx += 1;
} }
} }