Suggest _ for missing generic arguments in turbofish

This commit is contained in:
Kornel 2024-03-17 17:27:35 +00:00
parent 35dfc67d94
commit 55067c539a
3 changed files with 50 additions and 8 deletions

View File

@ -435,6 +435,22 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
&self,
num_params_to_take: usize,
) -> String {
let is_in_a_method_call = self
.tcx
.hir()
.parent_iter(self.path_segment.hir_id)
.skip(1)
.find_map(|(_, node)| match node {
hir::Node::Expr(expr) => Some(expr),
_ => None,
})
.is_some_and(|expr| {
matches!(
expr.kind,
hir::ExprKind::MethodCall(hir::PathSegment { args: Some(_), .. }, ..)
)
});
let fn_sig = self.tcx.hir().get_if_local(self.def_id).and_then(hir::Node::fn_sig);
let is_used_in_input = |def_id| {
fn_sig.is_some_and(|fn_sig| {
@ -453,14 +469,17 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
.skip(self.params_offset + self.num_provided_type_or_const_args())
.take(num_params_to_take)
.map(|param| match param.kind {
// This is being inferred from the item's inputs, no need to set it.
ty::GenericParamDefKind::Type { .. } if is_used_in_input(param.def_id) => {
"_".to_string()
// If it's in method call (turbofish), it might be inferred from the expression (e.g. `.collect::<Vec<_>>()`)
// If it is being inferred from the item's inputs, no need to set it.
ty::GenericParamDefKind::Type { .. }
if is_in_a_method_call || is_used_in_input(param.def_id) =>
{
"_"
}
_ => param.name.to_string(),
_ => param.name.as_str(),
})
.collect::<Vec<_>>()
.join(", ")
.intersperse(", ")
.collect()
}
fn get_unbound_associated_types(&self) -> Vec<String> {

View File

@ -5,7 +5,14 @@ struct Heap;
struct Vec<T, A = Heap>(
marker::PhantomData<(T,A)>);
struct HashMap<K, V, S = ()>(marker::PhantomData<(K,V,S)>);
fn main() {
let _: Vec;
//~^ ERROR missing generics for struct `Vec`
//~| SUGGESTION <T>
let _x = (1..10).collect::<HashMap>();
//~^ ERROR missing generics for struct `HashMap`
//~| SUGGESTION <_, _>
}

View File

@ -1,5 +1,5 @@
error[E0107]: missing generics for struct `Vec`
--> $DIR/generic-type-less-params-with-defaults.rs:9:12
--> $DIR/generic-type-less-params-with-defaults.rs:11:12
|
LL | let _: Vec;
| ^^^ expected at least 1 generic argument
@ -14,6 +14,22 @@ help: add missing generic argument
LL | let _: Vec<T>;
| +++
error: aborting due to 1 previous error
error[E0107]: missing generics for struct `HashMap`
--> $DIR/generic-type-less-params-with-defaults.rs:15:32
|
LL | let _x = (1..10).collect::<HashMap>();
| ^^^^^^^ expected at least 2 generic arguments
|
note: struct defined here, with at least 2 generic parameters: `K`, `V`
--> $DIR/generic-type-less-params-with-defaults.rs:8:8
|
LL | struct HashMap<K, V, S = ()>(marker::PhantomData<(K,V,S)>);
| ^^^^^^^ - -
help: add missing generic arguments
|
LL | let _x = (1..10).collect::<HashMap<_, _>>();
| ++++++
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0107`.