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};
28 use syntax::parse::token;
30 /// Check a `a <op>= b`
31 pub fn check_binop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
32 expr: &'tcx ast::Expr,
34 lhs_expr: &'tcx ast::Expr,
35 rhs_expr: &'tcx ast::Expr)
37 let tcx = fcx.ccx.tcx;
39 check_expr_with_lvalue_pref(fcx, lhs_expr, PreferMutLvalue);
40 check_expr(fcx, rhs_expr);
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));
45 if is_builtin_binop(lhs_ty, rhs_ty, op) {
46 enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
47 fcx.write_nil(expr.id);
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 ast_util::binop_to_string(op.node),
56 fcx.write_error(expr.id);
60 if !tcx.expr_is_lval(lhs_expr) {
61 span_err!(tcx.sess, lhs_expr.span, E0067, "invalid left-hand side expression");
64 fcx.require_expr_have_sized_type(lhs_expr, traits::AssignmentLhsSized);
67 /// Check a potentially overloaded binary operator.
68 pub fn check_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
69 expr: &'tcx ast::Expr,
71 lhs_expr: &'tcx ast::Expr,
72 rhs_expr: &'tcx ast::Expr)
74 let tcx = fcx.ccx.tcx;
76 debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
83 check_expr(fcx, lhs_expr);
84 let lhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
86 match BinOpCategory::from(op) {
87 BinOpCategory::Shortcircuit => {
88 // && and || are a simple case.
89 demand::suptype(fcx, lhs_expr.span, tcx.mk_bool(), lhs_ty);
90 check_expr_coercable_to_type(fcx, rhs_expr, tcx.mk_bool());
91 fcx.write_ty(expr.id, tcx.mk_bool());
94 // Otherwise, we always treat operators as if they are
95 // overloaded. This is the way to be most flexible w/r/t
96 // types that get inferred.
97 let (rhs_ty, return_ty) =
98 check_overloaded_binop(fcx, expr, lhs_expr, lhs_ty, rhs_expr, op);
100 // Supply type inference hints if relevant. Probably these
101 // hints should be enforced during select as part of the
102 // `consider_unification_despite_ambiguity` routine, but this
103 // more convenient for now.
105 // The basic idea is to help type inference by taking
106 // advantage of things we know about how the impls for
107 // scalar types are arranged. This is important in a
108 // scenario like `1_u32 << 2`, because it lets us quickly
109 // deduce that the result type should be `u32`, even
110 // though we don't know yet what type 2 has and hence
111 // can't pin this down to a specific impl.
112 let rhs_ty = fcx.resolve_type_vars_if_possible(rhs_ty);
114 !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() &&
115 is_builtin_binop(lhs_ty, rhs_ty, op)
117 let builtin_return_ty =
118 enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
119 demand::suptype(fcx, expr.span, builtin_return_ty, return_ty);
122 fcx.write_ty(expr.id, return_ty);
127 fn enforce_builtin_binop_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
128 lhs_expr: &'tcx ast::Expr,
130 rhs_expr: &'tcx ast::Expr,
135 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
138 match BinOpCategory::from(op) {
139 BinOpCategory::Shortcircuit => {
140 demand::suptype(fcx, lhs_expr.span, tcx.mk_bool(), lhs_ty);
141 demand::suptype(fcx, rhs_expr.span, tcx.mk_bool(), rhs_ty);
145 BinOpCategory::Shift => {
146 // result type is same as LHS always
150 BinOpCategory::Math |
151 BinOpCategory::Bitwise => {
152 // both LHS and RHS and result will have the same type
153 demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
157 BinOpCategory::Comparison => {
158 // both LHS and RHS and result will have the same type
159 demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
165 fn check_overloaded_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
166 expr: &'tcx ast::Expr,
167 lhs_expr: &'tcx ast::Expr,
169 rhs_expr: &'tcx ast::Expr,
171 -> (Ty<'tcx>, Ty<'tcx>)
173 debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?})",
177 let (name, trait_def_id) = name_and_trait_def_id(fcx, op);
179 // NB: As we have not yet type-checked the RHS, we don't have the
180 // type at hand. Make a variable to represent it. The whole reason
181 // for this indirection is so that, below, we can check the expr
182 // using this variable as the expected type, which sometimes lets
183 // us do better coercions than we would be able to do otherwise,
184 // particularly for things like `String + &String`.
185 let rhs_ty_var = fcx.infcx().next_ty_var();
187 let return_ty = match lookup_op_method(fcx, expr, lhs_ty, vec![rhs_ty_var],
188 token::intern(name), trait_def_id,
190 Ok(return_ty) => return_ty,
192 // error types are considered "builtin"
193 if !lhs_ty.references_error() {
194 span_err!(fcx.tcx().sess, lhs_expr.span, E0369,
195 "binary operation `{}` cannot be applied to type `{}`",
196 ast_util::binop_to_string(op.node),
204 check_expr_coercable_to_type(fcx, rhs_expr, rhs_ty_var);
206 (rhs_ty_var, return_ty)
209 pub fn check_user_unop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
212 trait_did: Option<DefId>,
214 operand_expr: &'tcx ast::Expr,
215 operand_ty: Ty<'tcx>,
219 assert!(ast_util::is_by_value_unop(op));
220 match lookup_op_method(fcx, ex, operand_ty, vec![],
221 token::intern(mname), trait_did,
225 fcx.type_error_message(ex.span, |actual| {
226 format!("cannot apply unary operator `{}` to type `{}`",
228 }, operand_ty, None);
234 fn name_and_trait_def_id(fcx: &FnCtxt, op: ast::BinOp) -> (&'static str, Option<DefId>) {
235 let lang = &fcx.tcx().lang_items;
237 ast::BiAdd => ("add", lang.add_trait()),
238 ast::BiSub => ("sub", lang.sub_trait()),
239 ast::BiMul => ("mul", lang.mul_trait()),
240 ast::BiDiv => ("div", lang.div_trait()),
241 ast::BiRem => ("rem", lang.rem_trait()),
242 ast::BiBitXor => ("bitxor", lang.bitxor_trait()),
243 ast::BiBitAnd => ("bitand", lang.bitand_trait()),
244 ast::BiBitOr => ("bitor", lang.bitor_trait()),
245 ast::BiShl => ("shl", lang.shl_trait()),
246 ast::BiShr => ("shr", lang.shr_trait()),
247 ast::BiLt => ("lt", lang.ord_trait()),
248 ast::BiLe => ("le", lang.ord_trait()),
249 ast::BiGe => ("ge", lang.ord_trait()),
250 ast::BiGt => ("gt", lang.ord_trait()),
251 ast::BiEq => ("eq", lang.eq_trait()),
252 ast::BiNe => ("ne", lang.eq_trait()),
253 ast::BiAnd | ast::BiOr => {
254 fcx.tcx().sess.span_bug(op.span, "&& and || are not overloadable")
259 fn lookup_op_method<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>,
260 expr: &'tcx ast::Expr,
262 other_tys: Vec<Ty<'tcx>>,
264 trait_did: Option<DefId>,
265 lhs_expr: &'a ast::Expr)
266 -> Result<Ty<'tcx>,()>
268 debug!("lookup_op_method(expr={:?}, lhs_ty={:?}, opname={:?}, trait_did={:?}, lhs_expr={:?})",
275 let method = match trait_did {
277 method::lookup_in_trait_adjusted(fcx,
292 let method_ty = method.ty;
294 // HACK(eddyb) Fully qualified path to work around a resolve bug.
295 let method_call = ::middle::ty::MethodCall::expr(expr.id);
296 fcx.inh.tables.borrow_mut().method_map.insert(method_call, method);
298 // extract return type for method; all late bound regions
299 // should have been instantiated by now
300 let ret_ty = method_ty.fn_ret();
301 Ok(fcx.tcx().no_late_bound_regions(&ret_ty).unwrap().unwrap())
309 // Binary operator categories. These categories summarize the behavior
310 // with respect to the builtin operationrs supported.
312 /// &&, || -- cannot be overridden
315 /// <<, >> -- when shifting a single integer, rhs can be any
316 /// integer type. For simd, types must match.
319 /// +, -, etc -- takes equal types, produces same type as input,
320 /// applicable to ints/floats/simd
323 /// &, |, ^ -- takes equal types, produces same type as input,
324 /// applicable to ints/floats/simd/bool
327 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
328 /// which produce the input type
333 fn from(op: ast::BinOp) -> BinOpCategory {
335 ast::BiShl | ast::BiShr =>
336 BinOpCategory::Shift,
348 BinOpCategory::Bitwise,
356 BinOpCategory::Comparison,
360 BinOpCategory::Shortcircuit,
365 /// Returns true if this is a built-in arithmetic operation (e.g. u32
366 /// + u32, i16x4 == i16x4) and false if these types would have to be
367 /// overloaded to be legal. There are two reasons that we distinguish
368 /// builtin operations from overloaded ones (vs trying to drive
369 /// everything uniformly through the trait system and intrinsics or
370 /// something like that):
372 /// 1. Builtin operations can trivially be evaluated in constants.
373 /// 2. For comparison operators applied to SIMD types the result is
374 /// not of type `bool`. For example, `i16x4==i16x4` yields a
375 /// type like `i16x4`. This means that the overloaded trait
376 /// `PartialEq` is not applicable.
378 /// Reason #2 is the killer. I tried for a while to always use
379 /// overloaded logic and just check the types in constants/trans after
380 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
381 fn is_builtin_binop<'tcx>(lhs: Ty<'tcx>,
386 match BinOpCategory::from(op) {
387 BinOpCategory::Shortcircuit => {
391 BinOpCategory::Shift => {
392 lhs.references_error() || rhs.references_error() ||
393 lhs.is_integral() && rhs.is_integral()
396 BinOpCategory::Math => {
397 lhs.references_error() || rhs.references_error() ||
398 lhs.is_integral() && rhs.is_integral() ||
399 lhs.is_floating_point() && rhs.is_floating_point()
402 BinOpCategory::Bitwise => {
403 lhs.references_error() || rhs.references_error() ||
404 lhs.is_integral() && rhs.is_integral() ||
405 lhs.is_floating_point() && rhs.is_floating_point() ||
406 lhs.is_bool() && rhs.is_bool()
409 BinOpCategory::Comparison => {
410 lhs.references_error() || rhs.references_error() ||
411 lhs.is_scalar() && rhs.is_scalar()