Skip to content

Commit f7b3ba5

Browse files
committed
Suggest trait bounds for used associated type on type param
Fix #101351. When an associated type on a type parameter is used, and the type parameter isn't constrained by the correct trait, suggest the appropriate trait bound: ``` error[E0220]: associated type `Associated` not found for `T` --> file.rs:6:15 | 6 | field: T::Associated, | ^^^^^^^^^^ there is a similarly named associated type `Associated` in the trait `Foo` | help: consider restricting type parameter `T` | 5 | struct Generic<T: Foo> { | +++++ ``` When an associated type on a type parameter has a typo, suggest fixing it: ``` error[E0220]: associated type `Baa` not found for `T` --> $DIR/issue-55673.rs:9:8 | LL | T::Baa: std::fmt::Debug, | ^^^ there is a similarly named associated type `Bar` in the trait `Foo` | help: change the associated type name to use `Bar` from `Foo` | LL | T::Bar: std::fmt::Debug, | ~~~ ```
1 parent dd91aba commit f7b3ba5

File tree

10 files changed

+112
-18
lines changed

10 files changed

+112
-18
lines changed

compiler/rustc_hir_analysis/src/astconv/bounds.rs

+1
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ {
284284
self.one_bound_for_assoc_type(
285285
|| traits::supertraits(tcx, trait_ref),
286286
trait_ref.skip_binder().print_only_trait_name(),
287+
None,
287288
binding.item_name,
288289
path_span,
289290
match binding.kind {

compiler/rustc_hir_analysis/src/astconv/errors.rs

+52-5
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,9 @@ use crate::errors::{
66
use rustc_data_structures::fx::FxHashMap;
77
use rustc_errors::{pluralize, struct_span_err, Applicability, Diagnostic, ErrorGuaranteed};
88
use rustc_hir as hir;
9-
use rustc_hir::def_id::DefId;
9+
use rustc_hir::def_id::{DefId, LocalDefId};
1010
use rustc_infer::traits::FulfillmentError;
11-
use rustc_middle::ty::TyCtxt;
12-
use rustc_middle::ty::{self, Ty};
11+
use rustc_middle::ty::{self, suggest_constraining_type_param, Ty, TyCtxt};
1312
use rustc_session::parse::feature_err;
1413
use rustc_span::edit_distance::find_best_match_for_name;
1514
use rustc_span::symbol::{sym, Ident};
@@ -102,6 +101,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
102101
&self,
103102
all_candidates: impl Fn() -> I,
104103
ty_param_name: &str,
104+
ty_param_def_id: Option<LocalDefId>,
105105
assoc_name: Ident,
106106
span: Span,
107107
) -> ErrorGuaranteed
@@ -190,13 +190,60 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
190190
})
191191
.collect::<Vec<_>>()[..]
192192
{
193+
let trait_name = self.tcx().def_path_str(*best_trait);
193194
err.span_label(
194195
assoc_name.span,
195196
format!(
196-
"there is a similarly named associated type `{suggested_name}` in the trait `{}`",
197-
self.tcx().def_path_str(*best_trait)
197+
"there is a similarly named associated type `{suggested_name}` in the \
198+
trait `{trait_name}`",
198199
),
199200
);
201+
let hir = self.tcx().hir();
202+
if let Some(def_id) = ty_param_def_id
203+
&& let parent = hir.get_parent_item(hir.local_def_id_to_hir_id(def_id))
204+
&& let Some(generics) = hir.get_generics(parent.def_id)
205+
{
206+
if generics.bounds_for_param(def_id)
207+
.flat_map(|pred| pred.bounds.iter())
208+
.any(|b| match b {
209+
hir::GenericBound::Trait(t, ..) => {
210+
t.trait_ref.trait_def_id().as_ref() == Some(best_trait)
211+
}
212+
_ => false,
213+
})
214+
{
215+
// The type param already has a bound for `trait_name`, we just need to
216+
// change the associated type.
217+
err.span_suggestion_verbose(
218+
assoc_name.span,
219+
format!(
220+
"change the associated type name to use `{suggested_name}` from \
221+
`{trait_name}`",
222+
),
223+
suggested_name.to_string(),
224+
Applicability::MaybeIncorrect,
225+
);
226+
} else if suggest_constraining_type_param(
227+
self.tcx(),
228+
generics,
229+
&mut err,
230+
&ty_param_name,
231+
&trait_name,
232+
None,
233+
None,
234+
)
235+
&& suggested_name != assoc_name.name
236+
{
237+
// We suggested constraining a type parameter, but the associated type on it
238+
// was also not an exact match, so we also suggest changing it.
239+
err.span_suggestion_verbose(
240+
assoc_name.span,
241+
"and also change the associated type name",
242+
suggested_name.to_string(),
243+
Applicability::MaybeIncorrect,
244+
);
245+
}
246+
}
200247
return err.emit();
201248
}
202249
}

compiler/rustc_hir_analysis/src/astconv/mod.rs

