From c83602a70239cf3d8c7d8e07e5041de6838e0cd9 Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Thu, 19 Jul 2018 15:10:14 +0200 Subject: [PATCH] When type-checking binops, LHS of assign-op like `+=` is invariant. Therefore we cannot coerce it to a supertype the same way that we can the LHS of `+`. Addresses issue 52126. --- src/librustc_typeck/check/op.rs | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/librustc_typeck/check/op.rs b/src/librustc_typeck/check/op.rs index 46746d4bd298..fb153464dff1 100644 --- a/src/librustc_typeck/check/op.rs +++ b/src/librustc_typeck/check/op.rs @@ -165,18 +165,25 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { op, is_assign); - let lhs_needs = match is_assign { - IsAssign::Yes => Needs::MutPlace, - IsAssign::No => Needs::None + let lhs_ty = match is_assign { + IsAssign::No => { + // Find a suitable supertype of the LHS expression's type, by coercing to + // a type variable, to pass as the `Self` to the trait, avoiding invariant + // trait matching creating lifetime constraints that are too strict. + // E.g. adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result + // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`. + let lhs_ty = self.check_expr_with_needs(lhs_expr, Needs::None); + let fresh_var = self.next_ty_var(TypeVariableOrigin::MiscVariable(lhs_expr.span)); + self.demand_coerce(lhs_expr, lhs_ty, fresh_var, AllowTwoPhase::No) + } + IsAssign::Yes => { + // rust-lang/rust#52126: We have to use strict + // equivalence on the LHS of an assign-op like `+=`; + // overwritten or mutably-borrowed places cannot be + // coerced to a supertype. + self.check_expr_with_needs(lhs_expr, Needs::MutPlace) + } }; - // Find a suitable supertype of the LHS expression's type, by coercing to - // a type variable, to pass as the `Self` to the trait, avoiding invariant - // trait matching creating lifetime constraints that are too strict. - // E.g. adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result - // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`. - let lhs_ty = self.check_expr_with_needs(lhs_expr, lhs_needs); - let fresh_var = self.next_ty_var(TypeVariableOrigin::MiscVariable(lhs_expr.span)); - let lhs_ty = self.demand_coerce(lhs_expr, lhs_ty, fresh_var, AllowTwoPhase::No); let lhs_ty = self.resolve_type_vars_with_obligations(lhs_ty); // NB: As we have not yet type-checked the RHS, we don't have the