Skip to content

Commit 5da1b41

Browse files
E0229: Suggest Moving Type Constraints to Type Parameter Declaration
1 parent 6d19ac3 commit 5da1b41

File tree

6 files changed

+105
-13
lines changed

6 files changed

+105
-13
lines changed

compiler/rustc_hir/src/hir.rs

+24
Original file line numberDiff line numberDiff line change
@@ -2456,6 +2456,15 @@ pub enum AssocItemConstraintKind<'hir> {
24562456
Bound { bounds: &'hir [GenericBound<'hir>] },
24572457
}
24582458

2459+
impl<'hir> AssocItemConstraintKind<'hir> {
2460+
pub fn descr(&self) -> &'static str {
2461+
match self {
2462+
AssocItemConstraintKind::Equality { .. } => "binding",
2463+
AssocItemConstraintKind::Bound { .. } => "constraint",
2464+
}
2465+
}
2466+
}
2467+
24592468
#[derive(Debug, Clone, Copy, HashStable_Generic)]
24602469
pub struct Ty<'hir> {
24612470
pub hir_id: HirId,
@@ -3735,6 +3744,21 @@ impl<'hir> Node<'hir> {
37353744
}
37363745
}
37373746

3747+
/// Get a `hir::Impl` if the node is an impl block for the given `trait_def_id`.
3748+
pub fn impl_block_of_trait(self, trait_def_id: DefId) -> Option<&'hir Impl<'hir>> {
3749+
match self {
3750+
Node::Item(Item { kind: ItemKind::Impl(impl_block), .. })
3751+
if impl_block
3752+
.of_trait
3753+
.and_then(|trait_ref| trait_ref.trait_def_id())
3754+
.is_some_and(|trait_id| trait_id == trait_def_id) =>
3755+
{
3756+
Some(impl_block)
3757+
}
3758+
_ => None,
3759+
}
3760+
}
3761+
37383762
pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
37393763
match self {
37403764
Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })

compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs

