]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/op.rs
Auto merge of #42394 - ollie27:rustdoc_deref_box, r=QuietMisdreavus
[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.borrow_mut().adjustments.entry(rhs_expr.id)
214                             .or_insert(vec![]).push(autoref);
215                     }
216                 }
217                 self.write_method_call(expr.id, method);
218
219                 method.sig.output()
220             }
221             Err(()) => {
222                 // error types are considered "builtin"
223                 if !lhs_ty.references_error() {
224                     if let IsAssign::Yes = is_assign {
225                         struct_span_err!(self.tcx.sess, expr.span, E0368,
226                                          "binary assignment operation `{}=` \
227                                           cannot be applied to type `{}`",
228                                          op.node.as_str(),
229                                          lhs_ty)
230                             .span_label(lhs_expr.span,
231                                         format!("cannot use `{}=` on type `{}`",
232                                         op.node.as_str(), lhs_ty))
233                             .emit();
234                     } else {
235                         let mut err = struct_span_err!(self.tcx.sess, expr.span, E0369,
236                             "binary operation `{}` cannot be applied to type `{}`",
237                             op.node.as_str(),
238                             lhs_ty);
239
240                         if let TypeVariants::TyRef(_, ref ty_mut) = lhs_ty.sty {
241                             if {
242                                 !self.infcx.type_moves_by_default(self.param_env,
243                                                                   ty_mut.ty,
244                                                                   lhs_expr.span) &&
245                                     self.lookup_op_method(ty_mut.ty,
246                                                           &[rhs_ty],
247                                                           Op::Binary(op, is_assign))
248                                         .is_ok()
249                             } {
250                                 err.note(
251                                     &format!(
252                                         "this is a reference to a type that `{}` can be applied \
253                                         to; you need to dereference this variable once for this \
254                                         operation to work",
255                                     op.node.as_str()));
256                             }
257                         }
258
259                         let missing_trait = match op.node {
260                             hir::BiAdd    => Some("std::ops::Add"),
261                             hir::BiSub    => Some("std::ops::Sub"),
262                             hir::BiMul    => Some("std::ops::Mul"),
263                             hir::BiDiv    => Some("std::ops::Div"),
264                             hir::BiRem    => Some("std::ops::Rem"),
265                             hir::BiBitAnd => Some("std::ops::BitAnd"),
266                             hir::BiBitOr  => Some("std::ops::BitOr"),
267                             hir::BiShl    => Some("std::ops::Shl"),
268                             hir::BiShr    => Some("std::ops::Shr"),
269                             hir::BiEq | hir::BiNe => Some("std::cmp::PartialEq"),
270                             hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe =>
271                                 Some("std::cmp::PartialOrd"),
272                             _             => None
273                         };
274
275                         if let Some(missing_trait) = missing_trait {
276                             if missing_trait == "std::ops::Add" &&
277                                 self.check_str_addition(expr, lhs_expr, lhs_ty,
278                                                         rhs_ty, &mut err) {
279                                 // This has nothing here because it means we did string
280                                 // concatenation (e.g. "Hello " + "World!"). This means
281                                 // we don't want the note in the else clause to be emitted
282                             } else {
283                                 err.note(
284                                     &format!("an implementation of `{}` might be missing for `{}`",
285                                              missing_trait, lhs_ty));
286                             }
287                         }
288                         err.emit();
289                     }
290                 }
291                 self.tcx.types.err
292             }
293         };
294
295         (rhs_ty_var, return_ty)
296     }
297
298     fn check_str_addition(&self,
299                           expr: &'gcx hir::Expr,
300                           lhs_expr: &'gcx hir::Expr,
301                           lhs_ty: Ty<'tcx>,
302                           rhs_ty: Ty<'tcx>,
303                           mut err: &mut errors::DiagnosticBuilder) -> bool {
304         // If this function returns true it means a note was printed, so we don't need
305         // to print the normal "implementation of `std::ops::Add` might be missing" note
306         let mut is_string_addition = false;
307         if let TyRef(_, l_ty) = lhs_ty.sty {
308             if let TyRef(_, r_ty) = rhs_ty.sty {
309                 if l_ty.ty.sty == TyStr && r_ty.ty.sty == TyStr {
310                     err.span_label(expr.span,
311                         "`+` can't be used to concatenate two `&str` strings");
312                     let codemap = self.tcx.sess.codemap();
313                     let suggestion =
314                         match codemap.span_to_snippet(lhs_expr.span) {
315                             Ok(lstring) => format!("{}.to_owned()", lstring),
316                             _ => format!("<expression>")
317                         };
318                     err.span_suggestion(lhs_expr.span,
319                         &format!("`to_owned()` can be used to create an owned `String` \
320                                   from a string reference. String concatenation \
321                                   appends the string on the right to the string \
322                                   on the left and may require reallocation. This \
323                                   requires ownership of the string on the left."), suggestion);
324                     is_string_addition = true;
325                 }
326
327             }
328
329         }
330
331         is_string_addition
332     }
333
334     pub fn check_user_unop(&self,
335                            ex: &'gcx hir::Expr,
336                            operand_ty: Ty<'tcx>,
337                            op: hir::UnOp)
338                            -> Ty<'tcx>
339     {
340         assert!(op.is_by_value());
341         match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) {
342             Ok(method) => {
343                 self.write_method_call(ex.id, method);
344                 method.sig.output()
345             }
346             Err(()) => {
347                 let actual = self.resolve_type_vars_if_possible(&operand_ty);
348                 if !actual.references_error() {
349                     struct_span_err!(self.tcx.sess, ex.span, E0600,
350                                      "cannot apply unary operator `{}` to type `{}`",
351                                      op.as_str(), actual).emit();
352                 }
353                 self.tcx.types.err
354             }
355         }
356     }
357
358     fn lookup_op_method(&self, lhs_ty: Ty<'tcx>, other_tys: &[Ty<'tcx>], op: Op)
359                         -> Result<MethodCallee<'tcx>, ()>
360     {
361         let lang = &self.tcx.lang_items;
362
363         let span = match op {
364             Op::Binary(op, _) => op.span,
365             Op::Unary(_, span) => span
366         };
367         let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
368             match op.node {
369                 hir::BiAdd => ("add_assign", lang.add_assign_trait()),
370                 hir::BiSub => ("sub_assign", lang.sub_assign_trait()),
371                 hir::BiMul => ("mul_assign", lang.mul_assign_trait()),
372                 hir::BiDiv => ("div_assign", lang.div_assign_trait()),
373                 hir::BiRem => ("rem_assign", lang.rem_assign_trait()),
374                 hir::BiBitXor => ("bitxor_assign", lang.bitxor_assign_trait()),
375                 hir::BiBitAnd => ("bitand_assign", lang.bitand_assign_trait()),
376                 hir::BiBitOr => ("bitor_assign", lang.bitor_assign_trait()),
377                 hir::BiShl => ("shl_assign", lang.shl_assign_trait()),
378                 hir::BiShr => ("shr_assign", lang.shr_assign_trait()),
379                 hir::BiLt | hir::BiLe |
380                 hir::BiGe | hir::BiGt |
381                 hir::BiEq | hir::BiNe |
382                 hir::BiAnd | hir::BiOr => {
383                     span_bug!(span,
384                               "impossible assignment operation: {}=",
385                               op.node.as_str())
386                 }
387             }
388         } else if let Op::Binary(op, IsAssign::No) = op {
389             match op.node {
390                 hir::BiAdd => ("add", lang.add_trait()),
391                 hir::BiSub => ("sub", lang.sub_trait()),
392                 hir::BiMul => ("mul", lang.mul_trait()),
393                 hir::BiDiv => ("div", lang.div_trait()),
394                 hir::BiRem => ("rem", lang.rem_trait()),
395                 hir::BiBitXor => ("bitxor", lang.bitxor_trait()),
396                 hir::BiBitAnd => ("bitand", lang.bitand_trait()),
397                 hir::BiBitOr => ("bitor", lang.bitor_trait()),
398                 hir::BiShl => ("shl", lang.shl_trait()),
399                 hir::BiShr => ("shr", lang.shr_trait()),
400                 hir::BiLt => ("lt", lang.ord_trait()),
401                 hir::BiLe => ("le", lang.ord_trait()),
402                 hir::BiGe => ("ge", lang.ord_trait()),
403                 hir::BiGt => ("gt", lang.ord_trait()),
404                 hir::BiEq => ("eq", lang.eq_trait()),
405                 hir::BiNe => ("ne", lang.eq_trait()),
406                 hir::BiAnd | hir::BiOr => {
407                     span_bug!(span, "&& and || are not overloadable")
408                 }
409             }
410         } else if let Op::Unary(hir::UnNot, _) = op {
411             ("not", lang.not_trait())
412         } else if let Op::Unary(hir::UnNeg, _) = op {
413             ("neg", lang.neg_trait())
414         } else {
415             bug!("lookup_op_method: op not supported: {:?}", op)
416         };
417
418         debug!("lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
419                lhs_ty,
420                op,
421                opname,
422                trait_did);
423
424         let method = trait_did.and_then(|trait_did| {
425             let opname = Symbol::intern(opname);
426             self.lookup_method_in_trait(span, opname, trait_did, lhs_ty, Some(other_tys))
427         });
428
429         match method {
430             Some(ok) => {
431                 let method = self.register_infer_ok_obligations(ok);
432                 self.select_obligations_where_possible();
433
434                 Ok(method)
435             }
436             None => {
437                 Err(())
438             }
439         }
440     }
441 }
442
443 // Binary operator categories. These categories summarize the behavior
444 // with respect to the builtin operationrs supported.
445 enum BinOpCategory {
446     /// &&, || -- cannot be overridden
447     Shortcircuit,
448
449     /// <<, >> -- when shifting a single integer, rhs can be any
450     /// integer type. For simd, types must match.
451     Shift,
452
453     /// +, -, etc -- takes equal types, produces same type as input,
454     /// applicable to ints/floats/simd
455     Math,
456
457     /// &, |, ^ -- takes equal types, produces same type as input,
458     /// applicable to ints/floats/simd/bool
459     Bitwise,
460
461     /// ==, !=, etc -- takes equal types, produces bools, except for simd,
462     /// which produce the input type
463     Comparison,
464 }
465
466 impl BinOpCategory {
467     fn from(op: hir::BinOp) -> BinOpCategory {
468         match op.node {
469             hir::BiShl | hir::BiShr =>
470                 BinOpCategory::Shift,
471
472             hir::BiAdd |
473             hir::BiSub |
474             hir::BiMul |
475             hir::BiDiv |
476             hir::BiRem =>
477                 BinOpCategory::Math,
478
479             hir::BiBitXor |
480             hir::BiBitAnd |
481             hir::BiBitOr =>
482                 BinOpCategory::Bitwise,
483
484             hir::BiEq |
485             hir::BiNe |
486             hir::BiLt |
487             hir::BiLe |
488             hir::BiGe |
489             hir::BiGt =>
490                 BinOpCategory::Comparison,
491
492             hir::BiAnd |
493             hir::BiOr =>
494                 BinOpCategory::Shortcircuit,
495         }
496     }
497 }
498
499 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
500 #[derive(Clone, Copy, Debug, PartialEq)]
501 enum IsAssign {
502     No,
503     Yes,
504 }
505
506 #[derive(Clone, Copy, Debug)]
507 enum Op {
508     Binary(hir::BinOp, IsAssign),
509     Unary(hir::UnOp, Span),
510 }
511
512 /// Returns true if this is a built-in arithmetic operation (e.g. u32
513 /// + u32, i16x4 == i16x4) and false if these types would have to be
514 /// overloaded to be legal. There are two reasons that we distinguish
515 /// builtin operations from overloaded ones (vs trying to drive
516 /// everything uniformly through the trait system and intrinsics or
517 /// something like that):
518 ///
519 /// 1. Builtin operations can trivially be evaluated in constants.
520 /// 2. For comparison operators applied to SIMD types the result is
521 ///    not of type `bool`. For example, `i16x4==i16x4` yields a
522 ///    type like `i16x4`. This means that the overloaded trait
523 ///    `PartialEq` is not applicable.
524 ///
525 /// Reason #2 is the killer. I tried for a while to always use
526 /// overloaded logic and just check the types in constants/trans after
527 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
528 fn is_builtin_binop(lhs: Ty, rhs: Ty, op: hir::BinOp) -> bool {
529     match BinOpCategory::from(op) {
530         BinOpCategory::Shortcircuit => {
531             true
532         }
533
534         BinOpCategory::Shift => {
535             lhs.references_error() || rhs.references_error() ||
536                 lhs.is_integral() && rhs.is_integral()
537         }
538
539         BinOpCategory::Math => {
540             lhs.references_error() || rhs.references_error() ||
541                 lhs.is_integral() && rhs.is_integral() ||
542                 lhs.is_floating_point() && rhs.is_floating_point()
543         }
544
545         BinOpCategory::Bitwise => {
546             lhs.references_error() || rhs.references_error() ||
547                 lhs.is_integral() && rhs.is_integral() ||
548                 lhs.is_floating_point() && rhs.is_floating_point() ||
549                 lhs.is_bool() && rhs.is_bool()
550         }
551
552         BinOpCategory::Comparison => {
553             lhs.references_error() || rhs.references_error() ||
554                 lhs.is_scalar() && rhs.is_scalar()
555         }
556     }
557 }