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.
15 check_expr_coercable_to_type,
16 check_expr_with_lvalue_pref,
21 structurally_resolved_type,
23 use middle::def_id::DefId;
25 use middle::ty::{Ty, HasTypeFlags};
27 use syntax::parse::token;
29 use rustc_front::util as hir_util;
31 /// Check a `a <op>= b`
32 pub fn check_binop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
33 expr: &'tcx hir::Expr,
35 lhs_expr: &'tcx hir::Expr,
36 rhs_expr: &'tcx hir::Expr)
38 let tcx = fcx.ccx.tcx;
40 check_expr_with_lvalue_pref(fcx, lhs_expr, PreferMutLvalue);
41 check_expr(fcx, rhs_expr);
43 let lhs_ty = structurally_resolved_type(fcx, lhs_expr.span, fcx.expr_ty(lhs_expr));
44 let rhs_ty = structurally_resolved_type(fcx, rhs_expr.span, fcx.expr_ty(rhs_expr));
46 if is_builtin_binop(lhs_ty, rhs_ty, op) {
47 enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
48 fcx.write_nil(expr.id);
50 // error types are considered "builtin"
51 assert!(!lhs_ty.references_error() || !rhs_ty.references_error());
52 span_err!(tcx.sess, lhs_expr.span, E0368,
53 "binary assignment operation `{}=` cannot be applied to types `{}` and `{}`",
54 hir_util::binop_to_string(op.node),
57 fcx.write_error(expr.id);
61 if !tcx.expr_is_lval(lhs_expr) {
62 span_err!(tcx.sess, lhs_expr.span, E0067, "invalid left-hand side expression");
65 fcx.require_expr_have_sized_type(lhs_expr, traits::AssignmentLhsSized);
68 /// Check a potentially overloaded binary operator.
69 pub fn check_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
70 expr: &'tcx hir::Expr,
72 lhs_expr: &'tcx hir::Expr,
73 rhs_expr: &'tcx hir::Expr)
75 let tcx = fcx.ccx.tcx;
77 debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
84 check_expr(fcx, lhs_expr);
85 let lhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
87 match BinOpCategory::from(op) {
88 BinOpCategory::Shortcircuit => {
89 // && and || are a simple case.
90 demand::suptype(fcx, lhs_expr.span, tcx.mk_bool(), lhs_ty);
91 check_expr_coercable_to_type(fcx, rhs_expr, tcx.mk_bool());
92 fcx.write_ty(expr.id, tcx.mk_bool());
95 // Otherwise, we always treat operators as if they are
96 // overloaded. This is the way to be most flexible w/r/t
97 // types that get inferred.
98 let (rhs_ty, return_ty) =
99 check_overloaded_binop(fcx, expr, lhs_expr, lhs_ty, rhs_expr, op);
101 // Supply type inference hints if relevant. Probably these
102 // hints should be enforced during select as part of the
103 // `consider_unification_despite_ambiguity` routine, but this
104 // more convenient for now.
106 // The basic idea is to help type inference by taking
107 // advantage of things we know about how the impls for
108 // scalar types are arranged. This is important in a
109 // scenario like `1_u32 << 2`, because it lets us quickly
110 // deduce that the result type should be `u32`, even
111 // though we don't know yet what type 2 has and hence
112 // can't pin this down to a specific impl.
113 let rhs_ty = fcx.resolve_type_vars_if_possible(rhs_ty);
115 !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() &&
116 is_builtin_binop(lhs_ty, rhs_ty, op)
118 let builtin_return_ty =
119 enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
120 demand::suptype(fcx, expr.span, builtin_return_ty, return_ty);
123 fcx.write_ty(expr.id, return_ty);
128 fn enforce_builtin_binop_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
129 lhs_expr: &'tcx hir::Expr,
131 rhs_expr: &'tcx hir::Expr,
136 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
139 match BinOpCategory::from(op) {
140 BinOpCategory::Shortcircuit => {
141 demand::suptype(fcx, lhs_expr.span, tcx.mk_bool(), lhs_ty);
142 demand::suptype(fcx, rhs_expr.span, tcx.mk_bool(), rhs_ty);
146 BinOpCategory::Shift => {
147 // result type is same as LHS always
151 BinOpCategory::Math |
152 BinOpCategory::Bitwise => {
153 // both LHS and RHS and result will have the same type
154 demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
158 BinOpCategory::Comparison => {
159 // both LHS and RHS and result will have the same type
160 demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
166 fn check_overloaded_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
167 expr: &'tcx hir::Expr,
168 lhs_expr: &'tcx hir::Expr,
170 rhs_expr: &'tcx hir::Expr,
172 -> (Ty<'tcx>, Ty<'tcx>)
174 debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?})",
178 let (name, trait_def_id) = name_and_trait_def_id(fcx, op);
180 // NB: As we have not yet type-checked the RHS, we don't have the
181 // type at hand. Make a variable to represent it. The whole reason
182 // for this indirection is so that, below, we can check the expr
183 // using this variable as the expected type, which sometimes lets
184 // us do better coercions than we would be able to do otherwise,
185 // particularly for things like `String + &String`.
186 let rhs_ty_var = fcx.infcx().next_ty_var();
188 let return_ty = match lookup_op_method(fcx, expr, lhs_ty, vec![rhs_ty_var],
189 token::intern(name), trait_def_id,
191 Ok(return_ty) => return_ty,
193 // error types are considered "builtin"
194 if !lhs_ty.references_error() {
195 span_err!(fcx.tcx().sess, lhs_expr.span, E0369,
196 "binary operation `{}` cannot be applied to type `{}`",
197 hir_util::binop_to_string(op.node),
205 check_expr_coercable_to_type(fcx, rhs_expr, rhs_ty_var);
207 (rhs_ty_var, return_ty)
210 pub fn check_user_unop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
213 trait_did: Option<DefId>,
215 operand_expr: &'tcx hir::Expr,
216 operand_ty: Ty<'tcx>,
220 assert!(hir_util::is_by_value_unop(op));
221 match lookup_op_method(fcx, ex, operand_ty, vec![],
222 token::intern(mname), trait_did,
226 fcx.type_error_message(ex.span, |actual| {
227 format!("cannot apply unary operator `{}` to type `{}`",
229 }, operand_ty, None);
235 fn name_and_trait_def_id(fcx: &FnCtxt, op: hir::BinOp) -> (&'static str, Option<DefId>) {
236 let lang = &fcx.tcx().lang_items;
238 hir::BiAdd => ("add", lang.add_trait()),
239 hir::BiSub => ("sub", lang.sub_trait()),
240 hir::BiMul => ("mul", lang.mul_trait()),
241 hir::BiDiv => ("div", lang.div_trait()),
242 hir::BiRem => ("rem", lang.rem_trait()),
243 hir::BiBitXor => ("bitxor", lang.bitxor_trait()),
244 hir::BiBitAnd => ("bitand", lang.bitand_trait()),
245 hir::BiBitOr => ("bitor", lang.bitor_trait()),
246 hir::BiShl => ("shl", lang.shl_trait()),
247 hir::BiShr => ("shr", lang.shr_trait()),
248 hir::BiLt => ("lt", lang.ord_trait()),
249 hir::BiLe => ("le", lang.ord_trait()),
250 hir::BiGe => ("ge", lang.ord_trait()),
251 hir::BiGt => ("gt", lang.ord_trait()),
252 hir::BiEq => ("eq", lang.eq_trait()),
253 hir::BiNe => ("ne", lang.eq_trait()),
254 hir::BiAnd | hir::BiOr => {
255 fcx.tcx().sess.span_bug(op.span, "&& and || are not overloadable")
260 fn lookup_op_method<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>,
261 expr: &'tcx hir::Expr,
263 other_tys: Vec<Ty<'tcx>>,
265 trait_did: Option<DefId>,
266 lhs_expr: &'a hir::Expr)
267 -> Result<Ty<'tcx>,()>
269 debug!("lookup_op_method(expr={:?}, lhs_ty={:?}, opname={:?}, trait_did={:?}, lhs_expr={:?})",
276 let method = match trait_did {
278 method::lookup_in_trait_adjusted(fcx,
293 let method_ty = method.ty;
295 // HACK(eddyb) Fully qualified path to work around a resolve bug.
296 let method_call = ::middle::ty::MethodCall::expr(expr.id);
297 fcx.inh.tables.borrow_mut().method_map.insert(method_call, method);
299 // extract return type for method; all late bound regions
300 // should have been instantiated by now
301 let ret_ty = method_ty.fn_ret();
302 Ok(fcx.tcx().no_late_bound_regions(&ret_ty).unwrap().unwrap())
310 // Binary operator categories. These categories summarize the behavior
311 // with respect to the builtin operationrs supported.
313 /// &&, || -- cannot be overridden
316 /// <<, >> -- when shifting a single integer, rhs can be any
317 /// integer type. For simd, types must match.
320 /// +, -, etc -- takes equal types, produces same type as input,
321 /// applicable to ints/floats/simd
324 /// &, |, ^ -- takes equal types, produces same type as input,
325 /// applicable to ints/floats/simd/bool
328 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
329 /// which produce the input type
334 fn from(op: hir::BinOp) -> BinOpCategory {
336 hir::BiShl | hir::BiShr =>
337 BinOpCategory::Shift,
349 BinOpCategory::Bitwise,
357 BinOpCategory::Comparison,
361 BinOpCategory::Shortcircuit,
366 /// Returns true if this is a built-in arithmetic operation (e.g. u32
367 /// + u32, i16x4 == i16x4) and false if these types would have to be
368 /// overloaded to be legal. There are two reasons that we distinguish
369 /// builtin operations from overloaded ones (vs trying to drive
370 /// everything uniformly through the trait system and intrinsics or
371 /// something like that):
373 /// 1. Builtin operations can trivially be evaluated in constants.
374 /// 2. For comparison operators applied to SIMD types the result is
375 /// not of type `bool`. For example, `i16x4==i16x4` yields a
376 /// type like `i16x4`. This means that the overloaded trait
377 /// `PartialEq` is not applicable.
379 /// Reason #2 is the killer. I tried for a while to always use
380 /// overloaded logic and just check the types in constants/trans after
381 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
382 fn is_builtin_binop<'tcx>(lhs: Ty<'tcx>,
387 match BinOpCategory::from(op) {
388 BinOpCategory::Shortcircuit => {
392 BinOpCategory::Shift => {
393 lhs.references_error() || rhs.references_error() ||
394 lhs.is_integral() && rhs.is_integral()
397 BinOpCategory::Math => {
398 lhs.references_error() || rhs.references_error() ||
399 lhs.is_integral() && rhs.is_integral() ||
400 lhs.is_floating_point() && rhs.is_floating_point()
403 BinOpCategory::Bitwise => {
404 lhs.references_error() || rhs.references_error() ||
405 lhs.is_integral() && rhs.is_integral() ||
406 lhs.is_floating_point() && rhs.is_floating_point() ||
407 lhs.is_bool() && rhs.is_bool()
410 BinOpCategory::Comparison => {
411 lhs.references_error() || rhs.references_error() ||
412 lhs.is_scalar() && rhs.is_scalar()