+62-9
Original file line numberDiff line numberDiff line change
@@ -1217,7 +1217,6 @@ pub fn prohibit_assoc_item_constraint(
12171217
// otherwise suggest the removal of the binding.
12181218
if let Some((def_id, segment, _)) = segment
12191219
&& segment.args().parenthesized == hir::GenericArgsParentheses::No
1220-
&& let hir::AssocItemConstraintKind::Equality { term } = constraint.kind
12211220
{
12221221
// Suggests removal of the offending binding
12231222
let suggest_removal = |e: &mut Diag<'_>| {
@@ -1263,7 +1262,7 @@ pub fn prohibit_assoc_item_constraint(
12631262
if let Ok(suggestion) = tcx.sess.source_map().span_to_snippet(removal_span) {
12641263
e.span_suggestion_verbose(
12651264
removal_span,
1266-
"consider removing this associated item binding",
1265+
format!("consider removing this associated item {}", constraint.kind.descr()),
12671266
suggestion,
12681267
Applicability::MaybeIncorrect,
12691268
);
@@ -1286,19 +1285,73 @@ pub fn prohibit_assoc_item_constraint(
12861285
// Check if the type has a generic param with the same name
12871286
// as the assoc type name in the associated item binding.
12881287
let generics = tcx.generics_of(def_id);
1289-
let matching_param =
1290-
generics.own_params.iter().find(|p| p.name.as_str() == constraint.ident.as_str());
1288+
let matching_param = generics.own_params.iter().find(|p| p.name == constraint.ident.name);
12911289

12921290
// Now emit the appropriate suggestion
12931291
if let Some(matching_param) = matching_param {
1294-
match (&matching_param.kind, term) {
1295-
(GenericParamDefKind::Type { .. }, hir::Term::Ty(ty)) => {
1296-
suggest_direct_use(&mut err, ty.span);
1297-
}
1298-
(GenericParamDefKind::Const { .. }, hir::Term::Const(c)) => {
1292+
match (constraint.kind, &matching_param.kind) {
1293+
(
1294+
hir::AssocItemConstraintKind::Equality { term: hir::Term::Ty(ty) },
1295+
GenericParamDefKind::Type { .. },
1296+
) => suggest_direct_use(&mut err, ty.span),
1297+
(
1298+
hir::AssocItemConstraintKind::Equality { term: hir::Term::Const(c) },
1299+
GenericParamDefKind::Const { .. },
1300+
) => {
12991301
let span = tcx.hir().span(c.hir_id);
13001302
suggest_direct_use(&mut err, span);
13011303
}
1304+
(hir::AssocItemConstraintKind::Bound { bounds }, _) => {
1305+
// Suggest `impl<T: Bound> Trait<T> for Foo` when finding
1306+
// `impl Trait<T: Bound> for Foo`
1307+
1308+
// Get the parent impl block based on the binding we have
1309+
// and the trait DefId
1310+
let impl_block = tcx
1311+
.hir()
1312+
.parent_iter(constraint.hir_id)
1313+
.find_map(|(_, node)| node.impl_block_of_trait(def_id));
1314+
1315+
let type_with_constraints =
1316+
tcx.sess.source_map().span_to_snippet(constraint.span);
1317+
1318+
if let Some(impl_block) = impl_block
1319+
&& let Ok(type_with_constraints) = type_with_constraints
1320+
{
1321+
// Filter out the lifetime parameters because
1322+
// they should be declared before the type parameter
1323+
let lifetimes: String = bounds
1324+
.iter()
1325+
.filter_map(|bound| {
1326+
if let hir::GenericBound::Outlives(lifetime) = bound {
1327+
Some(format!("{lifetime}, "))
1328+
} else {
1329+
None
1330+
}
1331+
})
1332+
.collect();
1333+
// Figure out a span and suggestion string based on
1334+
// whether there are any existing parameters
1335+
let param_decl = if let Some(param_span) =
1336+
impl_block.generics.span_for_param_suggestion()
1337+
{
1338+
(param_span, format!(", {lifetimes}{type_with_constraints}"))
1339+
} else {
1340+
(
1341+
impl_block.generics.span.shrink_to_lo(),
1342+
format!("<{lifetimes}{type_with_constraints}>"),
1343+
)
1344+
};
1345+
let suggestions =
1346+
vec![param_decl, (constraint.span, format!("{}", matching_param.name))];
1347+
1348+
err.multipart_suggestion_verbose(
1349+
format!("declare the type parameter right after the `impl` keyword"),
1350+
suggestions,
1351+
Applicability::MaybeIncorrect,
1352+
);
1353+
}
1354+
}
13021355
_ => suggest_removal(&mut err),
13031356
}
13041357
} else {

compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs

+16-1
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,7 @@ pub(crate) fn check_generic_arg_count(
531531

532532
let num_default_params = expected_max - expected_min;
533533

534+
let mut all_params_are_binded = false;
534535
let gen_args_info = if provided > expected_max {
535536
invalid_args.extend((expected_max..provided).map(|i| i + args_offset));
536537
let num_redundant_args = provided - expected_max;
@@ -547,6 +548,20 @@ pub(crate) fn check_generic_arg_count(
547548
} else {
548549
let num_missing_args = expected_max - provided;
549550

551+
let constraint_names: Vec<_> =
552+
gen_args.constraints.iter().map(|b| b.ident.name).collect();
553+
let param_names: Vec<_> = gen_params
554+
.own_params
555+
.iter()
556+
.filter(|param| !has_self || param.index != 0) // Assumes `Self` will always be the first parameter
557+
.map(|param| param.name)
558+
.collect();
559+
if constraint_names == param_names {
560+
// We set this to true and delay emitting `WrongNumberOfGenericArgs`
561+
// to provide a succinct error for cases like issue #113073
562+
all_params_are_binded = true;
563+
};
564+
550565
GenericArgsInfo::MissingTypesOrConsts {
551566
num_missing_args,
552567
num_default_params,
@@ -567,7 +582,7 @@ pub(crate) fn check_generic_arg_count(
567582
def_id,
568583
)
569584
.diagnostic()
570-
.emit()
585+
.emit_unless(all_params_are_binded)
571586
});
572587

573588
Err(reported)

tests/ui/associated-type-bounds/no-gat-position.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ pub trait Iter {
55

66
fn next<'a>(&'a mut self) -> Option<Self::Item<'a, As1: Copy>>;
77
//~^ ERROR associated item constraints are not allowed here
8-
//~| HELP consider removing this associated item binding
8+
//~| HELP consider removing this associated item constraint
99
}
1010

1111
impl Iter for () {

tests/ui/associated-type-bounds/no-gat-position.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ error[E0229]: associated item constraints are not allowed here
44
LL | fn next<'a>(&'a mut self) -> Option<Self::Item<'a, As1: Copy>>;
55
| ^^^^^^^^^ associated item constraint not allowed here
66
|
7-
help: consider removing this associated item binding
7+
help: consider removing this associated item constraint
88
|
99
LL | fn next<'a>(&'a mut self) -> Option<Self::Item<'a, As1: Copy>>;
1010
| ~~~~~~~~~~~

tests/ui/async-await/return-type-notation/rtn-in-impl-signature.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ error[E0229]: associated item constraints are not allowed here
1313
LL | impl Super1<'_, bar(): Send> for () {}
1414
| ^^^^^^^^^^^ associated item constraint not allowed here
1515
|
16-
help: consider removing this associated item binding
16+
help: consider removing this associated item constraint
1717
|
1818
LL | impl Super1<'_, bar(): Send> for () {}
1919
| ~~~~~~~~~~~~~

0 commit comments

Comments
 (0)