Skip to content

Check built-in operator obligation before the method's WF obligations so as to not incompletely guide inference #137811

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
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
4 changes: 3 additions & 1 deletion compiler/rustc_error_codes/src/error_codes/E0284.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
#### Note: this error code is no longer emitted by the compiler.

This error occurs when the compiler is unable to unambiguously infer the
return type of a function or method which is generic on return type, such
as the `collect` method for `Iterator`s.

For example:

```compile_fail,E0284
```compile_fail
fn main() {
let n: u32 = 1;
let mut d: u64 = 2;
Expand Down
26 changes: 14 additions & 12 deletions compiler/rustc_hir_typeck/src/method/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {

let obligation = traits::Obligation::new(
self.tcx,
cause,
cause.clone(),
self.param_env,
ty::TraitRef::new_from_args(self.tcx, trait_def_id, args),
);
Expand All @@ -385,6 +385,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {

debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
let mut obligations = PredicateObligations::new();
// Register the operator's obligation first to constrain the "rhs" argument (or inputs
// for a fn-like operator). This would happen coincidentally as part of normalizing the
// signature below if the output type is constrained but a param-env predicate, but for
// `AsyncFn*`, the output type doesn't actually show up in the signature, so we end up
// trying to prove other WF predicates first which incompletely constrains the type.
obligations.push(obligation);

// Instantiate late-bound regions and instantiate the trait
// parameters into the method type to get the actual method type.
Expand All @@ -393,11 +399,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// function signature so that normalization does not need to deal
// with bound regions.
let fn_sig = tcx.fn_sig(def_id).instantiate(self.tcx, args);
let fn_sig =
self.instantiate_binder_with_fresh_vars(obligation.cause.span, infer::FnCall, fn_sig);
let fn_sig = self.instantiate_binder_with_fresh_vars(cause.span, infer::FnCall, fn_sig);

let InferOk { value: fn_sig, obligations: o } =
self.at(&obligation.cause, self.param_env).normalize(fn_sig);
self.at(&cause, self.param_env).normalize(fn_sig);
obligations.extend(o);

// Register obligations for the parameters. This will include the
Expand All @@ -411,26 +416,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, args);

let InferOk { value: bounds, obligations: o } =
self.at(&obligation.cause, self.param_env).normalize(bounds);
self.at(&cause, self.param_env).normalize(bounds);
obligations.extend(o);
assert!(!bounds.has_escaping_bound_vars());

let predicates_cause = obligation.cause.clone();
obligations.extend(traits::predicates_for_generics(
move |_, _| predicates_cause.clone(),
|_, _| cause.clone(),
self.param_env,
bounds,
));

// Also add an obligation for the method type being well-formed.
let method_ty = Ty::new_fn_ptr(tcx, ty::Binder::dummy(fn_sig));
debug!(
"lookup_method_in_trait: matched method method_ty={:?} obligation={:?}",
method_ty, obligation
);
debug!("lookup_method_in_trait: matched method method_ty={:?}", method_ty);

obligations.push(traits::Obligation::new(
tcx,
obligation.cause,
cause.clone(),
self.param_env,
ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
method_ty.into(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ use tracing::{debug, instrument, warn};
use super::nice_region_error::placeholder_error::Highlighted;
use crate::error_reporting::TypeErrCtxt;
use crate::errors::{
AmbiguousImpl, AmbiguousReturn, AnnotationRequired, InferenceBadError,
SourceKindMultiSuggestion, SourceKindSubdiag,
AmbiguousImpl, AnnotationRequired, InferenceBadError, SourceKindMultiSuggestion,
SourceKindSubdiag,
};
use crate::infer::InferCtxt;

Expand All @@ -39,19 +39,13 @@ pub enum TypeAnnotationNeeded {
/// let _ = Default::default();
/// ```
E0283,
/// ```compile_fail,E0284
/// let mut d: u64 = 2;
/// d = d % 1u32.into();
/// ```
E0284,
}

impl From<TypeAnnotationNeeded> for ErrCode {
fn from(val: TypeAnnotationNeeded) -> Self {
match val {
TypeAnnotationNeeded::E0282 => E0282,
TypeAnnotationNeeded::E0283 => E0283,
TypeAnnotationNeeded::E0284 => E0284,
}
}
}
Expand Down Expand Up @@ -453,17 +447,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
was_written: false,
path: Default::default(),
}),
TypeAnnotationNeeded::E0284 => self.dcx().create_err(AmbiguousReturn {
span,
source_kind,
source_name,
failure_span,
infer_subdiags,
multi_suggestions,
bad_label,
was_written: false,
path: Default::default(),
}),
}
}

Expand Down Expand Up @@ -660,17 +643,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
was_written: path.is_some(),
path: path.unwrap_or_default(),
}),
TypeAnnotationNeeded::E0284 => self.dcx().create_err(AmbiguousReturn {
span,
source_kind,
source_name: &name,
failure_span,
infer_subdiags,
multi_suggestions,
bad_label: None,
was_written: path.is_some(),
path: path.unwrap_or_default(),
}),
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use std::ops::ControlFlow;

