Skip to content

Commit 783c3fc

Browse files
committed
Auto merge of #28345 - japaric:op-assign, r=nmatsakis
Implements overload-able augmented/compound assignments, like `a += b` via the `AddAssign` trait, as specified in RFC [953] [953]: https://github.com/rust-lang/rfcs/blob/master/text/0953-op-assign.md r? @nikomatsakis
2 parents 837840c + f5569ec commit 783c3fc

16 files changed

+1008
-84
lines changed

src/libcore/ops.rs

+528
Large diffs are not rendered by default.

src/librustc/middle/expr_use_visitor.rs

+8-5
Original file line numberDiff line numberDiff line change
@@ -525,11 +525,14 @@ impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> {
525525
self.consume_expr(&**base);
526526
}
527527

528-
hir::ExprAssignOp(_, ref lhs, ref rhs) => {
529-
// This will have to change if/when we support
530-
// overloaded operators for `+=` and so forth.
531-
self.mutate_expr(expr, &**lhs, WriteAndRead);
532-
self.consume_expr(&**rhs);
528+
hir::ExprAssignOp(op, ref lhs, ref rhs) => {
529+
// NB All our assignment operations take the RHS by value
530+
assert!(::rustc_front::util::is_by_value_binop(op.node));
531+
532+
if !self.walk_overloaded_operator(expr, lhs, vec![rhs], PassArgs::ByValue) {
533+
self.mutate_expr(expr, &**lhs, WriteAndRead);
534+
self.consume_expr(&**rhs);
535+
}
533536
}
534537

535538
hir::ExprRepeat(ref base, ref count) => {

src/librustc/middle/lang_items.rs

+10
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,16 @@ lets_do_this! {
286286
BitOrTraitLangItem, "bitor", bitor_trait;
287287
ShlTraitLangItem, "shl", shl_trait;
288288
ShrTraitLangItem, "shr", shr_trait;
289+
AddAssignTraitLangItem, "add_assign", add_assign_trait;
290+
SubAssignTraitLangItem, "sub_assign", sub_assign_trait;
291+
MulAssignTraitLangItem, "mul_assign", mul_assign_trait;
292+
DivAssignTraitLangItem, "div_assign", div_assign_trait;
293+
RemAssignTraitLangItem, "rem_assign", rem_assign_trait;
294+
BitXorAssignTraitLangItem, "bitxor_assign", bitxor_assign_trait;
295+
BitAndAssignTraitLangItem, "bitand_assign", bitand_assign_trait;
296+
BitOrAssignTraitLangItem, "bitor_assign", bitor_assign_trait;
297+
ShlAssignTraitLangItem, "shl_assign", shl_assign_trait;
298+
ShrAssignTraitLangItem, "shr_assign", shr_assign_trait;
289299
IndexTraitLangItem, "index", index_trait;
290300
IndexMutTraitLangItem, "index_mut", index_mut_trait;
291301
RangeStructLangItem, "range", range_struct;

src/librustc_trans/trans/expr.rs

+19-3
Original file line numberDiff line numberDiff line change
@@ -1049,7 +1049,20 @@ fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
10491049
}
10501050
}
10511051
hir::ExprAssignOp(op, ref dst, ref src) => {
1052-
trans_assign_op(bcx, expr, op, &**dst, &**src)
1052+
let has_method_map = bcx.tcx()
1053+
.tables
1054+
.borrow()
1055+
.method_map
1056+
.contains_key(&MethodCall::expr(expr.id));
1057+
1058+
if has_method_map {
1059+
let dst = unpack_datum!(bcx, trans(bcx, &**dst));
1060+
let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
1061+
trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), dst,
1062+
Some((src_datum, src.id)), None, false).bcx
1063+
} else {
1064+
trans_assign_op(bcx, expr, op, &**dst, &**src)
1065+
}
10531066
}
10541067
hir::ExprInlineAsm(ref a) => {
10551068
asm::trans_inline_asm(bcx, a)
@@ -1238,8 +1251,11 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
12381251
// Trait casts used to come this way, now they should be coercions.
12391252
bcx.tcx().sess.span_bug(expr.span, "DPS expr_cast (residual trait cast?)")
12401253
}
1241-
hir::ExprAssignOp(op, ref dst, ref src) => {
1242-
trans_assign_op(bcx, expr, op, &**dst, &**src)
1254+
hir::ExprAssignOp(op, _, _) => {
1255+
bcx.tcx().sess.span_bug(
1256+
expr.span,
1257+
&format!("augmented assignment `{}=` should always be a rvalue_stmt",
1258+
rustc_front::util::binop_to_string(op.node)))
12431259
}
12441260
_ => {
12451261
bcx.tcx().sess.span_bug(

src/librustc_typeck/check/op.rs

+75-47
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,8 @@ use super::{
1717
demand,
1818
method,
1919
FnCtxt,
20-
structurally_resolved_type,
2120
};
2221
use middle::def_id::DefId;
23-
use middle::traits;
2422
use middle::ty::{Ty, HasTypeFlags, PreferMutLvalue};
2523
use syntax::ast;
2624
use syntax::parse::token;
@@ -34,34 +32,24 @@ pub fn check_binop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
3432
lhs_expr: &'tcx hir::Expr,
3533
rhs_expr: &'tcx hir::Expr)
3634
{
37-
let tcx = fcx.ccx.tcx;
38-
3935
check_expr_with_lvalue_pref(fcx, lhs_expr, PreferMutLvalue);
40-
check_expr(fcx, rhs_expr);
4136

42-
let lhs_ty = structurally_resolved_type(fcx, lhs_expr.span, fcx.expr_ty(lhs_expr));
43-
let rhs_ty = structurally_resolved_type(fcx, rhs_expr.span, fcx.expr_ty(rhs_expr));
37+
let lhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
38+
let (rhs_ty, return_ty) =
39+
check_overloaded_binop(fcx, expr, lhs_expr, lhs_ty, rhs_expr, op, IsAssign::Yes);
40+
let rhs_ty = fcx.resolve_type_vars_if_possible(rhs_ty);
4441

45-
if is_builtin_binop(lhs_ty, rhs_ty, op) {
42+
if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() && is_builtin_binop(lhs_ty, rhs_ty, op) {
4643
enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
4744
fcx.write_nil(expr.id);
4845
} else {
49-
// error types are considered "builtin"
50-
assert!(!lhs_ty.references_error() || !rhs_ty.references_error());
51-
span_err!(tcx.sess, lhs_expr.span, E0368,
52-
"binary assignment operation `{}=` cannot be applied to types `{}` and `{}`",
53-
hir_util::binop_to_string(op.node),
54-
lhs_ty,
55-
rhs_ty);
56-
fcx.write_error(expr.id);
46+
fcx.write_ty(expr.id, return_ty);
5747
}
5848

5949
let tcx = fcx.tcx();
6050
if !tcx.expr_is_lval(lhs_expr) {
6151
span_err!(tcx.sess, lhs_expr.span, E0067, "invalid left-hand side expression");
6252
}
63-
64-
fcx.require_expr_have_sized_type(lhs_expr, traits::AssignmentLhsSized);
6553
}
6654

6755
/// Check a potentially overloaded binary operator.
@@ -95,7 +83,7 @@ pub fn check_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
9583
// overloaded. This is the way to be most flexible w/r/t
9684
// types that get inferred.
9785
let (rhs_ty, return_ty) =
98-
check_overloaded_binop(fcx, expr, lhs_expr, lhs_ty, rhs_expr, op);
86+
check_overloaded_binop(fcx, expr, lhs_expr, lhs_ty, rhs_expr, op, IsAssign::No);
9987

10088
// Supply type inference hints if relevant. Probably these
10189
// hints should be enforced during select as part of the
@@ -167,14 +155,16 @@ fn check_overloaded_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
167155
lhs_expr: &'tcx hir::Expr,
168156
lhs_ty: Ty<'tcx>,
169157
rhs_expr: &'tcx hir::Expr,
170-
op: hir::BinOp)
158+
op: hir::BinOp,
159+
is_assign: IsAssign)
171160
-> (Ty<'tcx>, Ty<'tcx>)
172161
{
173-
debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?})",
162+
debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?}, is_assign={:?})",
174163
expr.id,
175-
lhs_ty);
164+
lhs_ty,
165+
is_assign);
176166

