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.
13 use super::{FnCtxt, Needs};
14 use super::method::MethodCallee;
15 use rustc::ty::{self, Ty, TypeFoldable, TypeVariants};
16 use rustc::ty::TypeVariants::{TyStr, TyRef, TyAdt};
17 use rustc::ty::adjustment::{Adjustment, Adjust, AutoBorrow, AutoBorrowMutability};
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, rhs_ty, return_ty) =
33 self.check_overloaded_binop(expr, lhs_expr, rhs_expr, op, IsAssign::Yes);
35 let ty = if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var()
36 && is_builtin_binop(lhs_ty, rhs_ty, op) {
37 self.enforce_builtin_binop_types(lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
43 if !self.is_place_expr(lhs_expr) {
45 self.tcx.sess, lhs_expr.span,
46 E0067, "invalid left-hand side expression")
49 "invalid expression for left-hand side")
55 /// Check a potentially overloaded binary operator.
56 pub fn check_binop(&self,
57 expr: &'gcx hir::Expr,
59 lhs_expr: &'gcx hir::Expr,
60 rhs_expr: &'gcx hir::Expr) -> Ty<'tcx>
64 debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
71 match BinOpCategory::from(op) {
72 BinOpCategory::Shortcircuit => {
73 // && and || are a simple case.
74 self.check_expr_coercable_to_type(lhs_expr, tcx.types.bool);
75 let lhs_diverges = self.diverges.get();
76 self.check_expr_coercable_to_type(rhs_expr, tcx.types.bool);
78 // Depending on the LHS' value, the RHS can never execute.
79 self.diverges.set(lhs_diverges);
84 // Otherwise, we always treat operators as if they are
85 // overloaded. This is the way to be most flexible w/r/t
86 // types that get inferred.
87 let (lhs_ty, rhs_ty, return_ty) =
88 self.check_overloaded_binop(expr, lhs_expr,
89 rhs_expr, op, IsAssign::No);
91 // Supply type inference hints if relevant. Probably these
92 // hints should be enforced during select as part of the
93 // `consider_unification_despite_ambiguity` routine, but this
94 // more convenient for now.
96 // The basic idea is to help type inference by taking
97 // advantage of things we know about how the impls for
98 // scalar types are arranged. This is important in a
99 // scenario like `1_u32 << 2`, because it lets us quickly
100 // deduce that the result type should be `u32`, even
101 // though we don't know yet what type 2 has and hence
102 // can't pin this down to a specific impl.
104 !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() &&
105 is_builtin_binop(lhs_ty, rhs_ty, op)
107 let builtin_return_ty =
108 self.enforce_builtin_binop_types(lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
109 self.demand_suptype(expr.span, builtin_return_ty, return_ty);
117 fn enforce_builtin_binop_types(&self,
118 lhs_expr: &'gcx hir::Expr,
120 rhs_expr: &'gcx hir::Expr,
125 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
128 match BinOpCategory::from(op) {
129 BinOpCategory::Shortcircuit => {
130 self.demand_suptype(lhs_expr.span, tcx.mk_bool(), lhs_ty);
131 self.demand_suptype(rhs_expr.span, tcx.mk_bool(), rhs_ty);
135 BinOpCategory::Shift => {
136 // result type is same as LHS always
140 BinOpCategory::Math |
141 BinOpCategory::Bitwise => {
142 // both LHS and RHS and result will have the same type
143 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
147 BinOpCategory::Comparison => {
148 // both LHS and RHS and result will have the same type
149 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
155 fn check_overloaded_binop(&self,
156 expr: &'gcx hir::Expr,
157 lhs_expr: &'gcx hir::Expr,
158 rhs_expr: &'gcx hir::Expr,
161 -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>)
163 debug!("check_overloaded_binop(expr.id={}, op={:?}, is_assign={:?})",
168 let lhs_needs = match is_assign {
169 IsAssign::Yes => Needs::MutPlace,
170 IsAssign::No => Needs::None
172 // Find a suitable supertype of the LHS expression's type, by coercing to
173 // a type variable, to pass as the `Self` to the trait, avoiding invariant
174 // trait matching creating lifetime constraints that are too strict.
175 // E.g. adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
176 // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`.
177 let lhs_ty = self.check_expr_coercable_to_type_with_needs(lhs_expr,
178 self.next_ty_var(TypeVariableOrigin::MiscVariable(lhs_expr.span)),
180 let lhs_ty = self.resolve_type_vars_with_obligations(lhs_ty);
182 // NB: As we have not yet type-checked the RHS, we don't have the
183 // type at hand. Make a variable to represent it. The whole reason
184 // for this indirection is so that, below, we can check the expr
185 // using this variable as the expected type, which sometimes lets
186 // us do better coercions than we would be able to do otherwise,
187 // particularly for things like `String + &String`.
188 let rhs_ty_var = self.next_ty_var(TypeVariableOrigin::MiscVariable(rhs_expr.span));
190 let result = self.lookup_op_method(lhs_ty, &[rhs_ty_var], Op::Binary(op, is_assign));
193 let rhs_ty = self.check_expr_coercable_to_type(rhs_expr, rhs_ty_var);
194 let rhs_ty = self.resolve_type_vars_with_obligations(rhs_ty);
196 let return_ty = match result {
198 let by_ref_binop = !op.node.is_by_value();
199 if is_assign == IsAssign::Yes || by_ref_binop {
200 if let ty::TyRef(region, mt) = method.sig.inputs()[0].sty {
201 let mutbl = match mt.mutbl {
202 hir::MutImmutable => AutoBorrowMutability::Immutable,
203 hir::MutMutable => AutoBorrowMutability::Mutable {
204 // Allow two-phase borrows for binops in initial deployment
205 // since they desugar to methods
206 allow_two_phase_borrow: true,
209 let autoref = Adjustment {
210 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
211 target: method.sig.inputs()[0]
213 self.apply_adjustments(lhs_expr, vec![autoref]);
217 if let ty::TyRef(region, mt) = method.sig.inputs()[1].sty {
218 let mutbl = match mt.mutbl {
219 hir::MutImmutable => AutoBorrowMutability::Immutable,
220 hir::MutMutable => AutoBorrowMutability::Mutable {
221 // Allow two-phase borrows for binops in initial deployment
222 // since they desugar to methods
223 allow_two_phase_borrow: true,
226 let autoref = Adjustment {
227 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
228 target: method.sig.inputs()[1]
230 // HACK(eddyb) Bypass checks due to reborrows being in
231 // some cases applied on the RHS, on top of which we need
232 // to autoref, which is not allowed by apply_adjustments.
233 // self.apply_adjustments(rhs_expr, vec![autoref]);
237 .entry(rhs_expr.hir_id)
242 self.write_method_call(expr.hir_id, method);
247 // error types are considered "builtin"
248 if !lhs_ty.references_error() {
249 if let IsAssign::Yes = is_assign {
250 struct_span_err!(self.tcx.sess, expr.span, E0368,
251 "binary assignment operation `{}=` \
252 cannot be applied to type `{}`",
255 .span_label(lhs_expr.span,
256 format!("cannot use `{}=` on type `{}`",
257 op.node.as_str(), lhs_ty))
260 let mut err = struct_span_err!(self.tcx.sess, expr.span, E0369,
261 "binary operation `{}` cannot be applied to type `{}`",
265 if let TypeVariants::TyRef(_, ref ty_mut) = lhs_ty.sty {
267 !self.infcx.type_moves_by_default(self.param_env,
270 self.lookup_op_method(ty_mut.ty,
272 Op::Binary(op, is_assign))
277 "this is a reference to a type that `{}` can be applied \
278 to; you need to dereference this variable once for this \
284 let missing_trait = match op.node {
285 hir::BiAdd => Some("std::ops::Add"),
286 hir::BiSub => Some("std::ops::Sub"),
287 hir::BiMul => Some("std::ops::Mul"),
288 hir::BiDiv => Some("std::ops::Div"),
289 hir::BiRem => Some("std::ops::Rem"),
290 hir::BiBitAnd => Some("std::ops::BitAnd"),
291 hir::BiBitOr => Some("std::ops::BitOr"),
292 hir::BiShl => Some("std::ops::Shl"),
293 hir::BiShr => Some("std::ops::Shr"),
294 hir::BiEq | hir::BiNe => Some("std::cmp::PartialEq"),
295 hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe =>
296 Some("std::cmp::PartialOrd"),
300 if let Some(missing_trait) = missing_trait {
301 if missing_trait == "std::ops::Add" &&
302 self.check_str_addition(expr, lhs_expr, rhs_expr, lhs_ty,
304 // This has nothing here because it means we did string
305 // concatenation (e.g. "Hello " + "World!"). This means
306 // we don't want the note in the else clause to be emitted
307 } else if let ty::TyParam(_) = lhs_ty.sty {
308 // FIXME: point to span of param
310 &format!("`{}` might need a bound for `{}`",
311 lhs_ty, missing_trait));
314 &format!("an implementation of `{}` might be missing for `{}`",
315 missing_trait, lhs_ty));
325 (lhs_ty, rhs_ty, return_ty)
328 fn check_str_addition(&self,
329 expr: &'gcx hir::Expr,
330 lhs_expr: &'gcx hir::Expr,
331 rhs_expr: &'gcx hir::Expr,
334 err: &mut errors::DiagnosticBuilder) -> bool {
335 let codemap = self.tcx.sess.codemap();
336 let msg = "`to_owned()` can be used to create an owned `String` \
337 from a string reference. String concatenation \
338 appends the string on the right to the string \
339 on the left and may require reallocation. This \
340 requires ownership of the string on the left";
341 // If this function returns true it means a note was printed, so we don't need
342 // to print the normal "implementation of `std::ops::Add` might be missing" note
343 match (&lhs_ty.sty, &rhs_ty.sty) {
344 (&TyRef(_, ref l_ty), &TyRef(_, ref r_ty))
345 if l_ty.ty.sty == TyStr && r_ty.ty.sty == TyStr => {
346 err.span_label(expr.span,
347 "`+` can't be used to concatenate two `&str` strings");
348 match codemap.span_to_snippet(lhs_expr.span) {
349 Ok(lstring) => err.span_suggestion(lhs_expr.span,
351 format!("{}.to_owned()", lstring)),
356 (&TyRef(_, ref l_ty), &TyAdt(..))
357 if l_ty.ty.sty == TyStr && &format!("{:?}", rhs_ty) == "std::string::String" => {
358 err.span_label(expr.span,
359 "`+` can't be used to concatenate a `&str` with a `String`");
360 match codemap.span_to_snippet(lhs_expr.span) {
361 Ok(lstring) => err.span_suggestion(lhs_expr.span,
363 format!("{}.to_owned()", lstring)),
366 match codemap.span_to_snippet(rhs_expr.span) {
368 err.span_suggestion(rhs_expr.span,
369 "you also need to borrow the `String` on the right to \
371 format!("&{}", rstring));
381 pub fn check_user_unop(&self,
383 operand_ty: Ty<'tcx>,
387 assert!(op.is_by_value());
388 match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) {
390 self.write_method_call(ex.hir_id, method);
394 let actual = self.resolve_type_vars_if_possible(&operand_ty);
395 if !actual.references_error() {
396 struct_span_err!(self.tcx.sess, ex.span, E0600,
397 "cannot apply unary operator `{}` to type `{}`",
398 op.as_str(), actual).emit();
405 fn lookup_op_method(&self, lhs_ty: Ty<'tcx>, other_tys: &[Ty<'tcx>], op: Op)
406 -> Result<MethodCallee<'tcx>, ()>
408 let lang = self.tcx.lang_items();
410 let span = match op {
411 Op::Binary(op, _) => op.span,
412 Op::Unary(_, span) => span
414 let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
416 hir::BiAdd => ("add_assign", lang.add_assign_trait()),
417 hir::BiSub => ("sub_assign", lang.sub_assign_trait()),
418 hir::BiMul => ("mul_assign", lang.mul_assign_trait()),
419 hir::BiDiv => ("div_assign", lang.div_assign_trait()),
420 hir::BiRem => ("rem_assign", lang.rem_assign_trait()),
421 hir::BiBitXor => ("bitxor_assign", lang.bitxor_assign_trait()),
422 hir::BiBitAnd => ("bitand_assign", lang.bitand_assign_trait()),
423 hir::BiBitOr => ("bitor_assign", lang.bitor_assign_trait()),
424 hir::BiShl => ("shl_assign", lang.shl_assign_trait()),
425 hir::BiShr => ("shr_assign", lang.shr_assign_trait()),
426 hir::BiLt | hir::BiLe |
427 hir::BiGe | hir::BiGt |
428 hir::BiEq | hir::BiNe |
429 hir::BiAnd | hir::BiOr => {
431 "impossible assignment operation: {}=",
435 } else if let Op::Binary(op, IsAssign::No) = op {
437 hir::BiAdd => ("add", lang.add_trait()),
438 hir::BiSub => ("sub", lang.sub_trait()),
439 hir::BiMul => ("mul", lang.mul_trait()),
440 hir::BiDiv => ("div", lang.div_trait()),
441 hir::BiRem => ("rem", lang.rem_trait()),
442 hir::BiBitXor => ("bitxor", lang.bitxor_trait()),
443 hir::BiBitAnd => ("bitand", lang.bitand_trait()),
444 hir::BiBitOr => ("bitor", lang.bitor_trait()),
445 hir::BiShl => ("shl", lang.shl_trait()),
446 hir::BiShr => ("shr", lang.shr_trait()),
447 hir::BiLt => ("lt", lang.partial_ord_trait()),
448 hir::BiLe => ("le", lang.partial_ord_trait()),
449 hir::BiGe => ("ge", lang.partial_ord_trait()),
450 hir::BiGt => ("gt", lang.partial_ord_trait()),
451 hir::BiEq => ("eq", lang.eq_trait()),
452 hir::BiNe => ("ne", lang.eq_trait()),
453 hir::BiAnd | hir::BiOr => {
454 span_bug!(span, "&& and || are not overloadable")
457 } else if let Op::Unary(hir::UnNot, _) = op {
458 ("not", lang.not_trait())
459 } else if let Op::Unary(hir::UnNeg, _) = op {
460 ("neg", lang.neg_trait())
462 bug!("lookup_op_method: op not supported: {:?}", op)
465 debug!("lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
471 let method = trait_did.and_then(|trait_did| {
472 let opname = Symbol::intern(opname);
473 self.lookup_method_in_trait(span, opname, trait_did, lhs_ty, Some(other_tys))
478 let method = self.register_infer_ok_obligations(ok);
479 self.select_obligations_where_possible(false);
490 // Binary operator categories. These categories summarize the behavior
491 // with respect to the builtin operationrs supported.
493 /// &&, || -- cannot be overridden
496 /// <<, >> -- when shifting a single integer, rhs can be any
497 /// integer type. For simd, types must match.
500 /// +, -, etc -- takes equal types, produces same type as input,
501 /// applicable to ints/floats/simd
504 /// &, |, ^ -- takes equal types, produces same type as input,
505 /// applicable to ints/floats/simd/bool
508 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
509 /// which produce the input type
514 fn from(op: hir::BinOp) -> BinOpCategory {
516 hir::BiShl | hir::BiShr =>
517 BinOpCategory::Shift,
529 BinOpCategory::Bitwise,
537 BinOpCategory::Comparison,
541 BinOpCategory::Shortcircuit,
546 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
547 #[derive(Clone, Copy, Debug, PartialEq)]
553 #[derive(Clone, Copy, Debug)]
555 Binary(hir::BinOp, IsAssign),
556 Unary(hir::UnOp, Span),
559 /// Returns true if this is a built-in arithmetic operation (e.g. u32
560 /// + u32, i16x4 == i16x4) and false if these types would have to be
561 /// overloaded to be legal. There are two reasons that we distinguish
562 /// builtin operations from overloaded ones (vs trying to drive
563 /// everything uniformly through the trait system and intrinsics or
564 /// something like that):
566 /// 1. Builtin operations can trivially be evaluated in constants.
567 /// 2. For comparison operators applied to SIMD types the result is
568 /// not of type `bool`. For example, `i16x4==i16x4` yields a
569 /// type like `i16x4`. This means that the overloaded trait
570 /// `PartialEq` is not applicable.
572 /// Reason #2 is the killer. I tried for a while to always use
573 /// overloaded logic and just check the types in constants/trans after
574 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
575 fn is_builtin_binop(lhs: Ty, rhs: Ty, op: hir::BinOp) -> bool {
576 match BinOpCategory::from(op) {
577 BinOpCategory::Shortcircuit => {
581 BinOpCategory::Shift => {
582 lhs.references_error() || rhs.references_error() ||
583 lhs.is_integral() && rhs.is_integral()
586 BinOpCategory::Math => {
587 lhs.references_error() || rhs.references_error() ||
588 lhs.is_integral() && rhs.is_integral() ||
589 lhs.is_floating_point() && rhs.is_floating_point()
592 BinOpCategory::Bitwise => {
593 lhs.references_error() || rhs.references_error() ||
594 lhs.is_integral() && rhs.is_integral() ||
595 lhs.is_floating_point() && rhs.is_floating_point() ||
596 lhs.is_bool() && rhs.is_bool()
599 BinOpCategory::Comparison => {
600 lhs.references_error() || rhs.references_error() ||
601 lhs.is_scalar() && rhs.is_scalar()