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,
24 use middle::ty::{self, Ty};
27 use syntax::parse::token;
29 /// Check a `a <op>= b`
30 pub fn check_binop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
31 expr: &'tcx ast::Expr,
33 lhs_expr: &'tcx ast::Expr,
34 rhs_expr: &'tcx ast::Expr)
36 let tcx = fcx.ccx.tcx;
38 check_expr_with_lvalue_pref(fcx, lhs_expr, PreferMutLvalue);
39 check_expr(fcx, rhs_expr);
41 let lhs_ty = structurally_resolved_type(fcx, lhs_expr.span, fcx.expr_ty(lhs_expr));
42 let rhs_ty = structurally_resolved_type(fcx, rhs_expr.span, fcx.expr_ty(rhs_expr));
44 if is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op) {
45 enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
46 fcx.write_nil(expr.id);
48 // error types are considered "builtin"
49 assert!(!ty::type_is_error(lhs_ty) || !ty::type_is_error(rhs_ty));
50 span_err!(tcx.sess, lhs_expr.span, E0368,
51 "binary assignment operation `{}=` cannot be applied to types `{}` and `{}`",
52 ast_util::binop_to_string(op.node),
55 fcx.write_error(expr.id);
59 if !ty::expr_is_lval(tcx, lhs_expr) {
60 span_err!(tcx.sess, lhs_expr.span, E0067, "illegal left-hand side expression");
63 fcx.require_expr_have_sized_type(lhs_expr, traits::AssignmentLhsSized);
66 /// Check a potentially overloaded binary operator.
67 pub fn check_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
68 expr: &'tcx ast::Expr,
70 lhs_expr: &'tcx ast::Expr,
71 rhs_expr: &'tcx ast::Expr)
73 let tcx = fcx.ccx.tcx;
75 debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
82 check_expr(fcx, lhs_expr);
83 let lhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
85 // Annoyingly, SIMD ops don't fit into the PartialEq/PartialOrd
86 // traits, because their return type is not bool. Perhaps this
87 // should change, but for now if LHS is SIMD we go down a
88 // different path that bypassess all traits.
89 if ty::type_is_simd(fcx.tcx(), lhs_ty) {
90 check_expr_coercable_to_type(fcx, rhs_expr, lhs_ty);
91 let rhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
92 let return_ty = enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
93 fcx.write_ty(expr.id, return_ty);
97 match BinOpCategory::from(op) {
98 BinOpCategory::Shortcircuit => {
99 // && and || are a simple case.
100 demand::suptype(fcx, lhs_expr.span, ty::mk_bool(tcx), lhs_ty);
101 check_expr_coercable_to_type(fcx, rhs_expr, ty::mk_bool(tcx));
102 fcx.write_ty(expr.id, ty::mk_bool(tcx));
105 // Otherwise, we always treat operators as if they are
106 // overloaded. This is the way to be most flexible w/r/t
107 // types that get inferred.
108 let (rhs_ty, return_ty) =
109 check_overloaded_binop(fcx, expr, lhs_expr, lhs_ty, rhs_expr, op);
111 // Supply type inference hints if relevant. Probably these
112 // hints should be enforced during select as part of the
113 // `consider_unification_despite_ambiguity` routine, but this
114 // more convenient for now.
116 // The basic idea is to help type inference by taking
117 // advantage of things we know about how the impls for
118 // scalar types are arranged. This is important in a
119 // scenario like `1_u32 << 2`, because it lets us quickly
120 // deduce that the result type should be `u32`, even
121 // though we don't know yet what type 2 has and hence
122 // can't pin this down to a specific impl.
123 let rhs_ty = fcx.resolve_type_vars_if_possible(rhs_ty);
125 !ty::type_is_ty_var(lhs_ty) &&
126 !ty::type_is_ty_var(rhs_ty) &&
127 is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op)
129 let builtin_return_ty =
130 enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
131 demand::suptype(fcx, expr.span, builtin_return_ty, return_ty);
134 fcx.write_ty(expr.id, return_ty);
139 fn enforce_builtin_binop_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
140 lhs_expr: &'tcx ast::Expr,
142 rhs_expr: &'tcx ast::Expr,
147 debug_assert!(is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op));
150 match BinOpCategory::from(op) {
151 BinOpCategory::Shortcircuit => {
152 demand::suptype(fcx, lhs_expr.span, ty::mk_bool(tcx), lhs_ty);
153 demand::suptype(fcx, rhs_expr.span, ty::mk_bool(tcx), rhs_ty);
157 BinOpCategory::Shift => {
158 // For integers, the shift amount can be of any integral
159 // type. For simd, the type must match exactly.
160 if ty::type_is_simd(tcx, lhs_ty) {
161 demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
164 // result type is same as LHS always
168 BinOpCategory::Math |
169 BinOpCategory::Bitwise => {
170 // both LHS and RHS and result will have the same type
171 demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
175 BinOpCategory::Comparison => {
176 // both LHS and RHS and result will have the same type
177 demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
179 // if this is simd, result is same as lhs, else bool
180 if ty::type_is_simd(tcx, lhs_ty) {
181 let unit_ty = ty::simd_type(tcx, lhs_ty);
182 debug!("enforce_builtin_binop_types: lhs_ty={:?} unit_ty={:?}",
185 if !ty::type_is_integral(unit_ty) {
188 &format!("binary comparison operation `{}` not supported \
189 for floating point SIMD vector `{}`",
190 ast_util::binop_to_string(op.node),
203 fn check_overloaded_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
204 expr: &'tcx ast::Expr,
205 lhs_expr: &'tcx ast::Expr,
207 rhs_expr: &'tcx ast::Expr,
209 -> (Ty<'tcx>, Ty<'tcx>)
211 debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?})",
215 let (name, trait_def_id) = name_and_trait_def_id(fcx, op);
217 // NB: As we have not yet type-checked the RHS, we don't have the
218 // type at hand. Make a variable to represent it. The whole reason
219 // for this indirection is so that, below, we can check the expr
220 // using this variable as the expected type, which sometimes lets
221 // us do better coercions than we would be able to do otherwise,
222 // particularly for things like `String + &String`.
223 let rhs_ty_var = fcx.infcx().next_ty_var();
225 let return_ty = match lookup_op_method(fcx, expr, lhs_ty, vec![rhs_ty_var],
226 token::intern(name), trait_def_id,
228 Ok(return_ty) => return_ty,
230 // error types are considered "builtin"
231 if !ty::type_is_error(lhs_ty) {
232 span_err!(fcx.tcx().sess, lhs_expr.span, E0369,
233 "binary operation `{}` cannot be applied to type `{}`",
234 ast_util::binop_to_string(op.node),
242 check_expr_coercable_to_type(fcx, rhs_expr, rhs_ty_var);
244 (rhs_ty_var, return_ty)
247 pub fn check_user_unop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
250 trait_did: Option<ast::DefId>,
252 operand_expr: &'tcx ast::Expr,
253 operand_ty: Ty<'tcx>,
257 assert!(ast_util::is_by_value_unop(op));
258 match lookup_op_method(fcx, ex, operand_ty, vec![],
259 token::intern(mname), trait_did,
263 fcx.type_error_message(ex.span, |actual| {
264 format!("cannot apply unary operator `{}` to type `{}`",
266 }, operand_ty, None);
272 fn name_and_trait_def_id(fcx: &FnCtxt, op: ast::BinOp) -> (&'static str, Option<ast::DefId>) {
273 let lang = &fcx.tcx().lang_items;
275 ast::BiAdd => ("add", lang.add_trait()),
276 ast::BiSub => ("sub", lang.sub_trait()),
277 ast::BiMul => ("mul", lang.mul_trait()),
278 ast::BiDiv => ("div", lang.div_trait()),
279 ast::BiRem => ("rem", lang.rem_trait()),
280 ast::BiBitXor => ("bitxor", lang.bitxor_trait()),
281 ast::BiBitAnd => ("bitand", lang.bitand_trait()),
282 ast::BiBitOr => ("bitor", lang.bitor_trait()),
283 ast::BiShl => ("shl", lang.shl_trait()),
284 ast::BiShr => ("shr", lang.shr_trait()),
285 ast::BiLt => ("lt", lang.ord_trait()),
286 ast::BiLe => ("le", lang.ord_trait()),
287 ast::BiGe => ("ge", lang.ord_trait()),
288 ast::BiGt => ("gt", lang.ord_trait()),
289 ast::BiEq => ("eq", lang.eq_trait()),
290 ast::BiNe => ("ne", lang.eq_trait()),
291 ast::BiAnd | ast::BiOr => {
292 fcx.tcx().sess.span_bug(op.span, "&& and || are not overloadable")
297 fn lookup_op_method<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>,
298 expr: &'tcx ast::Expr,
300 other_tys: Vec<Ty<'tcx>>,
302 trait_did: Option<ast::DefId>,
303 lhs_expr: &'a ast::Expr)
304 -> Result<Ty<'tcx>,()>
306 debug!("lookup_op_method(expr={:?}, lhs_ty={:?}, opname={:?}, trait_did={:?}, lhs_expr={:?})",
313 let method = match trait_did {
315 method::lookup_in_trait_adjusted(fcx,
330 let method_ty = method.ty;
332 // HACK(eddyb) Fully qualified path to work around a resolve bug.
333 let method_call = ::middle::ty::MethodCall::expr(expr.id);
334 fcx.inh.method_map.borrow_mut().insert(method_call, method);
336 // extract return type for method; all late bound regions
337 // should have been instantiated by now
338 let ret_ty = ty::ty_fn_ret(method_ty);
339 Ok(ty::no_late_bound_regions(fcx.tcx(), &ret_ty).unwrap().unwrap())
347 // Binary operator categories. These categories summarize the behavior
348 // with respect to the builtin operationrs supported.
350 /// &&, || -- cannot be overridden
353 /// <<, >> -- when shifting a single integer, rhs can be any
354 /// integer type. For simd, types must match.
357 /// +, -, etc -- takes equal types, produces same type as input,
358 /// applicable to ints/floats/simd
361 /// &, |, ^ -- takes equal types, produces same type as input,
362 /// applicable to ints/floats/simd/bool
365 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
366 /// which produce the input type
371 fn from(op: ast::BinOp) -> BinOpCategory {
373 ast::BiShl | ast::BiShr =>
374 BinOpCategory::Shift,
386 BinOpCategory::Bitwise,
394 BinOpCategory::Comparison,
398 BinOpCategory::Shortcircuit,
403 /// Returns true if this is a built-in arithmetic operation (e.g. u32
404 /// + u32, i16x4 == i16x4) and false if these types would have to be
405 /// overloaded to be legal. There are two reasons that we distinguish
406 /// builtin operations from overloaded ones (vs trying to drive
407 /// everything uniformly through the trait system and intrinsics or
408 /// something like that):
410 /// 1. Builtin operations can trivially be evaluated in constants.
411 /// 2. For comparison operators applied to SIMD types the result is
412 /// not of type `bool`. For example, `i16x4==i16x4` yields a
413 /// type like `i16x4`. This means that the overloaded trait
414 /// `PartialEq` is not applicable.
416 /// Reason #2 is the killer. I tried for a while to always use
417 /// overloaded logic and just check the types in constants/trans after
418 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
419 fn is_builtin_binop<'tcx>(cx: &ty::ctxt<'tcx>,
425 match BinOpCategory::from(op) {
426 BinOpCategory::Shortcircuit => {
430 BinOpCategory::Shift => {
431 ty::type_is_error(lhs) || ty::type_is_error(rhs) ||
432 ty::type_is_integral(lhs) && ty::type_is_integral(rhs) ||
433 ty::type_is_simd(cx, lhs) && ty::type_is_simd(cx, rhs)
436 BinOpCategory::Math => {
437 ty::type_is_error(lhs) || ty::type_is_error(rhs) ||
438 ty::type_is_integral(lhs) && ty::type_is_integral(rhs) ||
439 ty::type_is_floating_point(lhs) && ty::type_is_floating_point(rhs) ||
440 ty::type_is_simd(cx, lhs) && ty::type_is_simd(cx, rhs)
443 BinOpCategory::Bitwise => {
444 ty::type_is_error(lhs) || ty::type_is_error(rhs) ||
445 ty::type_is_integral(lhs) && ty::type_is_integral(rhs) ||
446 ty::type_is_floating_point(lhs) && ty::type_is_floating_point(rhs) ||
447 ty::type_is_simd(cx, lhs) && ty::type_is_simd(cx, rhs) ||
448 ty::type_is_bool(lhs) && ty::type_is_bool(rhs)
451 BinOpCategory::Comparison => {
452 ty::type_is_error(lhs) || ty::type_is_error(rhs) ||
453 ty::type_is_scalar(lhs) && ty::type_is_scalar(rhs) ||
454 ty::type_is_simd(cx, lhs) && ty::type_is_simd(cx, rhs)