Skip to content

Commit 2898890

Browse files
committed
fix wrong suggestion for adding where clauses
1 parent e838059 commit 2898890

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

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

+16-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ use rustc_hir::lang_items::LangItem;
2121
use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
2222
use rustc_middle::hir::map;
2323
use rustc_middle::ty::{
24-
self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
24+
self,
25+
subst::{GenericArgKind, SubstsRef},
26+
suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
2527
GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, ToPredicate, Ty, TyCtxt,
2628
TypeFoldable,
2729
};
@@ -458,6 +460,16 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
458460
_ => (false, None),
459461
};
460462

463+
let generic_args_have_impl_trait = |args: SubstsRef<'tcx>| -> bool {
464+
args.iter().any(|arg| match arg.unpack() {
465+
GenericArgKind::Type(ty) => match ty.kind() {
466+
ty::Param(param) => param.name.as_str().starts_with("impl"),
467+
_ => false,
468+
},
469+
_ => false,
470+
})
471+
};
472+
461473
// FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
462474
// don't suggest `T: Sized + ?Sized`.
463475
let mut hir_id = body_id;
@@ -588,7 +600,9 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
588600
| hir::ItemKind::TraitAlias(generics, _)
589601
| hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
590602
..
591-
}) if !param_ty => {
603+
}) if !param_ty
604+
&& !generic_args_have_impl_trait(trait_pred.skip_binder().trait_ref.substs) =>
605+
{
592606
// Missing generic type parameter bound.
593607
let param_name = self_ty.to_string();
594608
let constraint = trait_pred.print_modifiers_and_trait_path().to_string();

src/test/ui/traits/issue-97576.rs

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
struct Foo {
2+
bar: String,
3+
}
4+
5+
impl Foo {
6+
pub fn new(bar: impl ToString) -> Self {
7+
Self {
8+
bar: bar.into(), //~ ERROR the trait bound `String: From<impl ToString>` is not satisfied
9+
}
10+
}
11+
}
12+
13+
fn main() {}

src/test/ui/traits/issue-97576.stderr

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error[E0277]: the trait bound `String: From<impl ToString>` is not satisfied
2+
--> $DIR/issue-97576.rs:8:22
3+
|
4+
LL | bar: bar.into(),
5+
| ^^^^ the trait `From<impl ToString>` is not implemented for `String`
6+
|
7+
= note: required because of the requirements on the impl of `Into<String>` for `impl ToString`
8+
9+
error: aborting due to previous error
10+
11+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)