177-
let (name, trait_def_id) = name_and_trait_def_id(fcx, op);
167+
let (name, trait_def_id) = name_and_trait_def_id(fcx, op, is_assign);
178168

179169
// NB: As we have not yet type-checked the RHS, we don't have the
180170
// type at hand. Make a variable to represent it. The whole reason
@@ -191,10 +181,17 @@ fn check_overloaded_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
191181
Err(()) => {
192182
// error types are considered "builtin"
193183
if !lhs_ty.references_error() {
194-
span_err!(fcx.tcx().sess, lhs_expr.span, E0369,
195-
"binary operation `{}` cannot be applied to type `{}`",
196-
hir_util::binop_to_string(op.node),
197-
lhs_ty);
184+
if let IsAssign::Yes = is_assign {
185+
span_err!(fcx.tcx().sess, lhs_expr.span, E0368,
186+
"binary assignment operation `{}=` cannot be applied to type `{}`",
187+
hir_util::binop_to_string(op.node),
188+
lhs_ty);
189+
} else {
190+
span_err!(fcx.tcx().sess, lhs_expr.span, E0369,
191+
"binary operation `{}` cannot be applied to type `{}`",
192+
hir_util::binop_to_string(op.node),
193+
lhs_ty);
194+
}
198195
}
199196
fcx.tcx().types.err
200197
}
@@ -231,27 +228,51 @@ pub fn check_user_unop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
231228
}
232229
}
233230

