]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/op.rs
Auto merge of #28197 - petrochenkov:borrow, r=alexcrichton
[rust.git] / src / librustc_typeck / check / op.rs
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.
4 //
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.
10
11 //! Code related to processing overloaded binary and unary operators.
12
13 use super::{
14     check_expr,
15     check_expr_coercable_to_type,
16     check_expr_with_lvalue_pref,
17     demand,
18     method,
19     FnCtxt,
20     structurally_resolved_type,
21 };
22 use middle::def_id::DefId;
23 use middle::traits;
24 use middle::ty::{Ty, HasTypeFlags, PreferMutLvalue};
25 use syntax::ast;
26 use syntax::parse::token;
27 use rustc_front::hir;
28 use rustc_front::util as hir_util;
29
30 /// Check a `a <op>= b`
31 pub fn check_binop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
32                                    expr: &'tcx hir::Expr,
33                                    op: hir::BinOp,
34                                    lhs_expr: &'tcx hir::Expr,
35                                    rhs_expr: &'tcx hir::Expr)
36 {
37     let tcx = fcx.ccx.tcx;
38
39     check_expr_with_lvalue_pref(fcx, lhs_expr, PreferMutLvalue);
40     check_expr(fcx, rhs_expr);
41
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));
44
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);
48     } else {
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                   hir_util::binop_to_string(op.node),
54                   lhs_ty,
55                   rhs_ty);
56         fcx.write_error(expr.id);
57     }
58
59     let tcx = fcx.tcx();
60     if !tcx.expr_is_lval(lhs_expr) {
61         span_err!(tcx.sess, lhs_expr.span, E0067, "invalid left-hand side expression");
62     }
63
64     fcx.require_expr_have_sized_type(lhs_expr, traits::AssignmentLhsSized);
65 }
66
67 /// Check a potentially overloaded binary operator.
68 pub fn check_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
69                              expr: &'tcx hir::Expr,
70                              op: hir::BinOp,
71                              lhs_expr: &'tcx hir::Expr,
72                              rhs_expr: &'tcx hir::Expr)
73 {
74     let tcx = fcx.ccx.tcx;
75
76     debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
77            expr.id,
78            expr,
79            op,
80            lhs_expr,
81            rhs_expr);
82
83     check_expr(fcx, lhs_expr);
84     let lhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
85
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());
92         }
93         _ => {
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);
99
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.
104             //
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);
113             if
114                 !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() &&
115                 is_builtin_binop(lhs_ty, rhs_ty, op)
116             {
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);
120             }
121
122             fcx.write_ty(expr.id, return_ty);
123         }
124     }
125 }
126
127 fn enforce_builtin_binop_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
128                                          lhs_expr: &'tcx hir::Expr,
129                                          lhs_ty: Ty<'tcx>,
130                                          rhs_expr: &'tcx hir::Expr,
131                                          rhs_ty: Ty<'tcx>,
132                                          op: hir::BinOp)
133                                          -> Ty<'tcx>
134 {
135     debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
136
137     let tcx = fcx.tcx();
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);
142             tcx.mk_bool()
143         }
144
145         BinOpCategory::Shift => {
146             // result type is same as LHS always
147             lhs_ty
148         }
149
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);
154             lhs_ty
155         }
156
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);
160             tcx.mk_bool()
161         }
162     }
163 }
164
165 fn check_overloaded_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
166                                     expr: &'tcx hir::Expr,
167                                     lhs_expr: &'tcx hir::Expr,
168                                     lhs_ty: Ty<'tcx>,
169                                     rhs_expr: &'tcx hir::Expr,
170                                     op: hir::BinOp)
171                                     -> (Ty<'tcx>, Ty<'tcx>)
172 {
173     debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?})",
174            expr.id,
175            lhs_ty);
176
177     let (name, trait_def_id) = name_and_trait_def_id(fcx, op);
178
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();
186
187     let return_ty = match lookup_op_method(fcx, expr, lhs_ty, vec![rhs_ty_var],
188                                            token::intern(name), trait_def_id,
189                                            lhs_expr) {
190         Ok(return_ty) => return_ty,
191         Err(()) => {
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                           hir_util::binop_to_string(op.node),
197                           lhs_ty);
198             }
199             fcx.tcx().types.err
200         }
201     };
202
203     // see `NB` above
204     check_expr_coercable_to_type(fcx, rhs_expr, rhs_ty_var);
205
206     (rhs_ty_var, return_ty)
207 }
208
209 pub fn check_user_unop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
210                                  op_str: &str,
211                                  mname: &str,
212                                  trait_did: Option<DefId>,
213                                  ex: &'tcx hir::Expr,
214                                  operand_expr: &'tcx hir::Expr,
215                                  operand_ty: Ty<'tcx>,
216                                  op: hir::UnOp)
217                                  -> Ty<'tcx>
218 {
219     assert!(hir_util::is_by_value_unop(op));
220     match lookup_op_method(fcx, ex, operand_ty, vec![],
221                            token::intern(mname), trait_did,
222                            operand_expr) {
223         Ok(t) => t,
224         Err(()) => {
225             fcx.type_error_message(ex.span, |actual| {
226                 format!("cannot apply unary operator `{}` to type `{}`",
227                         op_str, actual)
228             }, operand_ty, None);
229             fcx.tcx().types.err
230         }
231     }
232 }
233
234 fn name_and_trait_def_id(fcx: &FnCtxt, op: hir::BinOp) -> (&'static str, Option<DefId>) {
235     let lang = &fcx.tcx().lang_items;
236     match op.node {
237         hir::BiAdd => ("add", lang.add_trait()),
238         hir::BiSub => ("sub", lang.sub_trait()),
239         hir::BiMul => ("mul", lang.mul_trait()),
240         hir::BiDiv => ("div", lang.div_trait()),
241         hir::BiRem => ("rem", lang.rem_trait()),
242         hir::BiBitXor => ("bitxor", lang.bitxor_trait()),
243         hir::BiBitAnd => ("bitand", lang.bitand_trait()),
244         hir::BiBitOr => ("bitor", lang.bitor_trait()),
245         hir::BiShl => ("shl", lang.shl_trait()),
246         hir::BiShr => ("shr", lang.shr_trait()),
247         hir::BiLt => ("lt", lang.ord_trait()),
248         hir::BiLe => ("le", lang.ord_trait()),
249         hir::BiGe => ("ge", lang.ord_trait()),
250         hir::BiGt => ("gt", lang.ord_trait()),
251         hir::BiEq => ("eq", lang.eq_trait()),
252         hir::BiNe => ("ne", lang.eq_trait()),
253         hir::BiAnd | hir::BiOr => {
254             fcx.tcx().sess.span_bug(op.span, "&& and || are not overloadable")
255         }
256     }
257 }
258
259 fn lookup_op_method<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>,
260                               expr: &'tcx hir::Expr,
261                               lhs_ty: Ty<'tcx>,
262                               other_tys: Vec<Ty<'tcx>>,
263                               opname: ast::Name,
264                               trait_did: Option<DefId>,
265                               lhs_expr: &'a hir::Expr)
266                               -> Result<Ty<'tcx>,()>
267 {
268     debug!("lookup_op_method(expr={:?}, lhs_ty={:?}, opname={:?}, trait_did={:?}, lhs_expr={:?})",
269            expr,
270            lhs_ty,
271            opname,
272            trait_did,
273            lhs_expr);
274
275     let method = match trait_did {
276         Some(trait_did) => {
277             method::lookup_in_trait_adjusted(fcx,
278                                              expr.span,
279                                              Some(lhs_expr),
280                                              opname,
281                                              trait_did,
282                                              0,
283                                              false,
284                                              lhs_ty,
285                                              Some(other_tys))
286         }
287         None => None
288     };
289
290     match method {
291         Some(method) => {
292             let method_ty = method.ty;
293
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);
297
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())
302         }
303         None => {
304             Err(())
305         }
306     }
307 }
308
309 // Binary operator categories. These categories summarize the behavior
310 // with respect to the builtin operationrs supported.
311 enum BinOpCategory {
312     /// &&, || -- cannot be overridden
313     Shortcircuit,
314
315     /// <<, >> -- when shifting a single integer, rhs can be any
316     /// integer type. For simd, types must match.
317     Shift,
318
319     /// +, -, etc -- takes equal types, produces same type as input,
320     /// applicable to ints/floats/simd
321     Math,
322
323     /// &, |, ^ -- takes equal types, produces same type as input,
324     /// applicable to ints/floats/simd/bool
325     Bitwise,
326
327     /// ==, !=, etc -- takes equal types, produces bools, except for simd,
328     /// which produce the input type
329     Comparison,
330 }
331
332 impl BinOpCategory {
333     fn from(op: hir::BinOp) -> BinOpCategory {
334         match op.node {
335             hir::BiShl | hir::BiShr =>
336                 BinOpCategory::Shift,
337
338             hir::BiAdd |
339             hir::BiSub |
340             hir::BiMul |
341             hir::BiDiv |
342             hir::BiRem =>
343                 BinOpCategory::Math,
344
345             hir::BiBitXor |
346             hir::BiBitAnd |
347             hir::BiBitOr =>
348                 BinOpCategory::Bitwise,
349
350             hir::BiEq |
351             hir::BiNe |
352             hir::BiLt |
353             hir::BiLe |
354             hir::BiGe |
355             hir::BiGt =>
356                 BinOpCategory::Comparison,
357
358             hir::BiAnd |
359             hir::BiOr =>
360                 BinOpCategory::Shortcircuit,
361         }
362     }
363 }
364
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):
371 ///
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.
377 ///
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>,
382                           rhs: Ty<'tcx>,
383                           op: hir::BinOp)
384                           -> bool
385 {
386     match BinOpCategory::from(op) {
387         BinOpCategory::Shortcircuit => {
388             true
389         }
390
391         BinOpCategory::Shift => {
392             lhs.references_error() || rhs.references_error() ||
393                 lhs.is_integral() && rhs.is_integral()
394         }
395
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()
400         }
401
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()
407         }
408
409         BinOpCategory::Comparison => {
410             lhs.references_error() || rhs.references_error() ||
411                 lhs.is_scalar() && rhs.is_scalar()
412         }
413     }
414 }