+9-10
Original file line numberDiff line numberDiff line change
@@ -1061,6 +1061,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
10611061
)
10621062
},
10631063
param_name,
1064+
Some(ty_param_def_id),
10641065
assoc_name,
10651066
span,
10661067
None,
@@ -1074,6 +1075,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
10741075
&self,
10751076
all_candidates: impl Fn() -> I,
10761077
ty_param_name: impl Display,
1078+
ty_param_def_id: Option<LocalDefId>,
10771079
assoc_name: Ident,
10781080
span: Span,
10791081
is_equality: Option<ty::Term<'tcx>>,
@@ -1095,6 +1097,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
10951097
let reported = self.complain_about_assoc_type_not_found(
10961098
all_candidates,
10971099
&ty_param_name.to_string(),
1100+
ty_param_def_id,
10981101
assoc_name,
10991102
span,
11001103
);
@@ -1142,39 +1145,34 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
11421145
err.span_label(
11431146
bound_span,
11441147
format!(
1145-
"ambiguous `{}` from `{}`",
1146-
assoc_name,
1148+
"ambiguous `{assoc_name}` from `{}`",
11471149
bound.print_only_trait_path(),
11481150
),
11491151
);
11501152
if let Some(constraint) = &is_equality {
11511153
where_bounds.push(format!(
1152-
" T: {trait}::{assoc} = {constraint}",
1154+
" T: {trait}::{assoc_name} = {constraint}",
11531155
trait=bound.print_only_trait_path(),
1154-
assoc=assoc_name,
1155-
constraint=constraint,
11561156
));
11571157
} else {
11581158
err.span_suggestion_verbose(
11591159
span.with_hi(assoc_name.span.lo()),
11601160
"use fully qualified syntax to disambiguate",
1161-
format!("<{} as {}>::", ty_param_name, bound.print_only_trait_path()),
1161+
format!("<{ty_param_name} as {}>::", bound.print_only_trait_path()),
11621162
Applicability::MaybeIncorrect,
11631163
);
11641164
}
11651165
} else {
11661166
err.note(format!(
1167-
"associated type `{}` could derive from `{}`",
1168-
ty_param_name,
1167+
"associated type `{ty_param_name}` could derive from `{}`",
11691168
bound.print_only_trait_path(),
11701169
));
11711170
}
11721171
}
11731172
if !where_bounds.is_empty() {
11741173
err.help(format!(
11751174
"consider introducing a new type parameter `T` and adding `where` constraints:\
1176-
\n where\n T: {},\n{}",
1177-
ty_param_name,
1175+
\n where\n T: {ty_param_name},\n{}",
11781176
where_bounds.join(",\n"),
11791177
));
11801178
}
@@ -1394,6 +1392,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
13941392
)
13951393
},
13961394
kw::SelfUpper,
1395+
None,
13971396
assoc_ident,
13981397
span,
13991398
None,

compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -
364364
/// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
365365
/// it can also be an `impl Trait` param that needs to be decomposed to a type
366366
/// param for cleaner code.
367-
fn suggest_restriction<'tcx>(
367+
pub fn suggest_restriction<'tcx>(
368368
tcx: TyCtxt<'tcx>,
369369
item_id: LocalDefId,
370370
hir_generics: &hir::Generics<'tcx>,

tests/ui/resolve/issue-55673.fixed

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// run-rustfix
2+
#![allow(dead_code)]
3+
trait Foo {
4+
type Bar;
5+
}
6+
7+
fn foo<T: Foo>()
8+
where
9+
T::Bar: std::fmt::Debug,
10+
//~^ ERROR associated type `Baa` not found for `T`
11+
{
12+
}
13+
14+
fn main() {}

tests/ui/resolve/issue-55673.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// run-rustfix
2+
#![allow(dead_code)]
13
trait Foo {
24
type Bar;
35
}

tests/ui/resolve/issue-55673.stderr

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
error[E0220]: associated type `Baa` not found for `T`
2-
--> $DIR/issue-55673.rs:7:8
2+
--> $DIR/issue-55673.rs:9:8
33
|
44
LL | T::Baa: std::fmt::Debug,
55
| ^^^ there is a similarly named associated type `Bar` in the trait `Foo`
6+
|
7+
help: change the associated type name to use `Bar` from `Foo`
8+
|
9+
LL | T::Bar: std::fmt::Debug,
10+
| ~~~
611

712
error: aborting due to previous error
813

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// run-rustfix
2+
#![feature(type_alias_impl_trait)]
3+
#![allow(dead_code)]
4+
5+
fn main() {}
6+
7+
trait TraitWithAssoc {
8+
type Assoc;
9+
}
10+
11+
type Foo<V: TraitWithAssoc> = impl Trait<V::Assoc>; //~ associated type `Assoc` not found for `V`
12+
13+
trait Trait<U> {}
14+
15+
impl<W> Trait<W> for () {}
16+
17+
fn foo_desugared<T: TraitWithAssoc>(_: T) -> Foo<T> {
18+
()
19+
}

tests/ui/type-alias-impl-trait/not_well_formed.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
// run-rustfix
12
#![feature(type_alias_impl_trait)]
3+
#![allow(dead_code)]
24

35
fn main() {}
46

tests/ui/type-alias-impl-trait/not_well_formed.stderr

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
error[E0220]: associated type `Assoc` not found for `V`
2-
--> $DIR/not_well_formed.rs:9:29
2+
--> $DIR/not_well_formed.rs:11:29
33
|
44
LL | type Foo<V> = impl Trait<V::Assoc>;
55
| ^^^^^ there is a similarly named associated type `Assoc` in the trait `TraitWithAssoc`
6+
|
7+
help: consider restricting type parameter `V`
8+
|
9+
LL | type Foo<V: TraitWithAssoc> = impl Trait<V::Assoc>;
10+
| ++++++++++++++++
611

712
error: aborting due to previous error
813

0 commit comments

Comments
 (0)