Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions compiler/rustc_parse/src/parser/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,44 @@ impl<'a> Parser<'a> {
let mut generics = if self.choose_generics_over_qpath(0) {
self.parse_generics()?
} else {
// We might be mistakenly trying to use a generic type as a generic parameter.
// impl<X<T>> Trait for Y<T> { ... }
if self.look_ahead(0, |t| t == &token::Lt)
&& self.look_ahead(1, |t| t.is_ident())
&& self.look_ahead(2, |t| t == &token::Lt)
{
self.bump(); // <
let ident = self.parse_ident()?;
let generics = self.parse_generics()?;
let span = ident.span.to(generics.span);
let snippet = self.span_to_snippet(span).unwrap();

let msg = format!("expected type parameter, found path `{}`", snippet);
let mut err = self.dcx().struct_span_err(span, msg);
err.span_label(span, "expected type parameter, found path");
err.span_suggestion(
span,
"you might have meant to bind a type parameter to a trait",
format!("T: {snippet}"),
Applicability::Unspecified,
);

let mut mapped = String::new();
for i in 0..generics.params.len() {
mapped += &format!("{}: {}", generics.params[i].ident, ident);
if i != (generics.params.len() - 1) {
mapped += ", ";
}
}
err.span_suggestion(span, if generics.params.len() == 1 {
format!("alternatively, you might have meant to bind type parameter `{}` to trait `{}`", generics.params[0].ident.name.as_str(), ident.name.as_str())
} else {
format!("alternatively, you might have meant to bind type parameters to trait `{}`", ident.name.as_str())
}, mapped, Applicability::Unspecified);

return Err(err);
}

let mut generics = Generics::default();
// impl A for B {}
// /\ this is where `generics.span` should point when there are no type params.
Expand Down
1 change: 1 addition & 0 deletions tests/ui/impl-trait/type-as-type-param.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
impl<Y<A, B, C>> Z for X<T> {} //~ ERROR: expected type parameter, found path `Y<A, B, C>`
18 changes: 18 additions & 0 deletions tests/ui/impl-trait/type-as-type-param.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
error: expected type parameter, found path `Y<A, B, C>`
--> $DIR/type-as-type-param.rs:1:6
|
LL | impl<Y<A, B, C>> Z for X<T> {}
| ^^^^^^^^^^ expected type parameter, found path
|
help: you might have meant to bind a type parameter to a trait
|
LL | impl<T: Y<A, B, C>> Z for X<T> {}
| ++
help: alternatively, you might have meant to bind type parameters to trait `Y`
|
LL - impl<Y<A, B, C>> Z for X<T> {}
LL + impl<A: Y, B: Y, C: Y> Z for X<T> {}
|

error: aborting due to 1 previous error

Loading