use rustc_errors::{
Applicability, Diag, E0283, E0284, E0790, MultiSpan, StashKey, struct_span_code_err,
};
use rustc_errors::{Applicability, Diag, E0283, E0790, MultiSpan, StashKey, struct_span_code_err};
use rustc_hir as hir;
use rustc_hir::LangItem;
use rustc_hir::def::{DefKind, Res};
Expand Down Expand Up @@ -534,7 +532,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
obligation.cause.body_id,
span,
arg,
TypeAnnotationNeeded::E0284,
TypeAnnotationNeeded::E0283,
true,
)
.with_note(format!("cannot satisfy `{predicate}`"))
Expand All @@ -543,7 +541,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
struct_span_code_err!(
self.dcx(),
span,
E0284,
E0283,
"type annotations needed: cannot satisfy `{predicate}`",
)
.with_span_label(span, format!("cannot satisfy `{predicate}`"))
Expand All @@ -563,7 +561,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
obligation.cause.body_id,
span,
arg,
TypeAnnotationNeeded::E0284,
TypeAnnotationNeeded::E0283,
true,
);
err
Expand All @@ -573,7 +571,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
struct_span_code_err!(
self.dcx(),
span,
E0284,
E0283,
"type annotations needed: cannot satisfy `{predicate}`",
)
.with_span_label(span, format!("cannot satisfy `{predicate}`"))
Expand All @@ -585,7 +583,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
obligation.cause.body_id,
span,
ct.into(),
TypeAnnotationNeeded::E0284,
TypeAnnotationNeeded::E0283,
true,
),
ty::PredicateKind::NormalizesTo(ty::NormalizesTo { alias, term })
Expand All @@ -598,7 +596,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
struct_span_code_err!(
self.dcx(),
span,
E0284,
E0283,
"type annotations needed: cannot normalize `{alias}`",
)
.with_span_label(span, format!("cannot normalize `{alias}`"))
Expand All @@ -612,7 +610,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
struct_span_code_err!(
self.dcx(),
span,
E0284,
E0283,
"type annotations needed: cannot satisfy `{predicate}`",
)
.with_span_label(span, format!("cannot satisfy `{predicate}`"))
Expand Down
21 changes: 0 additions & 21 deletions compiler/rustc_trait_selection/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,27 +220,6 @@ pub struct AmbiguousImpl<'a> {
pub path: PathBuf,
}

// Copy of `AnnotationRequired` for E0284
#[derive(Diagnostic)]
#[diag(trait_selection_type_annotations_needed, code = E0284)]
pub struct AmbiguousReturn<'a> {
#[primary_span]
pub span: Span,
pub source_kind: &'static str,
pub source_name: &'a str,
#[label]
pub failure_span: Option<Span>,
#[subdiagnostic]
pub bad_label: Option<InferenceBadError<'a>>,
#[subdiagnostic]
pub infer_subdiags: Vec<SourceKindSubdiag<'a>>,
#[subdiagnostic]
pub multi_suggestions: Vec<SourceKindMultiSuggestion<'a>>,
#[note(trait_selection_full_type_written)]
pub was_written: bool,
pub path: PathBuf,
}

// Used when a better one isn't available
#[derive(Subdiagnostic)]
#[label(trait_selection_label_bad)]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0284]: type annotations needed: cannot satisfy `<Self as Iterator>::Item == i32`
error[E0283]: type annotations needed: cannot satisfy `<Self as Iterator>::Item == i32`
--> $DIR/associated-types-overridden-binding.rs:4:12
|
LL | trait Bar: Foo<Item = u32> {}
Expand All @@ -10,7 +10,7 @@ note: required by a bound in `Foo`
LL | trait Foo: Iterator<Item = i32> {}
| ^^^^^^^^^^ required by this bound in `Foo`

error[E0284]: type annotations needed: cannot satisfy `<Self as Iterator>::Item == i32`
error[E0283]: type annotations needed: cannot satisfy `<Self as Iterator>::Item == i32`
--> $DIR/associated-types-overridden-binding.rs:7:21
|
LL | trait U32Iterator = I32Iterator<Item = u32>;
Expand All @@ -35,4 +35,4 @@ LL | let _: &dyn I32Iterator<Item = u32>;

