1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Code related to processing overloaded binary and unary operators.
14 use super::method::MethodCallee;
15 use rustc::ty::{self, Ty, TypeFoldable, PreferMutLvalue, TypeVariants};
16 use rustc::ty::TypeVariants::{TyStr, TyRef};
17 use rustc::ty::adjustment::{Adjustment, Adjust, AutoBorrow};
18 use rustc::infer::type_variable::TypeVariableOrigin;
21 use syntax::symbol::Symbol;
24 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
25 /// Check a `a <op>= b`
26 pub fn check_binop_assign(&self,
27 expr: &'gcx hir::Expr,
29 lhs_expr: &'gcx hir::Expr,
30 rhs_expr: &'gcx hir::Expr) -> Ty<'tcx>
32 let lhs_ty = self.check_expr_with_lvalue_pref(lhs_expr, PreferMutLvalue);
34 let lhs_ty = self.resolve_type_vars_with_obligations(lhs_ty);
35 let (rhs_ty, return_ty) =
36 self.check_overloaded_binop(expr, lhs_expr, lhs_ty, rhs_expr, op, IsAssign::Yes);
37 let rhs_ty = self.resolve_type_vars_with_obligations(rhs_ty);
39 let ty = if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var()
40 && is_builtin_binop(lhs_ty, rhs_ty, op) {
41 self.enforce_builtin_binop_types(lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
48 if !tcx.expr_is_lval(lhs_expr) {
50 tcx.sess, lhs_expr.span,
51 E0067, "invalid left-hand side expression")
54 "invalid expression for left-hand side")
60 /// Check a potentially overloaded binary operator.
61 pub fn check_binop(&self,
62 expr: &'gcx hir::Expr,
64 lhs_expr: &'gcx hir::Expr,
65 rhs_expr: &'gcx hir::Expr) -> Ty<'tcx>
69 debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
76 let lhs_ty = self.check_expr(lhs_expr);
77 let lhs_ty = self.resolve_type_vars_with_obligations(lhs_ty);
79 match BinOpCategory::from(op) {
80 BinOpCategory::Shortcircuit => {
81 // && and || are a simple case.
82 let lhs_diverges = self.diverges.get();
83 self.demand_suptype(lhs_expr.span, tcx.mk_bool(), lhs_ty);
84 self.check_expr_coercable_to_type(rhs_expr, tcx.mk_bool());
86 // Depending on the LHS' value, the RHS can never execute.
87 self.diverges.set(lhs_diverges);
92 // Otherwise, we always treat operators as if they are
93 // overloaded. This is the way to be most flexible w/r/t
94 // types that get inferred.
95 let (rhs_ty, return_ty) =
96 self.check_overloaded_binop(expr, lhs_expr, lhs_ty,
97 rhs_expr, op, IsAssign::No);
99 // Supply type inference hints if relevant. Probably these
100 // hints should be enforced during select as part of the
101 // `consider_unification_despite_ambiguity` routine, but this
102 // more convenient for now.
104 // The basic idea is to help type inference by taking
105 // advantage of things we know about how the impls for
106 // scalar types are arranged. This is important in a
107 // scenario like `1_u32 << 2`, because it lets us quickly
108 // deduce that the result type should be `u32`, even
109 // though we don't know yet what type 2 has and hence
110 // can't pin this down to a specific impl.
111 let rhs_ty = self.resolve_type_vars_with_obligations(rhs_ty);
113 !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() &&
114 is_builtin_binop(lhs_ty, rhs_ty, op)
116 let builtin_return_ty =
117 self.enforce_builtin_binop_types(lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
118 self.demand_suptype(expr.span, builtin_return_ty, return_ty);
126 fn enforce_builtin_binop_types(&self,
127 lhs_expr: &'gcx hir::Expr,
129 rhs_expr: &'gcx hir::Expr,
134 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
137 match BinOpCategory::from(op) {
138 BinOpCategory::Shortcircuit => {
139 self.demand_suptype(lhs_expr.span, tcx.mk_bool(), lhs_ty);
140 self.demand_suptype(rhs_expr.span, tcx.mk_bool(), rhs_ty);
144 BinOpCategory::Shift => {
145 // result type is same as LHS always
149 BinOpCategory::Math |
150 BinOpCategory::Bitwise => {
151 // both LHS and RHS and result will have the same type
152 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
156 BinOpCategory::Comparison => {
157 // both LHS and RHS and result will have the same type
158 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
164 fn check_overloaded_binop(&self,
165 expr: &'gcx hir::Expr,
166 lhs_expr: &'gcx hir::Expr,
168 rhs_expr: &'gcx hir::Expr,
171 -> (Ty<'tcx>, Ty<'tcx>)
173 debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?}, is_assign={:?})",
178 // NB: As we have not yet type-checked the RHS, we don't have the
179 // type at hand. Make a variable to represent it. The whole reason
180 // for this indirection is so that, below, we can check the expr
181 // using this variable as the expected type, which sometimes lets
182 // us do better coercions than we would be able to do otherwise,
183 // particularly for things like `String + &String`.
184 let rhs_ty_var = self.next_ty_var(TypeVariableOrigin::MiscVariable(rhs_expr.span));
186 let result = self.lookup_op_method(lhs_ty, &[rhs_ty_var], Op::Binary(op, is_assign));
189 let rhs_ty = self.check_expr_coercable_to_type(rhs_expr, rhs_ty_var);
191 let return_ty = match result {
193 let by_ref_binop = !op.node.is_by_value();
194 if is_assign == IsAssign::Yes || by_ref_binop {
195 if let ty::TyRef(region, mt) = method.sig.inputs()[0].sty {
196 let autoref = Adjustment {
197 kind: Adjust::Borrow(AutoBorrow::Ref(region, mt.mutbl)),
198 target: method.sig.inputs()[0]
200 self.apply_adjustments(lhs_expr, vec![autoref]);
204 if let ty::TyRef(region, mt) = method.sig.inputs()[1].sty {
205 let autoref = Adjustment {
206 kind: Adjust::Borrow(AutoBorrow::Ref(region, mt.mutbl)),
207 target: method.sig.inputs()[1]
209 // HACK(eddyb) Bypass checks due to reborrows being in
210 // some cases applied on the RHS, on top of which we need
211 // to autoref, which is not allowed by apply_adjustments.
212 // self.apply_adjustments(rhs_expr, vec![autoref]);
216 .entry(rhs_expr.hir_id)
221 self.write_method_call(expr.hir_id, method);
226 // error types are considered "builtin"
227 if !lhs_ty.references_error() {
228 if let IsAssign::Yes = is_assign {
229 struct_span_err!(self.tcx.sess, expr.span, E0368,
230 "binary assignment operation `{}=` \
231 cannot be applied to type `{}`",
234 .span_label(lhs_expr.span,
235 format!("cannot use `{}=` on type `{}`",
236 op.node.as_str(), lhs_ty))
239 let mut err = struct_span_err!(self.tcx.sess, expr.span, E0369,
240 "binary operation `{}` cannot be applied to type `{}`",
244 if let TypeVariants::TyRef(_, ref ty_mut) = lhs_ty.sty {
246 !self.infcx.type_moves_by_default(self.param_env,
249 self.lookup_op_method(ty_mut.ty,
251 Op::Binary(op, is_assign))
256 "this is a reference to a type that `{}` can be applied \
257 to; you need to dereference this variable once for this \
263 let missing_trait = match op.node {
264 hir::BiAdd => Some("std::ops::Add"),
265 hir::BiSub => Some("std::ops::Sub"),
266 hir::BiMul => Some("std::ops::Mul"),
267 hir::BiDiv => Some("std::ops::Div"),
268 hir::BiRem => Some("std::ops::Rem"),
269 hir::BiBitAnd => Some("std::ops::BitAnd"),
270 hir::BiBitOr => Some("std::ops::BitOr"),
271 hir::BiShl => Some("std::ops::Shl"),
272 hir::BiShr => Some("std::ops::Shr"),
273 hir::BiEq | hir::BiNe => Some("std::cmp::PartialEq"),
274 hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe =>
275 Some("std::cmp::PartialOrd"),
279 if let Some(missing_trait) = missing_trait {
280 if missing_trait == "std::ops::Add" &&
281 self.check_str_addition(expr, lhs_expr, lhs_ty,
283 // This has nothing here because it means we did string
284 // concatenation (e.g. "Hello " + "World!"). This means
285 // we don't want the note in the else clause to be emitted
288 &format!("an implementation of `{}` might be missing for `{}`",
289 missing_trait, lhs_ty));
299 (rhs_ty_var, return_ty)
302 fn check_str_addition(&self,
303 expr: &'gcx hir::Expr,
304 lhs_expr: &'gcx hir::Expr,
307 err: &mut errors::DiagnosticBuilder) -> bool {
308 // If this function returns true it means a note was printed, so we don't need
309 // to print the normal "implementation of `std::ops::Add` might be missing" note
310 let mut is_string_addition = false;
311 if let TyRef(_, l_ty) = lhs_ty.sty {
312 if let TyRef(_, r_ty) = rhs_ty.sty {
313 if l_ty.ty.sty == TyStr && r_ty.ty.sty == TyStr {
314 err.span_label(expr.span,
315 "`+` can't be used to concatenate two `&str` strings");
316 let codemap = self.tcx.sess.codemap();
318 match codemap.span_to_snippet(lhs_expr.span) {
319 Ok(lstring) => format!("{}.to_owned()", lstring),
320 _ => format!("<expression>")
322 err.span_suggestion(lhs_expr.span,
323 &format!("`to_owned()` can be used to create an owned `String` \
324 from a string reference. String concatenation \
325 appends the string on the right to the string \
326 on the left and may require reallocation. This \
327 requires ownership of the string on the left"), suggestion);
328 is_string_addition = true;
338 pub fn check_user_unop(&self,
340 operand_ty: Ty<'tcx>,
344 assert!(op.is_by_value());
345 match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) {
347 self.write_method_call(ex.hir_id, method);
351 let actual = self.resolve_type_vars_if_possible(&operand_ty);
352 if !actual.references_error() {
353 struct_span_err!(self.tcx.sess, ex.span, E0600,
354 "cannot apply unary operator `{}` to type `{}`",
355 op.as_str(), actual).emit();
362 fn lookup_op_method(&self, lhs_ty: Ty<'tcx>, other_tys: &[Ty<'tcx>], op: Op)
363 -> Result<MethodCallee<'tcx>, ()>
365 let lang = &self.tcx.lang_items;
367 let span = match op {
368 Op::Binary(op, _) => op.span,
369 Op::Unary(_, span) => span
371 let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
373 hir::BiAdd => ("add_assign", lang.add_assign_trait()),
374 hir::BiSub => ("sub_assign", lang.sub_assign_trait()),
375 hir::BiMul => ("mul_assign", lang.mul_assign_trait()),
376 hir::BiDiv => ("div_assign", lang.div_assign_trait()),
377 hir::BiRem => ("rem_assign", lang.rem_assign_trait()),
378 hir::BiBitXor => ("bitxor_assign", lang.bitxor_assign_trait()),
379 hir::BiBitAnd => ("bitand_assign", lang.bitand_assign_trait()),
380 hir::BiBitOr => ("bitor_assign", lang.bitor_assign_trait()),
381 hir::BiShl => ("shl_assign", lang.shl_assign_trait()),
382 hir::BiShr => ("shr_assign", lang.shr_assign_trait()),
383 hir::BiLt | hir::BiLe |
384 hir::BiGe | hir::BiGt |
385 hir::BiEq | hir::BiNe |
386 hir::BiAnd | hir::BiOr => {
388 "impossible assignment operation: {}=",
392 } else if let Op::Binary(op, IsAssign::No) = op {
394 hir::BiAdd => ("add", lang.add_trait()),
395 hir::BiSub => ("sub", lang.sub_trait()),
396 hir::BiMul => ("mul", lang.mul_trait()),
397 hir::BiDiv => ("div", lang.div_trait()),
398 hir::BiRem => ("rem", lang.rem_trait()),
399 hir::BiBitXor => ("bitxor", lang.bitxor_trait()),
400 hir::BiBitAnd => ("bitand", lang.bitand_trait()),
401 hir::BiBitOr => ("bitor", lang.bitor_trait()),
402 hir::BiShl => ("shl", lang.shl_trait()),
403 hir::BiShr => ("shr", lang.shr_trait()),
404 hir::BiLt => ("lt", lang.ord_trait()),
405 hir::BiLe => ("le", lang.ord_trait()),
406 hir::BiGe => ("ge", lang.ord_trait()),
407 hir::BiGt => ("gt", lang.ord_trait()),
408 hir::BiEq => ("eq", lang.eq_trait()),
409 hir::BiNe => ("ne", lang.eq_trait()),
410 hir::BiAnd | hir::BiOr => {
411 span_bug!(span, "&& and || are not overloadable")
414 } else if let Op::Unary(hir::UnNot, _) = op {
415 ("not", lang.not_trait())
416 } else if let Op::Unary(hir::UnNeg, _) = op {
417 ("neg", lang.neg_trait())
419 bug!("lookup_op_method: op not supported: {:?}", op)
422 debug!("lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
428 let method = trait_did.and_then(|trait_did| {
429 let opname = Symbol::intern(opname);
430 self.lookup_method_in_trait(span, opname, trait_did, lhs_ty, Some(other_tys))
435 let method = self.register_infer_ok_obligations(ok);
436 self.select_obligations_where_possible();
447 // Binary operator categories. These categories summarize the behavior
448 // with respect to the builtin operationrs supported.
450 /// &&, || -- cannot be overridden
453 /// <<, >> -- when shifting a single integer, rhs can be any
454 /// integer type. For simd, types must match.
457 /// +, -, etc -- takes equal types, produces same type as input,
458 /// applicable to ints/floats/simd
461 /// &, |, ^ -- takes equal types, produces same type as input,
462 /// applicable to ints/floats/simd/bool
465 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
466 /// which produce the input type
471 fn from(op: hir::BinOp) -> BinOpCategory {
473 hir::BiShl | hir::BiShr =>
474 BinOpCategory::Shift,
486 BinOpCategory::Bitwise,
494 BinOpCategory::Comparison,
498 BinOpCategory::Shortcircuit,
503 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
504 #[derive(Clone, Copy, Debug, PartialEq)]
510 #[derive(Clone, Copy, Debug)]
512 Binary(hir::BinOp, IsAssign),
513 Unary(hir::UnOp, Span),
516 /// Returns true if this is a built-in arithmetic operation (e.g. u32
517 /// + u32, i16x4 == i16x4) and false if these types would have to be
518 /// overloaded to be legal. There are two reasons that we distinguish
519 /// builtin operations from overloaded ones (vs trying to drive
520 /// everything uniformly through the trait system and intrinsics or
521 /// something like that):
523 /// 1. Builtin operations can trivially be evaluated in constants.
524 /// 2. For comparison operators applied to SIMD types the result is
525 /// not of type `bool`. For example, `i16x4==i16x4` yields a
526 /// type like `i16x4`. This means that the overloaded trait
527 /// `PartialEq` is not applicable.
529 /// Reason #2 is the killer. I tried for a while to always use
530 /// overloaded logic and just check the types in constants/trans after
531 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
532 fn is_builtin_binop(lhs: Ty, rhs: Ty, op: hir::BinOp) -> bool {
533 match BinOpCategory::from(op) {
534 BinOpCategory::Shortcircuit => {
538 BinOpCategory::Shift => {
539 lhs.references_error() || rhs.references_error() ||
540 lhs.is_integral() && rhs.is_integral()
543 BinOpCategory::Math => {
544 lhs.references_error() || rhs.references_error() ||
545 lhs.is_integral() && rhs.is_integral() ||
546 lhs.is_floating_point() && rhs.is_floating_point()
549 BinOpCategory::Bitwise => {
550 lhs.references_error() || rhs.references_error() ||
551 lhs.is_integral() && rhs.is_integral() ||
552 lhs.is_floating_point() && rhs.is_floating_point() ||
553 lhs.is_bool() && rhs.is_bool()
556 BinOpCategory::Comparison => {
557 lhs.references_error() || rhs.references_error() ||
558 lhs.is_scalar() && rhs.is_scalar()