Rollup merge of #114834 - compiler-errors:try_coerce-side-effects, r=lcnr

Avoid side-effects from `try_coerce` when suggesting borrowing LHS of cast

The name `try_coerce` is a bit misleading -- it has side-effects, so when it's used in diagnostics code, it sometimes causes spurious obligations to be registered which cause other errors to occur that really make no sense in context.

Addendum: let's just rename `try_coerce` to `coerce` -- the `try_` part doesn't really add much, imo.
This commit is contained in:
Matthias Krüger 2023-08-20 08:34:03 +02:00 committed by GitHub
commit 33771dfaf0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 23 additions and 84 deletions

View File

@ -389,34 +389,26 @@ impl<'a, 'tcx> CastCheck<'tcx> {
if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() { if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
if let ty::RawPtr(TypeAndMut { ty: expr_ty, .. }) = *self.expr_ty.kind() if let ty::RawPtr(TypeAndMut { ty: expr_ty, .. }) = *self.expr_ty.kind()
&& fcx && fcx
.try_coerce( .can_coerce(
self.expr,
Ty::new_ref(fcx.tcx, Ty::new_ref(fcx.tcx,
fcx.tcx.lifetimes.re_erased, fcx.tcx.lifetimes.re_erased,
TypeAndMut { ty: expr_ty, mutbl }, TypeAndMut { ty: expr_ty, mutbl },
), ),
self.cast_ty, self.cast_ty,
AllowTwoPhase::No,
None,
) )
.is_ok()
{ {
sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty)); sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
} else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind() } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
&& expr_mutbl == Mutability::Not && expr_mutbl == Mutability::Not
&& mutbl == Mutability::Mut && mutbl == Mutability::Mut
&& fcx && fcx
.try_coerce( .can_coerce(
self.expr,
Ty::new_ref(fcx.tcx, Ty::new_ref(fcx.tcx,
expr_reg, expr_reg,
TypeAndMut { ty: expr_ty, mutbl: Mutability::Mut }, TypeAndMut { ty: expr_ty, mutbl: Mutability::Mut },
), ),
self.cast_ty, self.cast_ty,
AllowTwoPhase::No,
None,
) )
.is_ok()
{ {
sugg_mutref = true; sugg_mutref = true;
} }
@ -424,30 +416,22 @@ impl<'a, 'tcx> CastCheck<'tcx> {
if !sugg_mutref if !sugg_mutref
&& sugg == None && sugg == None
&& fcx && fcx
.try_coerce( .can_coerce(
self.expr,
Ty::new_ref(fcx.tcx,reg, TypeAndMut { ty: self.expr_ty, mutbl }), Ty::new_ref(fcx.tcx,reg, TypeAndMut { ty: self.expr_ty, mutbl }),
self.cast_ty, self.cast_ty,
AllowTwoPhase::No,
None,
) )
.is_ok()
{ {
sugg = Some((format!("&{}", mutbl.prefix_str()), false)); sugg = Some((format!("&{}", mutbl.prefix_str()), false));
} }
} else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind() } else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind()
&& fcx && fcx
.try_coerce( .can_coerce(
self.expr,
Ty::new_ref(fcx.tcx, Ty::new_ref(fcx.tcx,
fcx.tcx.lifetimes.re_erased, fcx.tcx.lifetimes.re_erased,
TypeAndMut { ty: self.expr_ty, mutbl }, TypeAndMut { ty: self.expr_ty, mutbl },
), ),
self.cast_ty, self.cast_ty,
AllowTwoPhase::No,
None,
) )
.is_ok()
{ {
sugg = Some((format!("&{}", mutbl.prefix_str()), false)); sugg = Some((format!("&{}", mutbl.prefix_str()), false));
} }
@ -760,7 +744,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
ty::FnDef(..) => { ty::FnDef(..) => {
// Attempt a coercion to a fn pointer type. // Attempt a coercion to a fn pointer type.
let f = fcx.normalize(self.expr_span, self.expr_ty.fn_sig(fcx.tcx)); let f = fcx.normalize(self.expr_span, self.expr_ty.fn_sig(fcx.tcx));
let res = fcx.try_coerce( let res = fcx.coerce(
self.expr, self.expr,
self.expr_ty, self.expr_ty,
Ty::new_fn_ptr(fcx.tcx, f), Ty::new_fn_ptr(fcx.tcx, f),
@ -860,7 +844,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
(_, DynStar) => { (_, DynStar) => {
if fcx.tcx.features().dyn_star { if fcx.tcx.features().dyn_star {
bug!("should be handled by `try_coerce`") bug!("should be handled by `coerce`")
} else { } else {
Err(CastError::IllegalCast) Err(CastError::IllegalCast)
} }
@ -956,7 +940,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
// Coerce to a raw pointer so that we generate AddressOf in MIR. // Coerce to a raw pointer so that we generate AddressOf in MIR.
let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr); let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr);
fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None) fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
.unwrap_or_else(|_| { .unwrap_or_else(|_| {
bug!( bug!(
"could not cast from reference to array to pointer to array ({:?} to {:?})", "could not cast from reference to array to pointer to array ({:?} to {:?})",
@ -992,7 +976,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
} }
fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> { fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) { match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(err) => Err(err), Err(err) => Err(err),
} }

View File

@ -1005,7 +1005,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// adjusted type of the expression, if successful. /// adjusted type of the expression, if successful.
/// Adjustments are only recorded if the coercion succeeded. /// Adjustments are only recorded if the coercion succeeded.
/// The expressions *must not* have any preexisting adjustments. /// The expressions *must not* have any preexisting adjustments.
pub fn try_coerce( pub fn coerce(
&self, &self,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
expr_ty: Ty<'tcx>, expr_ty: Ty<'tcx>,
@ -1036,7 +1036,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}) })
} }
/// Same as `try_coerce()`, but without side-effects. /// Same as `coerce()`, but without side-effects.
/// ///
/// Returns false if the coercion creates any obligations that result in /// Returns false if the coercion creates any obligations that result in
/// errors. /// errors.
@ -1494,7 +1494,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
// Special-case the first expression we are coercing. // Special-case the first expression we are coercing.
// To be honest, I'm not entirely sure why we do this. // To be honest, I'm not entirely sure why we do this.
// We don't allow two-phase borrows, see comment in try_find_coercion_lub for why // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
fcx.try_coerce( fcx.coerce(
expression, expression,
expression_ty, expression_ty,
self.expected_ty, self.expected_ty,

View File

@ -254,7 +254,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>) { ) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>) {
let expected = self.resolve_vars_with_obligations(expected); let expected = self.resolve_vars_with_obligations(expected);
let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase, None) { let e = match self.coerce(expr, checked_ty, expected, allow_two_phase, None) {
Ok(ty) => return (ty, None), Ok(ty) => return (ty, None),
Err(e) => e, Err(e) => e,
}; };
@ -475,7 +475,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
{ {
let Some(arg_ty) = self.node_ty_opt(arg_expr.hir_id) else { continue; }; let Some(arg_ty) = self.node_ty_opt(arg_expr.hir_id) else { continue; };
let arg_ty = arg_ty.fold_with(&mut fudger); let arg_ty = arg_ty.fold_with(&mut fudger);
let _ = self.try_coerce( let _ = self.coerce(
arg_expr, arg_expr,
arg_ty, arg_ty,
*expected_arg_ty, *expected_arg_ty,

View File

@ -260,9 +260,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// fulfillment error to be more accurate. // fulfillment error to be more accurate.
let coerced_ty = self.resolve_vars_with_obligations(coerced_ty); let coerced_ty = self.resolve_vars_with_obligations(coerced_ty);
let coerce_error = self let coerce_error =
.try_coerce(provided_arg, checked_ty, coerced_ty, AllowTwoPhase::Yes, None) self.coerce(provided_arg, checked_ty, coerced_ty, AllowTwoPhase::Yes, None).err();
.err();
if coerce_error.is_some() { if coerce_error.is_some() {
return Compatibility::Incompatible(coerce_error); return Compatibility::Incompatible(coerce_error);

View File

@ -2,22 +2,8 @@ error[E0605]: non-primitive cast: `&dyn Foo` as `&dyn Bar<_>`
--> $DIR/type-checking-test-1.rs:19:13 --> $DIR/type-checking-test-1.rs:19:13
| |
LL | let _ = x as &dyn Bar<_>; // Ambiguous LL | let _ = x as &dyn Bar<_>; // Ambiguous
| ^^^^^^^^^^^^^^^^ invalid cast | ^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
|
help: consider borrowing the value
|
LL | let _ = &x as &dyn Bar<_>; // Ambiguous
| +
error[E0277]: the trait bound `&dyn Foo: Bar<_>` is not satisfied error: aborting due to previous error
--> $DIR/type-checking-test-1.rs:19:13
|
LL | let _ = x as &dyn Bar<_>; // Ambiguous
| ^ the trait `Bar<_>` is not implemented for `&dyn Foo`
|
= note: required for the cast from `&&dyn Foo` to `&dyn Bar<_>`
error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0605`.
Some errors have detailed explanations: E0277, E0605.
For more information about an error, try `rustc --explain E0277`.

View File

@ -18,7 +18,6 @@ fn test_specific(x: &dyn Foo) {
fn test_unknown_version(x: &dyn Foo) { fn test_unknown_version(x: &dyn Foo) {
let _ = x as &dyn Bar<_>; // Ambiguous let _ = x as &dyn Bar<_>; // Ambiguous
//~^ ERROR non-primitive cast //~^ ERROR non-primitive cast
//[current]~^^ ERROR the trait bound `&dyn Foo: Bar<_>` is not satisfied
} }
fn test_infer_version(x: &dyn Foo) { fn test_infer_version(x: &dyn Foo) {

View File

@ -18,13 +18,11 @@ fn test_specific2(x: &dyn Foo<u32>) {
fn test_specific3(x: &dyn Foo<i32>) { fn test_specific3(x: &dyn Foo<i32>) {
let _ = x as &dyn Bar<u32>; // Error let _ = x as &dyn Bar<u32>; // Error
//~^ ERROR non-primitive cast //~^ ERROR non-primitive cast
//~^^ ERROR the trait bound `&dyn Foo<i32>: Bar<u32>` is not satisfied
} }
fn test_infer_arg(x: &dyn Foo<u32>) { fn test_infer_arg(x: &dyn Foo<u32>) {
let a = x as &dyn Bar<_>; // Ambiguous let a = x as &dyn Bar<_>; // Ambiguous
//~^ ERROR non-primitive cast //~^ ERROR non-primitive cast
//~^^ ERROR the trait bound `&dyn Foo<u32>: Bar<_>` is not satisfied
let _ = a.bar(); let _ = a.bar();
} }

View File

@ -2,41 +2,14 @@ error[E0605]: non-primitive cast: `&dyn Foo<i32>` as `&dyn Bar<u32>`
--> $DIR/type-checking-test-2.rs:19:13 --> $DIR/type-checking-test-2.rs:19:13
| |
LL | let _ = x as &dyn Bar<u32>; // Error LL | let _ = x as &dyn Bar<u32>; // Error
| ^^^^^^^^^^^^^^^^^^ invalid cast | ^^^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
|
help: consider borrowing the value
|
LL | let _ = &x as &dyn Bar<u32>; // Error
| +
error[E0277]: the trait bound `&dyn Foo<i32>: Bar<u32>` is not satisfied
--> $DIR/type-checking-test-2.rs:19:13
|
LL | let _ = x as &dyn Bar<u32>; // Error
| ^ the trait `Bar<u32>` is not implemented for `&dyn Foo<i32>`
|
= note: required for the cast from `&&dyn Foo<i32>` to `&dyn Bar<u32>`
error[E0605]: non-primitive cast: `&dyn Foo<u32>` as `&dyn Bar<_>` error[E0605]: non-primitive cast: `&dyn Foo<u32>` as `&dyn Bar<_>`
--> $DIR/type-checking-test-2.rs:25:13 --> $DIR/type-checking-test-2.rs:24:13
| |
LL | let a = x as &dyn Bar<_>; // Ambiguous LL | let a = x as &dyn Bar<_>; // Ambiguous
| ^^^^^^^^^^^^^^^^ invalid cast | ^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
|
help: consider borrowing the value
|
LL | let a = &x as &dyn Bar<_>; // Ambiguous
| +
error[E0277]: the trait bound `&dyn Foo<u32>: Bar<_>` is not satisfied error: aborting due to 2 previous errors
--> $DIR/type-checking-test-2.rs:25:13
|
LL | let a = x as &dyn Bar<_>; // Ambiguous
| ^ the trait `Bar<_>` is not implemented for `&dyn Foo<u32>`
|
= note: required for the cast from `&&dyn Foo<u32>` to `&dyn Bar<_>`
error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0605`.
Some errors have detailed explanations: E0277, E0605.
For more information about an error, try `rustc --explain E0277`.