]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/op.rs
Auto merge of #43710 - zackmdavis:field_init_shorthand_power_slam, r=Mark-Simulacrum
[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::FnCtxt;
14 use super::method::MethodCallee;
15 use rustc::ty::{self, Ty, TypeFoldable, PreferMutLvalue, TypeVariants};
16 use rustc::ty::TypeVariants::{TyStr, TyRef};
17 use rustc::ty::adjustment::{Adjustment, Adjust, AutoBorrow};
18 use rustc::infer::type_variable::TypeVariableOrigin;
19 use errors;
20 use syntax_pos::Span;
21 use syntax::symbol::Symbol;
22 use rustc::hir;
23
24 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
25     /// Check a `a <op>= b`
26     pub fn check_binop_assign(&self,
27                               expr: &'gcx hir::Expr,
28                               op: hir::BinOp,
29                               lhs_expr: &'gcx hir::Expr,
30                               rhs_expr: &'gcx hir::Expr) -> Ty<'tcx>
31     {
32         let lhs_ty = self.check_expr_with_lvalue_pref(lhs_expr, PreferMutLvalue);
33
34         let lhs_ty = self.resolve_type_vars_with_obligations(lhs_ty);
35         let (rhs_ty, return_ty) =
36             self.check_overloaded_binop(expr, lhs_expr, lhs_ty, rhs_expr, op, IsAssign::Yes);
37         let rhs_ty = self.resolve_type_vars_with_obligations(rhs_ty);
38
39         let ty = if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var()
40                     && is_builtin_binop(lhs_ty, rhs_ty, op) {
41             self.enforce_builtin_binop_types(lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
42             self.tcx.mk_nil()
43         } else {
44             return_ty
45         };
46
47         let tcx = self.tcx;
48         if !tcx.expr_is_lval(lhs_expr) {
49             struct_span_err!(
50                 tcx.sess, lhs_expr.span,
51                 E0067, "invalid left-hand side expression")
52             .span_label(
53                 lhs_expr.span,
54                 "invalid expression for left-hand side")
55             .emit();
56         }
57         ty
58     }
59
60     /// Check a potentially overloaded binary operator.
61     pub fn check_binop(&self,
62                        expr: &'gcx hir::Expr,
63                        op: hir::BinOp,
64                        lhs_expr: &'gcx hir::Expr,
65                        rhs_expr: &'gcx hir::Expr) -> Ty<'tcx>
66     {
67         let tcx = self.tcx;
68
69         debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
70                expr.id,
71                expr,
72                op,
73                lhs_expr,
74                rhs_expr);
75
76         let lhs_ty = self.check_expr(lhs_expr);
77         let lhs_ty = self.resolve_type_vars_with_obligations(lhs_ty);
78
79         match BinOpCategory::from(op) {
80             BinOpCategory::Shortcircuit => {
81                 // && and || are a simple case.
82                 let lhs_diverges = self.diverges.get();
83                 self.demand_suptype(lhs_expr.span, tcx.mk_bool(), lhs_ty);
84                 self.check_expr_coercable_to_type(rhs_expr, tcx.mk_bool());
85
86                 // Depending on the LHS' value, the RHS can never execute.
87                 self.diverges.set(lhs_diverges);
88
89                 tcx.mk_bool()
90             }
91             _ => {
92                 // Otherwise, we always treat operators as if they are
93                 // overloaded. This is the way to be most flexible w/r/t
94                 // types that get inferred.
95                 let (rhs_ty, return_ty) =
96                     self.check_overloaded_binop(expr, lhs_expr, lhs_ty,
97                                                 rhs_expr, op, IsAssign::No);
98
99                 // Supply type inference hints if relevant. Probably these
100                 // hints should be enforced during select as part of the
101                 // `consider_unification_despite_ambiguity` routine, but this
102                 // more convenient for now.
103                 //
104                 // The basic idea is to help type inference by taking
105                 // advantage of things we know about how the impls for
106                 // scalar types are arranged. This is important in a
107                 // scenario like `1_u32 << 2`, because it lets us quickly
108                 // deduce that the result type should be `u32`, even
109                 // though we don't know yet what type 2 has and hence
110                 // can't pin this down to a specific impl.
111                 let rhs_ty = self.resolve_type_vars_with_obligations(rhs_ty);
112                 if
113                     !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() &&
114                     is_builtin_binop(lhs_ty, rhs_ty, op)
115                 {
116                     let builtin_return_ty =
117                         self.enforce_builtin_binop_types(lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
118                     self.demand_suptype(expr.span, builtin_return_ty, return_ty);
119                 }
120
121                 return_ty
122             }
123         }
124     }
125
126     fn enforce_builtin_binop_types(&self,
127                                    lhs_expr: &'gcx hir::Expr,
128                                    lhs_ty: Ty<'tcx>,
129                                    rhs_expr: &'gcx hir::Expr,
130                                    rhs_ty: Ty<'tcx>,
131                                    op: hir::BinOp)
132                                    -> Ty<'tcx>
133     {
134         debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
135
136         let tcx = self.tcx;
137         match BinOpCategory::from(op) {
138             BinOpCategory::Shortcircuit => {
139                 self.demand_suptype(lhs_expr.span, tcx.mk_bool(), lhs_ty);
140                 self.demand_suptype(rhs_expr.span, tcx.mk_bool(), rhs_ty);
141                 tcx.mk_bool()
142             }
143
144             BinOpCategory::Shift => {
145                 // result type is same as LHS always
146                 lhs_ty
147             }
148
149             BinOpCategory::Math |
150             BinOpCategory::Bitwise => {
151                 // both LHS and RHS and result will have the same type
152                 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
153                 lhs_ty
154             }
155
156             BinOpCategory::Comparison => {
157                 // both LHS and RHS and result will have the same type
158                 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
159                 tcx.mk_bool()
160             }
161         }
162     }
163
164     fn check_overloaded_binop(&self,
165                               expr: &'gcx hir::Expr,
166                               lhs_expr: &'gcx hir::Expr,
167                               lhs_ty: Ty<'tcx>,
168                               rhs_expr: &'gcx hir::Expr,
169                               op: hir::BinOp,
170                               is_assign: IsAssign)
171                               -> (Ty<'tcx>, Ty<'tcx>)
172     {
173         debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?}, is_assign={:?})",
174                expr.id,
175                lhs_ty,
176                is_assign);
177
178         // NB: As we have not yet type-checked the RHS, we don't have the
179         // type at hand. Make a variable to represent it. The whole reason
180         // for this indirection is so that, below, we can check the expr
181         // using this variable as the expected type, which sometimes lets
182         // us do better coercions than we would be able to do otherwise,
183         // particularly for things like `String + &String`.
184         let rhs_ty_var = self.next_ty_var(TypeVariableOrigin::MiscVariable(rhs_expr.span));
185
186         let result = self.lookup_op_method(lhs_ty, &[rhs_ty_var], Op::Binary(op, is_assign));
187
188         // see `NB` above
189         let rhs_ty = self.check_expr_coercable_to_type(rhs_expr, rhs_ty_var);
190
191         let return_ty = match result {
192             Ok(method) => {
193                 let by_ref_binop = !op.node.is_by_value();
194                 if is_assign == IsAssign::Yes || by_ref_binop {
195                     if let ty::TyRef(region, mt) = method.sig.inputs()[0].sty {
196                         let autoref = Adjustment {
197                             kind: Adjust::Borrow(AutoBorrow::Ref(region, mt.mutbl)),
198                             target: method.sig.inputs()[0]
199                         };
200                         self.apply_adjustments(lhs_expr, vec![autoref]);
201                     }
202                 }
203                 if by_ref_binop {
204                     if let ty::TyRef(region, mt) = method.sig.inputs()[1].sty {
205                         let autoref = Adjustment {
206                             kind: Adjust::Borrow(AutoBorrow::Ref(region, mt.mutbl)),
207                             target: method.sig.inputs()[1]
208                         };
209                         // HACK(eddyb) Bypass checks due to reborrows being in
210                         // some cases applied on the RHS, on top of which we need
211                         // to autoref, which is not allowed by apply_adjustments.
212                         // self.apply_adjustments(rhs_expr, vec![autoref]);
213                         self.tables
214                             .borrow_mut()
215                             .adjustments_mut()
216                             .entry(rhs_expr.hir_id)
217                             .or_insert(vec![])
218                             .push(autoref);
219                     }
220                 }
221                 self.write_method_call(expr.hir_id, method);
222
223                 method.sig.output()
224             }
225             Err(()) => {
226                 // error types are considered "builtin"
227                 if !lhs_ty.references_error() {
228                     if let IsAssign::Yes = is_assign {
229                         struct_span_err!(self.tcx.sess, expr.span, E0368,
230                                          "binary assignment operation `{}=` \
231                                           cannot be applied to type `{}`",
232                                          op.node.as_str(),
233                                          lhs_ty)
234                             .span_label(lhs_expr.span,
235                                         format!("cannot use `{}=` on type `{}`",
236                                         op.node.as_str(), lhs_ty))
237                             .emit();
238                     } else {
239                         let mut err = struct_span_err!(self.tcx.sess, expr.span, E0369,
240                             "binary operation `{}` cannot be applied to type `{}`",
241                             op.node.as_str(),
242                             lhs_ty);
243
244                         if let TypeVariants::TyRef(_, ref ty_mut) = lhs_ty.sty {
245                             if {
246                                 !self.infcx.type_moves_by_default(self.param_env,
247                                                                   ty_mut.ty,
248                                                                   lhs_expr.span) &&
249                                     self.lookup_op_method(ty_mut.ty,
250                                                           &[rhs_ty],
251                                                           Op::Binary(op, is_assign))
252                                         .is_ok()
253                             } {
254                                 err.note(
255                                     &format!(
256                                         "this is a reference to a type that `{}` can be applied \
257                                         to; you need to dereference this variable once for this \
258                                         operation to work",
259                                     op.node.as_str()));
260                             }
261                         }
262
263                         let missing_trait = match op.node {
264                             hir::BiAdd    => Some("std::ops::Add"),
265                             hir::BiSub    => Some("std::ops::Sub"),
266                             hir::BiMul    => Some("std::ops::Mul"),
267                             hir::BiDiv    => Some("std::ops::Div"),
268                             hir::BiRem    => Some("std::ops::Rem"),
269                             hir::BiBitAnd => Some("std::ops::BitAnd"),
270                             hir::BiBitOr  => Some("std::ops::BitOr"),
271                             hir::BiShl    => Some("std::ops::Shl"),
272                             hir::BiShr    => Some("std::ops::Shr"),
273                             hir::BiEq | hir::BiNe => Some("std::cmp::PartialEq"),
274                             hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe =>
275                                 Some("std::cmp::PartialOrd"),
276                             _             => None
277                         };
278
279                         if let Some(missing_trait) = missing_trait {
280                             if missing_trait == "std::ops::Add" &&
281                                 self.check_str_addition(expr, lhs_expr, lhs_ty,
282                                                         rhs_ty, &mut err) {
283                                 // This has nothing here because it means we did string
284                                 // concatenation (e.g. "Hello " + "World!"). This means
285                                 // we don't want the note in the else clause to be emitted
286                             } else {
287                                 err.note(
288                                     &format!("an implementation of `{}` might be missing for `{}`",
289                                              missing_trait, lhs_ty));
290                             }
291                         }
292                         err.emit();
293                     }
294                 }
295                 self.tcx.types.err
296             }
297         };
298
299         (rhs_ty_var, return_ty)
300     }
301
302     fn check_str_addition(&self,
303                           expr: &'gcx hir::Expr,
304                           lhs_expr: &'gcx hir::Expr,
305                           lhs_ty: Ty<'tcx>,
306                           rhs_ty: Ty<'tcx>,
307                           err: &mut errors::DiagnosticBuilder) -> bool {
308         // If this function returns true it means a note was printed, so we don't need
309         // to print the normal "implementation of `std::ops::Add` might be missing" note
310         let mut is_string_addition = false;
311         if let TyRef(_, l_ty) = lhs_ty.sty {
312             if let TyRef(_, r_ty) = rhs_ty.sty {
313                 if l_ty.ty.sty == TyStr && r_ty.ty.sty == TyStr {
314                     err.span_label(expr.span,
315                         "`+` can't be used to concatenate two `&str` strings");
316                     let codemap = self.tcx.sess.codemap();
317                     let suggestion =
318                         match codemap.span_to_snippet(lhs_expr.span) {
319                             Ok(lstring) => format!("{}.to_owned()", lstring),
320                             _ => format!("<expression>")
321                         };
322                     err.span_suggestion(lhs_expr.span,
323                         &format!("`to_owned()` can be used to create an owned `String` \
324                                   from a string reference. String concatenation \
325                                   appends the string on the right to the string \
326                                   on the left and may require reallocation. This \
327                                   requires ownership of the string on the left"), suggestion);
328                     is_string_addition = true;
329                 }
330
331             }
332
333         }
334
335         is_string_addition
336     }
337
338     pub fn check_user_unop(&self,
339                            ex: &'gcx hir::Expr,
340                            operand_ty: Ty<'tcx>,
341                            op: hir::UnOp)
342                            -> Ty<'tcx>
343     {
344         assert!(op.is_by_value());
345         match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) {
346             Ok(method) => {
347                 self.write_method_call(ex.hir_id, method);
348                 method.sig.output()
349             }
350             Err(()) => {
351                 let actual = self.resolve_type_vars_if_possible(&operand_ty);
352                 if !actual.references_error() {
353                     struct_span_err!(self.tcx.sess, ex.span, E0600,
354                                      "cannot apply unary operator `{}` to type `{}`",
355                                      op.as_str(), actual).emit();
356                 }
357                 self.tcx.types.err
358             }
359         }
360     }
361
362     fn lookup_op_method(&self, lhs_ty: Ty<'tcx>, other_tys: &[Ty<'tcx>], op: Op)
363                         -> Result<MethodCallee<'tcx>, ()>
364     {
365         let lang = &self.tcx.lang_items;
366
367         let span = match op {
368             Op::Binary(op, _) => op.span,
369             Op::Unary(_, span) => span
370         };
371         let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
372             match op.node {
373                 hir::BiAdd => ("add_assign", lang.add_assign_trait()),
374                 hir::BiSub => ("sub_assign", lang.sub_assign_trait()),
375                 hir::BiMul => ("mul_assign", lang.mul_assign_trait()),
376                 hir::BiDiv => ("div_assign", lang.div_assign_trait()),
377                 hir::BiRem => ("rem_assign", lang.rem_assign_trait()),
378                 hir::BiBitXor => ("bitxor_assign", lang.bitxor_assign_trait()),
379                 hir::BiBitAnd => ("bitand_assign", lang.bitand_assign_trait()),
380                 hir::BiBitOr => ("bitor_assign", lang.bitor_assign_trait()),
381                 hir::BiShl => ("shl_assign", lang.shl_assign_trait()),
382                 hir::BiShr => ("shr_assign", lang.shr_assign_trait()),
383                 hir::BiLt | hir::BiLe |
384                 hir::BiGe | hir::BiGt |
385                 hir::BiEq | hir::BiNe |
386                 hir::BiAnd | hir::BiOr => {
387                     span_bug!(span,
388                               "impossible assignment operation: {}=",
389                               op.node.as_str())
390                 }
391             }
392         } else if let Op::Binary(op, IsAssign::No) = op {
393             match op.node {
394                 hir::BiAdd => ("add", lang.add_trait()),
395                 hir::BiSub => ("sub", lang.sub_trait()),
396                 hir::BiMul => ("mul", lang.mul_trait()),
397                 hir::BiDiv => ("div", lang.div_trait()),
398                 hir::BiRem => ("rem", lang.rem_trait()),
399                 hir::BiBitXor => ("bitxor", lang.bitxor_trait()),
400                 hir::BiBitAnd => ("bitand", lang.bitand_trait()),
401                 hir::BiBitOr => ("bitor", lang.bitor_trait()),
402                 hir::BiShl => ("shl", lang.shl_trait()),
403                 hir::BiShr => ("shr", lang.shr_trait()),
404                 hir::BiLt => ("lt", lang.ord_trait()),
405                 hir::BiLe => ("le", lang.ord_trait()),
406                 hir::BiGe => ("ge", lang.ord_trait()),
407                 hir::BiGt => ("gt", lang.ord_trait()),
408                 hir::BiEq => ("eq", lang.eq_trait()),
409                 hir::BiNe => ("ne", lang.eq_trait()),
410                 hir::BiAnd | hir::BiOr => {
411                     span_bug!(span, "&& and || are not overloadable")
412                 }
413             }
414         } else if let Op::Unary(hir::UnNot, _) = op {
415             ("not", lang.not_trait())
416         } else if let Op::Unary(hir::UnNeg, _) = op {
417             ("neg", lang.neg_trait())
418         } else {
419             bug!("lookup_op_method: op not supported: {:?}", op)
420         };
421
422         debug!("lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
423                lhs_ty,
424                op,
425                opname,
426                trait_did);
427
428         let method = trait_did.and_then(|trait_did| {
429             let opname = Symbol::intern(opname);
430             self.lookup_method_in_trait(span, opname, trait_did, lhs_ty, Some(other_tys))
431         });
432
433         match method {
434             Some(ok) => {
435                 let method = self.register_infer_ok_obligations(ok);
436                 self.select_obligations_where_possible();
437
438                 Ok(method)
439             }
440             None => {
441                 Err(())
442             }
443         }
444     }
445 }
446
447 // Binary operator categories. These categories summarize the behavior
448 // with respect to the builtin operationrs supported.
449 enum BinOpCategory {
450     /// &&, || -- cannot be overridden
451     Shortcircuit,
452
453     /// <<, >> -- when shifting a single integer, rhs can be any
454     /// integer type. For simd, types must match.
455     Shift,
456
457     /// +, -, etc -- takes equal types, produces same type as input,
458     /// applicable to ints/floats/simd
459     Math,
460
461     /// &, |, ^ -- takes equal types, produces same type as input,
462     /// applicable to ints/floats/simd/bool
463     Bitwise,
464
465     /// ==, !=, etc -- takes equal types, produces bools, except for simd,
466     /// which produce the input type
467     Comparison,
468 }
469
470 impl BinOpCategory {
471     fn from(op: hir::BinOp) -> BinOpCategory {
472         match op.node {
473             hir::BiShl | hir::BiShr =>
474                 BinOpCategory::Shift,
475
476             hir::BiAdd |
477             hir::BiSub |
478             hir::BiMul |
479             hir::BiDiv |
480             hir::BiRem =>
481                 BinOpCategory::Math,
482
483             hir::BiBitXor |
484             hir::BiBitAnd |
485             hir::BiBitOr =>
486                 BinOpCategory::Bitwise,
487
488             hir::BiEq |
489             hir::BiNe |
490             hir::BiLt |
491             hir::BiLe |
492             hir::BiGe |
493             hir::BiGt =>
494                 BinOpCategory::Comparison,
495
496             hir::BiAnd |
497             hir::BiOr =>
498                 BinOpCategory::Shortcircuit,
499         }
500     }
501 }
502
503 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
504 #[derive(Clone, Copy, Debug, PartialEq)]
505 enum IsAssign {
506     No,
507     Yes,
508 }
509
510 #[derive(Clone, Copy, Debug)]
511 enum Op {
512     Binary(hir::BinOp, IsAssign),
513     Unary(hir::UnOp, Span),
514 }
515
516 /// Returns true if this is a built-in arithmetic operation (e.g. u32
517 /// + u32, i16x4 == i16x4) and false if these types would have to be
518 /// overloaded to be legal. There are two reasons that we distinguish
519 /// builtin operations from overloaded ones (vs trying to drive
520 /// everything uniformly through the trait system and intrinsics or
521 /// something like that):
522 ///
523 /// 1. Builtin operations can trivially be evaluated in constants.
524 /// 2. For comparison operators applied to SIMD types the result is
525 ///    not of type `bool`. For example, `i16x4==i16x4` yields a
526 ///    type like `i16x4`. This means that the overloaded trait
527 ///    `PartialEq` is not applicable.
528 ///
529 /// Reason #2 is the killer. I tried for a while to always use
530 /// overloaded logic and just check the types in constants/trans after
531 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
532 fn is_builtin_binop(lhs: Ty, rhs: Ty, op: hir::BinOp) -> bool {
533     match BinOpCategory::from(op) {
534         BinOpCategory::Shortcircuit => {
535             true
536         }
537
538         BinOpCategory::Shift => {
539             lhs.references_error() || rhs.references_error() ||
540                 lhs.is_integral() && rhs.is_integral()
541         }
542
543         BinOpCategory::Math => {
544             lhs.references_error() || rhs.references_error() ||
545                 lhs.is_integral() && rhs.is_integral() ||
546                 lhs.is_floating_point() && rhs.is_floating_point()
547         }
548
549         BinOpCategory::Bitwise => {
550             lhs.references_error() || rhs.references_error() ||
551                 lhs.is_integral() && rhs.is_integral() ||
552                 lhs.is_floating_point() && rhs.is_floating_point() ||
553                 lhs.is_bool() && rhs.is_bool()
554         }
555
556         BinOpCategory::Comparison => {
557             lhs.references_error() || rhs.references_error() ||
558                 lhs.is_scalar() && rhs.is_scalar()
559         }
560     }
561 }