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]);
213 self.tables.borrow_mut().adjustments.entry(rhs_expr.id)
214 .or_insert(vec![]).push(autoref);
217 self.write_method_call(expr.id, method);
222 // error types are considered "builtin"
223 if !lhs_ty.references_error() {
224 if let IsAssign::Yes = is_assign {
225 struct_span_err!(self.tcx.sess, expr.span, E0368,
226 "binary assignment operation `{}=` \
227 cannot be applied to type `{}`",
230 .span_label(lhs_expr.span,
231 format!("cannot use `{}=` on type `{}`",
232 op.node.as_str(), lhs_ty))
235 let mut err = struct_span_err!(self.tcx.sess, expr.span, E0369,
236 "binary operation `{}` cannot be applied to type `{}`",
240 if let TypeVariants::TyRef(_, ref ty_mut) = lhs_ty.sty {
242 !self.infcx.type_moves_by_default(self.param_env,
245 self.lookup_op_method(ty_mut.ty,
247 Op::Binary(op, is_assign))
252 "this is a reference to a type that `{}` can be applied \
253 to; you need to dereference this variable once for this \
259 let missing_trait = match op.node {
260 hir::BiAdd => Some("std::ops::Add"),
261 hir::BiSub => Some("std::ops::Sub"),
262 hir::BiMul => Some("std::ops::Mul"),
263 hir::BiDiv => Some("std::ops::Div"),
264 hir::BiRem => Some("std::ops::Rem"),
265 hir::BiBitAnd => Some("std::ops::BitAnd"),
266 hir::BiBitOr => Some("std::ops::BitOr"),
267 hir::BiShl => Some("std::ops::Shl"),
268 hir::BiShr => Some("std::ops::Shr"),
269 hir::BiEq | hir::BiNe => Some("std::cmp::PartialEq"),
270 hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe =>
271 Some("std::cmp::PartialOrd"),
275 if let Some(missing_trait) = missing_trait {
276 if missing_trait == "std::ops::Add" &&
277 self.check_str_addition(expr, lhs_expr, lhs_ty,
279 // This has nothing here because it means we did string
280 // concatenation (e.g. "Hello " + "World!"). This means
281 // we don't want the note in the else clause to be emitted
284 &format!("an implementation of `{}` might be missing for `{}`",
285 missing_trait, lhs_ty));
295 (rhs_ty_var, return_ty)
298 fn check_str_addition(&self,
299 expr: &'gcx hir::Expr,
300 lhs_expr: &'gcx hir::Expr,
303 mut err: &mut errors::DiagnosticBuilder) -> bool {
304 // If this function returns true it means a note was printed, so we don't need
305 // to print the normal "implementation of `std::ops::Add` might be missing" note
306 let mut is_string_addition = false;
307 if let TyRef(_, l_ty) = lhs_ty.sty {
308 if let TyRef(_, r_ty) = rhs_ty.sty {
309 if l_ty.ty.sty == TyStr && r_ty.ty.sty == TyStr {
310 err.span_label(expr.span,
311 "`+` can't be used to concatenate two `&str` strings");
312 let codemap = self.tcx.sess.codemap();
314 match codemap.span_to_snippet(lhs_expr.span) {
315 Ok(lstring) => format!("{}.to_owned()", lstring),
316 _ => format!("<expression>")
318 err.span_suggestion(lhs_expr.span,
319 &format!("`to_owned()` can be used to create an owned `String` \
320 from a string reference. String concatenation \
321 appends the string on the right to the string \
322 on the left and may require reallocation. This \
323 requires ownership of the string on the left"), suggestion);
324 is_string_addition = true;
334 pub fn check_user_unop(&self,
336 operand_ty: Ty<'tcx>,
340 assert!(op.is_by_value());
341 match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) {
343 self.write_method_call(ex.id, method);
347 let actual = self.resolve_type_vars_if_possible(&operand_ty);
348 if !actual.references_error() {
349 struct_span_err!(self.tcx.sess, ex.span, E0600,
350 "cannot apply unary operator `{}` to type `{}`",
351 op.as_str(), actual).emit();
358 fn lookup_op_method(&self, lhs_ty: Ty<'tcx>, other_tys: &[Ty<'tcx>], op: Op)
359 -> Result<MethodCallee<'tcx>, ()>
361 let lang = &self.tcx.lang_items;
363 let span = match op {
364 Op::Binary(op, _) => op.span,
365 Op::Unary(_, span) => span
367 let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
369 hir::BiAdd => ("add_assign", lang.add_assign_trait()),
370 hir::BiSub => ("sub_assign", lang.sub_assign_trait()),
371 hir::BiMul => ("mul_assign", lang.mul_assign_trait()),
372 hir::BiDiv => ("div_assign", lang.div_assign_trait()),
373 hir::BiRem => ("rem_assign", lang.rem_assign_trait()),
374 hir::BiBitXor => ("bitxor_assign", lang.bitxor_assign_trait()),
375 hir::BiBitAnd => ("bitand_assign", lang.bitand_assign_trait()),
376 hir::BiBitOr => ("bitor_assign", lang.bitor_assign_trait()),
377 hir::BiShl => ("shl_assign", lang.shl_assign_trait()),
378 hir::BiShr => ("shr_assign", lang.shr_assign_trait()),
379 hir::BiLt | hir::BiLe |
380 hir::BiGe | hir::BiGt |
381 hir::BiEq | hir::BiNe |
382 hir::BiAnd | hir::BiOr => {
384 "impossible assignment operation: {}=",
388 } else if let Op::Binary(op, IsAssign::No) = op {
390 hir::BiAdd => ("add", lang.add_trait()),
391 hir::BiSub => ("sub", lang.sub_trait()),
392 hir::BiMul => ("mul", lang.mul_trait()),
393 hir::BiDiv => ("div", lang.div_trait()),
394 hir::BiRem => ("rem", lang.rem_trait()),
395 hir::BiBitXor => ("bitxor", lang.bitxor_trait()),
396 hir::BiBitAnd => ("bitand", lang.bitand_trait()),
397 hir::BiBitOr => ("bitor", lang.bitor_trait()),
398 hir::BiShl => ("shl", lang.shl_trait()),
399 hir::BiShr => ("shr", lang.shr_trait()),
400 hir::BiLt => ("lt", lang.ord_trait()),
401 hir::BiLe => ("le", lang.ord_trait()),
402 hir::BiGe => ("ge", lang.ord_trait()),
403 hir::BiGt => ("gt", lang.ord_trait()),
404 hir::BiEq => ("eq", lang.eq_trait()),
405 hir::BiNe => ("ne", lang.eq_trait()),
406 hir::BiAnd | hir::BiOr => {
407 span_bug!(span, "&& and || are not overloadable")
410 } else if let Op::Unary(hir::UnNot, _) = op {
411 ("not", lang.not_trait())
412 } else if let Op::Unary(hir::UnNeg, _) = op {
413 ("neg", lang.neg_trait())
415 bug!("lookup_op_method: op not supported: {:?}", op)
418 debug!("lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
424 let method = trait_did.and_then(|trait_did| {
425 let opname = Symbol::intern(opname);
426 self.lookup_method_in_trait(span, opname, trait_did, lhs_ty, Some(other_tys))
431 let method = self.register_infer_ok_obligations(ok);
432 self.select_obligations_where_possible();
443 // Binary operator categories. These categories summarize the behavior
444 // with respect to the builtin operationrs supported.
446 /// &&, || -- cannot be overridden
449 /// <<, >> -- when shifting a single integer, rhs can be any
450 /// integer type. For simd, types must match.
453 /// +, -, etc -- takes equal types, produces same type as input,
454 /// applicable to ints/floats/simd
457 /// &, |, ^ -- takes equal types, produces same type as input,
458 /// applicable to ints/floats/simd/bool
461 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
462 /// which produce the input type
467 fn from(op: hir::BinOp) -> BinOpCategory {
469 hir::BiShl | hir::BiShr =>
470 BinOpCategory::Shift,
482 BinOpCategory::Bitwise,
490 BinOpCategory::Comparison,
494 BinOpCategory::Shortcircuit,
499 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
500 #[derive(Clone, Copy, Debug, PartialEq)]
506 #[derive(Clone, Copy, Debug)]
508 Binary(hir::BinOp, IsAssign),
509 Unary(hir::UnOp, Span),
512 /// Returns true if this is a built-in arithmetic operation (e.g. u32
513 /// + u32, i16x4 == i16x4) and false if these types would have to be
514 /// overloaded to be legal. There are two reasons that we distinguish
515 /// builtin operations from overloaded ones (vs trying to drive
516 /// everything uniformly through the trait system and intrinsics or
517 /// something like that):
519 /// 1. Builtin operations can trivially be evaluated in constants.
520 /// 2. For comparison operators applied to SIMD types the result is
521 /// not of type `bool`. For example, `i16x4==i16x4` yields a
522 /// type like `i16x4`. This means that the overloaded trait
523 /// `PartialEq` is not applicable.
525 /// Reason #2 is the killer. I tried for a while to always use
526 /// overloaded logic and just check the types in constants/trans after
527 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
528 fn is_builtin_binop(lhs: Ty, rhs: Ty, op: hir::BinOp) -> bool {
529 match BinOpCategory::from(op) {
530 BinOpCategory::Shortcircuit => {
534 BinOpCategory::Shift => {
535 lhs.references_error() || rhs.references_error() ||
536 lhs.is_integral() && rhs.is_integral()
539 BinOpCategory::Math => {
540 lhs.references_error() || rhs.references_error() ||
541 lhs.is_integral() && rhs.is_integral() ||
542 lhs.is_floating_point() && rhs.is_floating_point()
545 BinOpCategory::Bitwise => {
546 lhs.references_error() || rhs.references_error() ||
547 lhs.is_integral() && rhs.is_integral() ||
548 lhs.is_floating_point() && rhs.is_floating_point() ||
549 lhs.is_bool() && rhs.is_bool()
552 BinOpCategory::Comparison => {
553 lhs.references_error() || rhs.references_error() ||
554 lhs.is_scalar() && rhs.is_scalar()