Avoid suggesting constrain the associated type to a trait

This commit is contained in:
yukang
2025-10-05 12:03:17 +08:00
parent 27b076af7e
commit 76bd555913
3 changed files with 58 additions and 16 deletions
+21 -16
View File
@@ -1572,26 +1572,31 @@ fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) ->
[ast::PathSegment { args: None, .. }],
[ast::GenericBound::Trait(poly_trait_ref)],
) = (&type_param_path.segments[..], &bounds[..])
&& let [ast::PathSegment { ident, args: None, id }] =
&poly_trait_ref.trait_ref.path.segments[..]
&& poly_trait_ref.modifiers == ast::TraitBoundModifiers::NONE
{
if let [ast::PathSegment { ident, args: None, .. }] =
&poly_trait_ref.trait_ref.path.segments[..]
{
if ident.span == span {
let Some(new_where_bound_predicate) =
mk_where_bound_predicate(path, poly_trait_ref, ty)
else {
return false;
};
err.span_suggestion_verbose(
*where_span,
format!("constrain the associated type to `{ident}`"),
where_bound_predicate_to_string(&new_where_bound_predicate),
Applicability::MaybeIncorrect,
);
if ident.span == span {
let Some(partial_res) = self.r.partial_res_map.get(&id) else {
return false;
};
if !matches!(partial_res.full_res(), Some(hir::def::Res::Def(..))) {
return false;
}
return true;
let Some(new_where_bound_predicate) =
mk_where_bound_predicate(path, poly_trait_ref, ty)
else {
return false;
};
err.span_suggestion_verbose(
*where_span,
format!("constrain the associated type to `{ident}`"),
where_bound_predicate_to_string(&new_where_bound_predicate),
Applicability::MaybeIncorrect,
);
}
return true;
}
}
false
@@ -0,0 +1,16 @@
use std::str::FromStr;
fn foo<T: FromStr>() -> T
where
<T as FromStr>::Err: Debug, //~ ERROR expected trait
{
"".parse().unwrap()
}
fn bar<T: FromStr>() -> T
where
<T as FromStr>::Err: some_unknown_name, //~ ERROR cannot find trait `some_unknown_name` in this scope
{
"".parse().unwrap()
}
fn main() {}
@@ -0,0 +1,21 @@
error[E0404]: expected trait, found derive macro `Debug`
--> $DIR/assoc-type-maybe-trait-147356.rs:4:26
|
LL | <T as FromStr>::Err: Debug,
| ^^^^^ not a trait
|
help: consider importing this trait instead
|
LL + use std::fmt::Debug;
|
error[E0405]: cannot find trait `some_unknown_name` in this scope
--> $DIR/assoc-type-maybe-trait-147356.rs:11:26
|
LL | <T as FromStr>::Err: some_unknown_name,
| ^^^^^^^^^^^^^^^^^ not found in this scope
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0404, E0405.
For more information about an error, try `rustc --explain E0404`.