Skip to content

Commit 33771df

Browse files
authored
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.
2 parents 484cb4e + 406b0e2 commit 33771df

File tree

8 files changed

+23
-84
lines changed

8 files changed

+23
-84
lines changed

compiler/rustc_hir_typeck/src/cast.rs

+8-24
Original file line numberDiff line numberDiff line change
@@ -389,65 +389,49 @@ impl<'a, 'tcx> CastCheck<'tcx> {
389389
if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
390390
if let ty::RawPtr(TypeAndMut { ty: expr_ty, .. }) = *self.expr_ty.kind()
391391
&& fcx
392-
.try_coerce(
393-
self.expr,
392+
.can_coerce(
394393
Ty::new_ref(fcx.tcx,
395394
fcx.tcx.lifetimes.re_erased,
396395
TypeAndMut { ty: expr_ty, mutbl },
397396
),
398397
self.cast_ty,
399-
AllowTwoPhase::No,
400-
None,
401398
)
402-
.is_ok()
403399
{
404400
sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
405401
} else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
406402
&& expr_mutbl == Mutability::Not
407403
&& mutbl == Mutability::Mut
408404
&& fcx
409-
.try_coerce(
410-
self.expr,
405+
.can_coerce(
411406
Ty::new_ref(fcx.tcx,
412407
expr_reg,
413408
TypeAndMut { ty: expr_ty, mutbl: Mutability::Mut },
414409
),
415410
self.cast_ty,
416-
AllowTwoPhase::No,
417-
None,
418411
)
419-
.is_ok()
420412
{
421413
sugg_mutref = true;
422414
}
423415

424416
if !sugg_mutref
425417
&& sugg == None
426418
&& fcx
427-
.try_coerce(
428-
self.expr,
419+
.can_coerce(
429420
Ty::new_ref(fcx.tcx,reg, TypeAndMut { ty: self.expr_ty, mutbl }),
430421
self.cast_ty,
431-
AllowTwoPhase::No,
432-
None,
433422
)
434-
.is_ok()
435423
{
436424
sugg = Some((format!("&{}", mutbl.prefix_str()), false));
437425
}
438426
} else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind()
439427
&& fcx
440-
.try_coerce(
441-
self.expr,
428+
.can_coerce(
442429
Ty::new_ref(fcx.tcx,
443430
fcx.tcx.lifetimes.re_erased,
444431
TypeAndMut { ty: self.expr_ty, mutbl },
445432
),
446433
self.cast_ty,
447-
AllowTwoPhase::No,
448-
None,
449434
)
450-
.is_ok()
451435
{
452436
sugg = Some((format!("&{}", mutbl.prefix_str()), false));
453437
}
@@ -760,7 +744,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
760744
ty::FnDef(..) => {
761745
// Attempt a coercion to a fn pointer type.
762746
let f = fcx.normalize(self.expr_span, self.expr_ty.fn_sig(fcx.tcx));
763-
let res = fcx.try_coerce(
747+
let res = fcx.coerce(
764748
self.expr,
765749
self.expr_ty,
766750
Ty::new_fn_ptr(fcx.tcx, f),
@@ -860,7 +844,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
860844

861845
(_, DynStar) => {
862846
if fcx.tcx.features().dyn_star {
863-
bug!("should be handled by `try_coerce`")
847+
bug!("should be handled by `coerce`")
864848
} else {
865849
Err(CastError::IllegalCast)
866850
}
@@ -956,7 +940,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
956940

957941
// Coerce to a raw pointer so that we generate AddressOf in MIR.
958942
let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr);
959-
fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
943+
fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
960944
.unwrap_or_else(|_| {
961945
bug!(
962946
"could not cast from reference to array to pointer to array ({:?} to {:?})",
@@ -992,7 +976,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
992976
}
993977

994978
fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
995-
match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
979+
match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
996980
Ok(_) => Ok(()),
997981
Err(err) => Err(err),
998982
}

compiler/rustc_hir_typeck/src/coercion.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1005,7 +1005,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
10051005
/// adjusted type of the expression, if successful.
10061006
/// Adjustments are only recorded if the coercion succeeded.
10071007
/// The expressions *must not* have any preexisting adjustments.
1008-
pub fn try_coerce(
1008+
pub fn coerce(
10091009
&self,
10101010
expr: &hir::Expr<'_>,
10111011
expr_ty: Ty<'tcx>,
@@ -1036,7 +1036,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
10361036
})
10371037
}
10381038

1039-
/// Same as `try_coerce()`, but without side-effects.
1039+
/// Same as `coerce()`, but without side-effects.
10401040
///
10411041
/// Returns false if the coercion creates any obligations that result in
10421042
/// errors.
@@ -1494,7 +1494,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
14941494
// Special-case the first expression we are coercing.
14951495
// To be honest, I'm not entirely sure why we do this.
14961496
// We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1497-
fcx.try_coerce(
1497+
fcx.coerce(
14981498
expression,
14991499
expression_ty,
15001500
self.expected_ty,

compiler/rustc_hir_typeck/src/demand.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
254254
) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>) {
255255
let expected = self.resolve_vars_with_obligations(expected);
256256

257-
let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase, None) {
257+
let e = match self.coerce(expr, checked_ty, expected, allow_two_phase, None) {
258258
Ok(ty) => return (ty, None),
259259
Err(e) => e,
260260
};
@@ -475,7 +475,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
475475
{
476476
let Some(arg_ty) = self.node_ty_opt(arg_expr.hir_id) else { continue; };
477477
let arg_ty = arg_ty.fold_with(&mut fudger);
478-
let _ = self.try_coerce(
478+
let _ = self.coerce(
479479
arg_expr,
480480
arg_ty,
481481
*expected_arg_ty,

compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -260,9 +260,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
260260
// fulfillment error to be more accurate.
261261
let coerced_ty = self.resolve_vars_with_obligations(coerced_ty);
262262

263-
let coerce_error = self
264-
.try_coerce(provided_arg, checked_ty, coerced_ty, AllowTwoPhase::Yes, None)
265-
.err();
263+
let coerce_error =
264+
self.coerce(provided_arg, checked_ty, coerced_ty, AllowTwoPhase::Yes, None).err();
266265

267266
if coerce_error.is_some() {
268267
return Compatibility::Incompatible(coerce_error);

tests/ui/traits/trait-upcasting/type-checking-test-1.current.stderr

+3-17
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,8 @@ error[E0605]: non-primitive cast: `&dyn Foo` as `&dyn Bar<_>`
22
--> $DIR/type-checking-test-1.rs:19:13
33
|
44
LL | let _ = x as &dyn Bar<_>; // Ambiguous
5-
| ^^^^^^^^^^^^^^^^ invalid cast
6-
|
7-
help: consider borrowing the value
8-
|
9-
LL | let _ = &x as &dyn Bar<_>; // Ambiguous
10-
| +
11-
12-
error[E0277]: the trait bound `&dyn Foo: Bar<_>` is not satisfied
13-
--> $DIR/type-checking-test-1.rs:19:13
14-
|
15-
LL | let _ = x as &dyn Bar<_>; // Ambiguous
16-
| ^ the trait `Bar<_>` is not implemented for `&dyn Foo`
17-
|
18-
= note: required for the cast from `&&dyn Foo` to `&dyn Bar<_>`
5+
| ^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
196

20-
error: aborting due to 2 previous errors
7+
error: aborting due to previous error
218

22-
Some errors have detailed explanations: E0277, E0605.
23-
For more information about an error, try `rustc --explain E0277`.
9+
For more information about this error, try `rustc --explain E0605`.

tests/ui/traits/trait-upcasting/type-checking-test-1.rs

-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ fn test_specific(x: &dyn Foo) {
1818
fn test_unknown_version(x: &dyn Foo) {
1919
let _ = x as &dyn Bar<_>; // Ambiguous
2020
//~^ ERROR non-primitive cast
21-
//[current]~^^ ERROR the trait bound `&dyn Foo: Bar<_>` is not satisfied
2221
}
2322

2423
fn test_infer_version(x: &dyn Foo) {

tests/ui/traits/trait-upcasting/type-checking-test-2.rs

-2
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,11 @@ fn test_specific2(x: &dyn Foo<u32>) {
1818
fn test_specific3(x: &dyn Foo<i32>) {
1919
let _ = x as &dyn Bar<u32>; // Error
2020
//~^ ERROR non-primitive cast
21-
//~^^ ERROR the trait bound `&dyn Foo<i32>: Bar<u32>` is not satisfied
2221
}
2322

2423
fn test_infer_arg(x: &dyn Foo<u32>) {
2524
let a = x as &dyn Bar<_>; // Ambiguous
2625
//~^ ERROR non-primitive cast
27-
//~^^ ERROR the trait bound `&dyn Foo<u32>: Bar<_>` is not satisfied
2826
let _ = a.bar();
2927
}
3028

tests/ui/traits/trait-upcasting/type-checking-test-2.stderr

+5-32
Original file line numberDiff line numberDiff line change
@@ -2,41 +2,14 @@ error[E0605]: non-primitive cast: `&dyn Foo<i32>` as `&dyn Bar<u32>`
22
--> $DIR/type-checking-test-2.rs:19:13
33
|
44
LL | let _ = x as &dyn Bar<u32>; // Error
5-
| ^^^^^^^^^^^^^^^^^^ invalid cast
6-
|
7-
help: consider borrowing the value
8-
|
9-
LL | let _ = &x as &dyn Bar<u32>; // Error
10-
| +
11-
12-
error[E0277]: the trait bound `&dyn Foo<i32>: Bar<u32>` is not satisfied
13-
--> $DIR/type-checking-test-2.rs:19:13
14-
|
15-
LL | let _ = x as &dyn Bar<u32>; // Error
16-
| ^ the trait `Bar<u32>` is not implemented for `&dyn Foo<i32>`
17-
|
18-
= note: required for the cast from `&&dyn Foo<i32>` to `&dyn Bar<u32>`
5+
| ^^^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
196

207
error[E0605]: non-primitive cast: `&dyn Foo<u32>` as `&dyn Bar<_>`
21-
--> $DIR/type-checking-test-2.rs:25:13
8+
--> $DIR/type-checking-test-2.rs:24:13
229
|
2310
LL | let a = x as &dyn Bar<_>; // Ambiguous
24-
| ^^^^^^^^^^^^^^^^ invalid cast
25-
|
26-
help: consider borrowing the value
27-
|
28-
LL | let a = &x as &dyn Bar<_>; // Ambiguous
29-
| +
30-
31-
error[E0277]: the trait bound `&dyn Foo<u32>: Bar<_>` is not satisfied
32-
--> $DIR/type-checking-test-2.rs:25:13
33-
|
34-
LL | let a = x as &dyn Bar<_>; // Ambiguous
35-
| ^ the trait `Bar<_>` is not implemented for `&dyn Foo<u32>`
36-
|
37-
= note: required for the cast from `&&dyn Foo<u32>` to `&dyn Bar<_>`
11+
| ^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
3812

39-
error: aborting due to 4 previous errors
13+
error: aborting due to 2 previous errors
4014

41-
Some errors have detailed explanations: E0277, E0605.
42-
For more information about an error, try `rustc --explain E0277`.
15+
For more information about this error, try `rustc --explain E0605`.

0 commit comments

Comments
 (0)