]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/op.rs
Auto merge of #26521 - oli-obk:android-x86-libclibc, 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     PreferMutLvalue,
21     structurally_resolved_type,
22 };
23 use middle::traits;
24 use middle::ty::{self, Ty};
25 use syntax::ast;
26 use syntax::ast_util;
27 use syntax::parse::token;
28
29 /// Check a `a <op>= b`
30 pub fn check_binop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
31                                    expr: &'tcx ast::Expr,
32                                    op: ast::BinOp,
33                                    lhs_expr: &'tcx ast::Expr,
34                                    rhs_expr: &'tcx ast::Expr)
35 {
36     let tcx = fcx.ccx.tcx;
37
38     check_expr_with_lvalue_pref(fcx, lhs_expr, PreferMutLvalue);
39     check_expr(fcx, rhs_expr);
40
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));
43
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);
47     } else {
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),
53                   lhs_ty,
54                   rhs_ty);
55         fcx.write_error(expr.id);
56     }
57
58     let tcx = fcx.tcx();
59     if !ty::expr_is_lval(tcx, lhs_expr) {
60         span_err!(tcx.sess, lhs_expr.span, E0067, "illegal left-hand side expression");
61     }
62
63     fcx.require_expr_have_sized_type(lhs_expr, traits::AssignmentLhsSized);
64 }
65
66 /// Check a potentially overloaded binary operator.
67 pub fn check_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
68                              expr: &'tcx ast::Expr,
69                              op: ast::BinOp,
70                              lhs_expr: &'tcx ast::Expr,
71                              rhs_expr: &'tcx ast::Expr)
72 {
73     let tcx = fcx.ccx.tcx;
74
75     debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
76            expr.id,
77            expr,
78            op,
79            lhs_expr,
80            rhs_expr);
81
82     check_expr(fcx, lhs_expr);
83     let lhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
84
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);
94         return;
95     }
96
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));
103         }
104         _ => {
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);
110
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.
115             //
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);
124             if
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)
128             {
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);
132             }
133
134             fcx.write_ty(expr.id, return_ty);
135         }
136     }
137 }
138
139 fn enforce_builtin_binop_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
140                                          lhs_expr: &'tcx ast::Expr,
141                                          lhs_ty: Ty<'tcx>,
142                                          rhs_expr: &'tcx ast::Expr,
143                                          rhs_ty: Ty<'tcx>,
144                                          op: ast::BinOp)
145                                          -> Ty<'tcx>
146 {
147     debug_assert!(is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op));
148
149     let tcx = fcx.tcx();
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);
154             ty::mk_bool(tcx)
155         }
156
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);
162             }
163
164             // result type is same as LHS always
165             lhs_ty
166         }
167
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);
172             lhs_ty
173         }
174
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);
178
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={:?}",
183                        lhs_ty,
184                        unit_ty);
185                 if !ty::type_is_integral(unit_ty) {
186                     tcx.sess.span_err(
187                         lhs_expr.span,
188                         &format!("binary comparison operation `{}` not supported \
189                                   for floating point SIMD vector `{}`",
190                                  ast_util::binop_to_string(op.node),
191                                  lhs_ty));
192                     tcx.types.err
193                 } else {
194                     lhs_ty
195                 }
196             } else {
197                 ty::mk_bool(tcx)
198             }
199         }
200     }
201 }
202
203 fn check_overloaded_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
204                                     expr: &'tcx ast::Expr,
205                                     lhs_expr: &'tcx ast::Expr,
206                                     lhs_ty: Ty<'tcx>,
207                                     rhs_expr: &'tcx ast::Expr,
208                                     op: ast::BinOp)
209                                     -> (Ty<'tcx>, Ty<'tcx>)
210 {
211     debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?})",
212            expr.id,
213            lhs_ty);
214
215     let (name, trait_def_id) = name_and_trait_def_id(fcx, op);
216
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();
224
225     let return_ty = match lookup_op_method(fcx, expr, lhs_ty, vec![rhs_ty_var],
226                                            token::intern(name), trait_def_id,
227                                            lhs_expr) {
228         Ok(return_ty) => return_ty,
229         Err(()) => {
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),
235                           lhs_ty);
236             }
237             fcx.tcx().types.err
238         }
239     };
240
241     // see `NB` above
242     check_expr_coercable_to_type(fcx, rhs_expr, rhs_ty_var);
243
244     (rhs_ty_var, return_ty)
245 }
246
247 pub fn check_user_unop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
248                                  op_str: &str,
249                                  mname: &str,
250                                  trait_did: Option<ast::DefId>,
251                                  ex: &'tcx ast::Expr,
252                                  operand_expr: &'tcx ast::Expr,
253                                  operand_ty: Ty<'tcx>,
254                                  op: ast::UnOp)
255                                  -> Ty<'tcx>
256 {
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,
260                            operand_expr) {
261         Ok(t) => t,
262         Err(()) => {
263             fcx.type_error_message(ex.span, |actual| {
264                 format!("cannot apply unary operator `{}` to type `{}`",
265                         op_str, actual)
266             }, operand_ty, None);
267             fcx.tcx().types.err
268         }
269     }
270 }
271
272 fn name_and_trait_def_id(fcx: &FnCtxt, op: ast::BinOp) -> (&'static str, Option<ast::DefId>) {
273     let lang = &fcx.tcx().lang_items;
274     match op.node {
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")
293         }
294     }
295 }
296
297 fn lookup_op_method<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>,
298                               expr: &'tcx ast::Expr,
299                               lhs_ty: Ty<'tcx>,
300                               other_tys: Vec<Ty<'tcx>>,
301                               opname: ast::Name,
302                               trait_did: Option<ast::DefId>,
303                               lhs_expr: &'a ast::Expr)
304                               -> Result<Ty<'tcx>,()>
305 {
306     debug!("lookup_op_method(expr={:?}, lhs_ty={:?}, opname={:?}, trait_did={:?}, lhs_expr={:?})",
307            expr,
308            lhs_ty,
309            opname,
310            trait_did,
311            lhs_expr);
312
313     let method = match trait_did {
314         Some(trait_did) => {
315             method::lookup_in_trait_adjusted(fcx,
316                                              expr.span,
317                                              Some(lhs_expr),
318                                              opname,
319                                              trait_did,
320                                              0,
321                                              false,
322                                              lhs_ty,
323                                              Some(other_tys))
324         }
325         None => None
326     };
327
328     match method {
329         Some(method) => {
330             let method_ty = method.ty;
331
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);
335
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())
340         }
341         None => {
342             Err(())
343         }
344     }
345 }
346
347 // Binary operator categories. These categories summarize the behavior
348 // with respect to the builtin operationrs supported.
349 enum BinOpCategory {
350     /// &&, || -- cannot be overridden
351     Shortcircuit,
352
353     /// <<, >> -- when shifting a single integer, rhs can be any
354     /// integer type. For simd, types must match.
355     Shift,
356
357     /// +, -, etc -- takes equal types, produces same type as input,
358     /// applicable to ints/floats/simd
359     Math,
360
361     /// &, |, ^ -- takes equal types, produces same type as input,
362     /// applicable to ints/floats/simd/bool
363     Bitwise,
364
365     /// ==, !=, etc -- takes equal types, produces bools, except for simd,
366     /// which produce the input type
367     Comparison,
368 }
369
370 impl BinOpCategory {
371     fn from(op: ast::BinOp) -> BinOpCategory {
372         match op.node {
373             ast::BiShl | ast::BiShr =>
374                 BinOpCategory::Shift,
375
376             ast::BiAdd |
377             ast::BiSub |
378             ast::BiMul |
379             ast::BiDiv |
380             ast::BiRem =>
381                 BinOpCategory::Math,
382
383             ast::BiBitXor |
384             ast::BiBitAnd |
385             ast::BiBitOr =>
386                 BinOpCategory::Bitwise,
387
388             ast::BiEq |
389             ast::BiNe |
390             ast::BiLt |
391             ast::BiLe |
392             ast::BiGe |
393             ast::BiGt =>
394                 BinOpCategory::Comparison,
395
396             ast::BiAnd |
397             ast::BiOr =>
398                 BinOpCategory::Shortcircuit,
399         }
400     }
401 }
402
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):
409 ///
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.
415 ///
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>,
420                           lhs: Ty<'tcx>,
421                           rhs: Ty<'tcx>,
422                           op: ast::BinOp)
423                           -> bool
424 {
425     match BinOpCategory::from(op) {
426         BinOpCategory::Shortcircuit => {
427             true
428         }
429
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)
434         }
435
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)
441         }
442
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)
449         }
450
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)
455         }
456     }
457 }
458