234-
fn name_and_trait_def_id(fcx: &FnCtxt, op: hir::BinOp) -> (&'static str, Option<DefId>) {
231+
fn name_and_trait_def_id(fcx: &FnCtxt,
232+
op: hir::BinOp,
233+
is_assign: IsAssign)
234+
-> (&'static str, Option<DefId>) {
235235
let lang = &fcx.tcx().lang_items;
236-
match op.node {
237-
hir::BiAdd => ("add", lang.add_trait()),
238-
hir::BiSub => ("sub", lang.sub_trait()),
239-
hir::BiMul => ("mul", lang.mul_trait()),
240-
hir::BiDiv => ("div", lang.div_trait()),
241-
hir::BiRem => ("rem", lang.rem_trait()),
242-
hir::BiBitXor => ("bitxor", lang.bitxor_trait()),
243-
hir::BiBitAnd => ("bitand", lang.bitand_trait()),
244-
hir::BiBitOr => ("bitor", lang.bitor_trait()),
245-
hir::BiShl => ("shl", lang.shl_trait()),
246-
hir::BiShr => ("shr", lang.shr_trait()),
247-
hir::BiLt => ("lt", lang.ord_trait()),
248-
hir::BiLe => ("le", lang.ord_trait()),
249-
hir::BiGe => ("ge", lang.ord_trait()),
250-
hir::BiGt => ("gt", lang.ord_trait()),
251-
hir::BiEq => ("eq", lang.eq_trait()),
252-
hir::BiNe => ("ne", lang.eq_trait()),
253-
hir::BiAnd | hir::BiOr => {
254-
fcx.tcx().sess.span_bug(op.span, "&& and || are not overloadable")
236+
237+
if let IsAssign::Yes = is_assign {
238+
match op.node {
239+
hir::BiAdd => ("add_assign", lang.add_assign_trait()),
240+
hir::BiSub => ("sub_assign", lang.sub_assign_trait()),
241+
hir::BiMul => ("mul_assign", lang.mul_assign_trait()),
242+
hir::BiDiv => ("div_assign", lang.div_assign_trait()),
243+
hir::BiRem => ("rem_assign", lang.rem_assign_trait()),
244+
hir::BiBitXor => ("bitxor_assign", lang.bitxor_assign_trait()),
245+
hir::BiBitAnd => ("bitand_assign", lang.bitand_assign_trait()),
246+
hir::BiBitOr => ("bitor_assign", lang.bitor_assign_trait()),
247+
hir::BiShl => ("shl_assign", lang.shl_assign_trait()),
248+
hir::BiShr => ("shr_assign", lang.shr_assign_trait()),
249+
hir::BiLt | hir::BiLe | hir::BiGe | hir::BiGt | hir::BiEq | hir::BiNe | hir::BiAnd |
250+
hir::BiOr => {
251+
fcx.tcx().sess.span_bug(op.span, &format!("impossible assignment operation: {}=",
252+
hir_util::binop_to_string(op.node)))
253+
}
254+
}
255+
} else {
256+
match op.node {
257+
hir::BiAdd => ("add", lang.add_trait()),
258+
hir::BiSub => ("sub", lang.sub_trait()),
259+
hir::BiMul => ("mul", lang.mul_trait()),
260+
hir::BiDiv => ("div", lang.div_trait()),
261+
hir::BiRem => ("rem", lang.rem_trait()),
262+
hir::BiBitXor => ("bitxor", lang.bitxor_trait()),
263+
hir::BiBitAnd => ("bitand", lang.bitand_trait()),
264+
hir::BiBitOr => ("bitor", lang.bitor_trait()),
265+
hir::BiShl => ("shl", lang.shl_trait()),
266+
hir::BiShr => ("shr", lang.shr_trait()),
267+
hir::BiLt => ("lt", lang.ord_trait()),
268+
hir::BiLe => ("le", lang.ord_trait()),
269+
hir::BiGe => ("ge", lang.ord_trait()),
270+
hir::BiGt => ("gt", lang.ord_trait()),
271+
hir::BiEq => ("eq", lang.eq_trait()),
272+
hir::BiNe => ("ne", lang.eq_trait()),
273+
hir::BiAnd | hir::BiOr => {
274+
fcx.tcx().sess.span_bug(op.span, "&& and || are not overloadable")
275+
}
255276
}
256277
}
257278
}
@@ -362,6 +383,13 @@ impl BinOpCategory {
362383
}
363384
}
364385

386+
/// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
387+
#[derive(Clone, Copy, Debug)]
388+
enum IsAssign {
389+
No,
390+
Yes,
391+
}
392+
365393
/// Returns true if this is a built-in arithmetic operation (e.g. u32
366394
/// + u32, i16x4 == i16x4) and false if these types would have to be
367395
/// overloaded to be legal. There are two reasons that we distinguish

src/librustc_typeck/check/regionck.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -695,7 +695,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &hir::Expr) {
695695
hir::ExprAssignOp(_, ref lhs, ref rhs) => {
696696
if has_method_map {
697697
constrain_call(rcx, expr, Some(&**lhs),
698-
Some(&**rhs).into_iter(), true);
698+
Some(&**rhs).into_iter(), false);
699699
}
700700

701701
visit::walk_expr(rcx, expr);

src/librustc_typeck/check/writeback.rs

+46-17
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use astconv::AstConv;
1717
use check::FnCtxt;
1818
use middle::def_id::DefId;
1919
use middle::pat_util;
20-
use middle::ty::{self, Ty, MethodCall, MethodCallee};
20+
use middle::ty::{self, Ty, MethodCall, MethodCallee, HasTypeFlags};
2121
use middle::ty::adjustment;
2222
use middle::ty::fold::{TypeFolder,TypeFoldable};
2323
use middle::infer;
@@ -91,24 +91,53 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
9191
// we observe that something like `a+b` is (known to be)
9292
// operating on scalars, we clear the overload.
9393
fn fix_scalar_binary_expr(&mut self, e: &hir::Expr) {
94-
if let hir::ExprBinary(ref op, ref lhs, ref rhs) = e.node {
95-
let lhs_ty = self.fcx.node_ty(lhs.id);
96-
let lhs_ty = self.fcx.infcx().resolve_type_vars_if_possible(&lhs_ty);
97-
98-
let rhs_ty = self.fcx.node_ty(rhs.id);
99-
let rhs_ty = self.fcx.infcx().resolve_type_vars_if_possible(&rhs_ty);
100-
101-
if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
102-
self.fcx.inh.tables.borrow_mut().method_map.remove(&MethodCall::expr(e.id));
103-
104-
// weird but true: the by-ref binops put an
105-
// adjustment on the lhs but not the rhs; the
106-
// adjustment for rhs is kind of baked into the
107-
// system.
108-
if !hir_util::is_by_value_binop(op.node) {
109-
self.fcx.inh.tables.borrow_mut().adjustments.remove(&lhs.id);
94+
match e.node {
95+
hir::ExprBinary(ref op, ref lhs, ref rhs) |
96+
hir::ExprAssignOp(ref op, ref lhs, ref rhs) => {
97+
let lhs_ty = self.fcx.node_ty(lhs.id);
98+
let lhs_ty = self.fcx.infcx().resolve_type_vars_if_possible(&lhs_ty);
99+
100+
let rhs_ty = self.fcx.node_ty(rhs.id);
101+
let rhs_ty = self.fcx.infcx().resolve_type_vars_if_possible(&rhs_ty);
102+
103+
if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
104+
self.fcx.inh.tables.borrow_mut().method_map.remove(&MethodCall::expr(e.id));
105+
106+
// weird but true: the by-ref binops put an
107+
// adjustment on the lhs but not the rhs; the
108+
// adjustment for rhs is kind of baked into the
109+
// system.
110+
match e.node {
111+
hir::ExprBinary(..) => {
112+
if !hir_util::is_by_value_binop(op.node) {
113+
self.fcx.inh.tables.borrow_mut().adjustments.remove(&lhs.id);
114+
}
115+
},
116+
hir::ExprAssignOp(..) => {
117+
self.fcx.inh.tables.borrow_mut().adjustments.remove(&lhs.id);
118+
},
119+
_ => {},
120+
}
121+
} else {
122+
let tcx = self.tcx();
123+
124+
if let hir::ExprAssignOp(..) = e.node {
125+
if
126+
!tcx.sess.features.borrow().augmented_assignments &&
127+
!self.fcx.expr_ty(e).references_error()
128+
{
129+
tcx.sess.span_err(
130+
e.span,
131+
"overloaded augmented assignments are not stable");
132+
fileline_help!(
133+
tcx.sess, e.span,
134+
"add #![feature(augmented_assignments)] to the crate features \
135+
to enable");
136+
}
137+
}
110138
}
111139
}
140+
_ => {},
112141
}
113142
}
114143
}

0 commit comments

Comments
 (0)