error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0284`.
For more information about this error, try `rustc --explain E0283`.
23 changes: 23 additions & 0 deletions tests/ui/async-await/async-fn/incomplete-constrain-builtin.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//@ check-pass

// Ensure that a param-env predicate like `(T,): Sized` doesn't get in the way of us
// confirming the built-in call operator for `AsyncFnOnce`. This happens because we
// end up with a signature like:
//
// `<F as AsyncFnOnce<(?0,)>>::async_call_once(self) -> <F as AsyncFnOnce<(?0,)>>::CallOnceFuture`
//
// (where we use fresh infer vars for each arg since we haven't actually typeck'd the args yet).
// But normalizing that signature keeps the associated type rigid, so we don't end up
// constraining `?0` like we would if we were normalizing the analogous `FnOnce` call...
// Then we were checking that the method signature was WF, which would incompletely constrain
// `(?0,) == (T,)` via the param-env, leading to us later failing on `F: AsyncFnOnce<(T,)>`.

fn run<F, T>(f: F)
where
F: AsyncFnOnce(i32),
(T,): Sized,
{
f(1i32);
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
error[E0284]: type annotations needed: cannot normalize `<dyn Object<U, Output = T> as Object<U>>::Output`
error[E0283]: type annotations needed: cannot normalize `<dyn Object<U, Output = T> as Object<U>>::Output`
--> $DIR/indirect-impl-for-trait-obj-coherence.rs:25:41
|
LL | foo::<dyn Object<U, Output = T>, U>(x)
| ^ cannot normalize `<dyn Object<U, Output = T> as Object<U>>::Output`

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0284`.
For more information about this error, try `rustc --explain E0283`.
4 changes: 2 additions & 2 deletions tests/ui/coherence/occurs-check/associated-type.next.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ LL | | for<'a> *const T: ToUnit<'a>,
|
= note: this behavior recently changed as a result of a bug fix; see rust-lang/rust#56105 for details

error[E0284]: type annotations needed: cannot normalize `<for<'a> fn(&'a (), ()) as Overlap<for<'a> fn(&'a (), ())>>::Assoc`
error[E0283]: type annotations needed: cannot normalize `<for<'a> fn(&'a (), ()) as Overlap<for<'a> fn(&'a (), ())>>::Assoc`
--> $DIR/associated-type.rs:45:59
|
LL | foo::<for<'a> fn(&'a (), ()), for<'a> fn(&'a (), ())>(3usize);
| ^^^^^^ cannot normalize `<for<'a> fn(&'a (), ()) as Overlap<for<'a> fn(&'a (), ())>>::Assoc`

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0119, E0284.
Some errors have detailed explanations: E0119, E0283.
For more information about an error, try `rustc --explain E0119`.
6 changes: 3 additions & 3 deletions tests/ui/const-generics/defaults/doesnt_infer.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0284]: type annotations needed for `Foo<_>`
error[E0283]: type annotations needed for `Foo<_>`
--> $DIR/doesnt_infer.rs:13:9
|
LL | let foo = Foo::foo();
Expand All @@ -14,7 +14,7 @@ help: consider giving `foo` an explicit type, where the value of const parameter
LL | let foo: Foo<N> = Foo::foo();
| ++++++++

error[E0284]: type annotations needed for `Foo<_>`
error[E0283]: type annotations needed for `Foo<_>`
--> $DIR/doesnt_infer.rs:13:9
|
LL | let foo = Foo::foo();
Expand All @@ -34,4 +34,4 @@ LL | let foo: Foo<N> = Foo::foo();

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0284`.
For more information about this error, try `rustc --explain E0283`.
4 changes: 2 additions & 2 deletions tests/ui/const-generics/defaults/rp_impl_trait_fail.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ LL | 1_u64
= help: the trait `Traitor<1, 1>` is not implemented for `u64`
but trait `Traitor<1, 2>` is implemented for it

error[E0284]: type annotations needed
error[E0283]: type annotations needed
--> $DIR/rp_impl_trait_fail.rs:28:5
|
LL | uwu();
Expand All @@ -51,5 +51,5 @@ LL | uwu::<N>();

error: aborting due to 4 previous errors

Some errors have detailed explanations: E0277, E0284.
Some errors have detailed explanations: E0277, E0283.
For more information about an error, try `rustc --explain E0277`.
6 changes: 3 additions & 3 deletions tests/ui/const-generics/generic_arg_infer/issue-91614.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0284]: type annotations needed for `Mask<_, _>`
error[E0283]: type annotations needed for `Mask<_, _>`
--> $DIR/issue-91614.rs:6:9
|
LL | let y = Mask::<_, _>::splat(false);
Expand All @@ -11,7 +11,7 @@ help: consider giving `y` an explicit type, where the value of const parameter `
LL | let y: Mask<_, N> = Mask::<_, _>::splat(false);
| ++++++++++++

error[E0284]: type annotations needed for `Mask<_, _>`
error[E0283]: type annotations needed for `Mask<_, _>`
--> $DIR/issue-91614.rs:6:9
|
LL | let y = Mask::<_, _>::splat(false);
Expand All @@ -26,4 +26,4 @@ LL | let y: Mask<_, N> = Mask::<_, _>::splat(false);

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0284`.
For more information about this error, try `rustc --explain E0283`.
Loading
Loading