]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/op.rs
review comment: add extra doc
[rust.git] / src / librustc_typeck / check / op.rs
1 //! Code related to processing overloaded binary and unary operators.
2
3 use super::{FnCtxt, Needs};
4 use super::method::MethodCallee;
5 use rustc::ty::{self, Ty, TypeFoldable};
6 use rustc::ty::TyKind::{Ref, Adt, FnDef, Str, Uint, Never, Tuple, Char, Array};
7 use rustc::ty::adjustment::{Adjustment, Adjust, AllowTwoPhase, AutoBorrow, AutoBorrowMutability};
8 use rustc::infer::type_variable::TypeVariableOrigin;
9 use errors::{self,Applicability};
10 use syntax_pos::Span;
11 use syntax::ast::Ident;
12 use rustc::hir;
13
14 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
15     /// Checks a `a <op>= b`
16     pub fn check_binop_assign(&self,
17                               expr: &'gcx hir::Expr,
18                               op: hir::BinOp,
19                               lhs_expr: &'gcx hir::Expr,
20                               rhs_expr: &'gcx hir::Expr) -> Ty<'tcx>
21     {
22         let (lhs_ty, rhs_ty, return_ty) =
23             self.check_overloaded_binop(expr, lhs_expr, rhs_expr, op, IsAssign::Yes);
24
25         let ty = if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var()
26                     && is_builtin_binop(lhs_ty, rhs_ty, op) {
27             self.enforce_builtin_binop_types(lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
28             self.tcx.mk_unit()
29         } else {
30             return_ty
31         };
32
33         if !lhs_expr.is_place_expr() {
34             struct_span_err!(
35                 self.tcx.sess, lhs_expr.span,
36                 E0067, "invalid left-hand side expression")
37             .span_label(
38                 lhs_expr.span,
39                 "invalid expression for left-hand side")
40             .emit();
41         }
42         ty
43     }
44
45     /// Checks a potentially overloaded binary operator.
46     pub fn check_binop(&self,
47                        expr: &'gcx hir::Expr,
48                        op: hir::BinOp,
49                        lhs_expr: &'gcx hir::Expr,
50                        rhs_expr: &'gcx hir::Expr) -> Ty<'tcx>
51     {
52         let tcx = self.tcx;
53
54         debug!("check_binop(expr.hir_id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
55                expr.hir_id,
56                expr,
57                op,
58                lhs_expr,
59                rhs_expr);
60
61         match BinOpCategory::from(op) {
62             BinOpCategory::Shortcircuit => {
63                 // && and || are a simple case.
64                 self.check_expr_coercable_to_type(lhs_expr, tcx.types.bool);
65                 let lhs_diverges = self.diverges.get();
66                 self.check_expr_coercable_to_type(rhs_expr, tcx.types.bool);
67
68                 // Depending on the LHS' value, the RHS can never execute.
69                 self.diverges.set(lhs_diverges);
70
71                 tcx.types.bool
72             }
73             _ => {
74                 // Otherwise, we always treat operators as if they are
75                 // overloaded. This is the way to be most flexible w/r/t
76                 // types that get inferred.
77                 let (lhs_ty, rhs_ty, return_ty) =
78                     self.check_overloaded_binop(expr, lhs_expr,
79                                                 rhs_expr, op, IsAssign::No);
80
81                 // Supply type inference hints if relevant. Probably these
82                 // hints should be enforced during select as part of the
83                 // `consider_unification_despite_ambiguity` routine, but this
84                 // more convenient for now.
85                 //
86                 // The basic idea is to help type inference by taking
87                 // advantage of things we know about how the impls for
88                 // scalar types are arranged. This is important in a
89                 // scenario like `1_u32 << 2`, because it lets us quickly
90                 // deduce that the result type should be `u32`, even
91                 // though we don't know yet what type 2 has and hence
92                 // can't pin this down to a specific impl.
93                 if
94                     !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() &&
95                     is_builtin_binop(lhs_ty, rhs_ty, op)
96                 {
97                     let builtin_return_ty =
98                         self.enforce_builtin_binop_types(lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
99                     self.demand_suptype(expr.span, builtin_return_ty, return_ty);
100                 }
101
102                 return_ty
103             }
104         }
105     }
106
107     fn enforce_builtin_binop_types(&self,
108                                    lhs_expr: &'gcx hir::Expr,
109                                    lhs_ty: Ty<'tcx>,
110                                    rhs_expr: &'gcx hir::Expr,
111                                    rhs_ty: Ty<'tcx>,
112                                    op: hir::BinOp)
113                                    -> Ty<'tcx>
114     {
115         debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
116
117         let tcx = self.tcx;
118         match BinOpCategory::from(op) {
119             BinOpCategory::Shortcircuit => {
120                 self.demand_suptype(lhs_expr.span, tcx.mk_bool(), lhs_ty);
121                 self.demand_suptype(rhs_expr.span, tcx.mk_bool(), rhs_ty);
122                 tcx.mk_bool()
123             }
124
125             BinOpCategory::Shift => {
126                 // result type is same as LHS always
127                 lhs_ty
128             }
129
130             BinOpCategory::Math |
131             BinOpCategory::Bitwise => {
132                 // both LHS and RHS and result will have the same type
133                 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
134                 lhs_ty
135             }
136
137             BinOpCategory::Comparison => {
138                 // both LHS and RHS and result will have the same type
139                 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
140                 tcx.mk_bool()
141             }
142         }
143     }
144
145     fn check_overloaded_binop(&self,
146                               expr: &'gcx hir::Expr,
147                               lhs_expr: &'gcx hir::Expr,
148                               rhs_expr: &'gcx hir::Expr,
149                               op: hir::BinOp,
150                               is_assign: IsAssign)
151                               -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>)
152     {
153         debug!("check_overloaded_binop(expr.hir_id={}, op={:?}, is_assign={:?})",
154                expr.hir_id,
155                op,
156                is_assign);
157
158         let lhs_ty = match is_assign {
159             IsAssign::No => {
160                 // Find a suitable supertype of the LHS expression's type, by coercing to
161                 // a type variable, to pass as the `Self` to the trait, avoiding invariant
162                 // trait matching creating lifetime constraints that are too strict.
163                 // e.g., adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
164                 // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`.
165                 let lhs_ty = self.check_expr_with_needs(lhs_expr, Needs::None);
166                 let fresh_var = self.next_ty_var(TypeVariableOrigin::MiscVariable(lhs_expr.span));
167                 self.demand_coerce(lhs_expr, lhs_ty, fresh_var,  AllowTwoPhase::No)
168             }
169             IsAssign::Yes => {
170                 // rust-lang/rust#52126: We have to use strict
171                 // equivalence on the LHS of an assign-op like `+=`;
172                 // overwritten or mutably-borrowed places cannot be
173                 // coerced to a supertype.
174                 self.check_expr_with_needs(lhs_expr, Needs::MutPlace)
175             }
176         };
177         let lhs_ty = self.resolve_type_vars_with_obligations(lhs_ty);
178
179         // N.B., 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 = self.next_ty_var(TypeVariableOrigin::MiscVariable(rhs_expr.span));
186
187         let result = self.lookup_op_method(lhs_ty, &[rhs_ty_var], Op::Binary(op, is_assign));
188
189         // see `NB` above
190         let rhs_ty = self.check_expr_coercable_to_type(rhs_expr, rhs_ty_var);
191         let rhs_ty = self.resolve_type_vars_with_obligations(rhs_ty);
192
193         let return_ty = match result {
194             Ok(method) => {
195                 let by_ref_binop = !op.node.is_by_value();
196                 if is_assign == IsAssign::Yes || by_ref_binop {
197                     if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].sty {
198                         let mutbl = match mutbl {
199                             hir::MutImmutable => AutoBorrowMutability::Immutable,
200                             hir::MutMutable => AutoBorrowMutability::Mutable {
201                                 // Allow two-phase borrows for binops in initial deployment
202                                 // since they desugar to methods
203                                 allow_two_phase_borrow: AllowTwoPhase::Yes,
204                             }
205                         };
206                         let autoref = Adjustment {
207                             kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
208                             target: method.sig.inputs()[0]
209                         };
210                         self.apply_adjustments(lhs_expr, vec![autoref]);
211                     }
212                 }
213                 if by_ref_binop {
214                     if let ty::Ref(region, _, mutbl) = method.sig.inputs()[1].sty {
215                         let mutbl = match mutbl {
216                             hir::MutImmutable => AutoBorrowMutability::Immutable,
217                             hir::MutMutable => AutoBorrowMutability::Mutable {
218                                 // Allow two-phase borrows for binops in initial deployment
219                                 // since they desugar to methods
220                                 allow_two_phase_borrow: AllowTwoPhase::Yes,
221                             }
222                         };
223                         let autoref = Adjustment {
224                             kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
225                             target: method.sig.inputs()[1]
226                         };
227                         // HACK(eddyb) Bypass checks due to reborrows being in
228                         // some cases applied on the RHS, on top of which we need
229                         // to autoref, which is not allowed by apply_adjustments.
230                         // self.apply_adjustments(rhs_expr, vec![autoref]);
231                         self.tables
232                             .borrow_mut()
233                             .adjustments_mut()
234                             .entry(rhs_expr.hir_id)
235                             .or_default()
236                             .push(autoref);
237                     }
238                 }
239                 self.write_method_call(expr.hir_id, method);
240
241                 method.sig.output()
242             }
243             Err(()) => {
244                 // error types are considered "builtin"
245                 if !lhs_ty.references_error() {
246                     let source_map = self.tcx.sess.source_map();
247                     match is_assign {
248                         IsAssign::Yes => {
249                             let mut err = struct_span_err!(
250                                 self.tcx.sess,
251                                 expr.span,
252                                 E0368,
253                                 "binary assignment operation `{}=` cannot be applied to type `{}`",
254                                 op.node.as_str(),
255                                 lhs_ty,
256                             );
257                             err.span_label(
258                                 lhs_expr.span,
259                                 format!("cannot use `{}=` on type `{}`",
260                                 op.node.as_str(), lhs_ty),
261                             );
262                             let mut suggested_deref = false;
263                             if let Ref(_, mut rty, _) = lhs_ty.sty {
264                                 if {
265                                     self.infcx.type_is_copy_modulo_regions(self.param_env,
266                                                                            rty,
267                                                                            lhs_expr.span) &&
268                                         self.lookup_op_method(rty,
269                                                               &[rhs_ty],
270                                                               Op::Binary(op, is_assign))
271                                             .is_ok()
272                                 } {
273                                     if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
274                                         while let Ref(_, rty_inner, _) = rty.sty {
275                                             rty = rty_inner;
276                                         }
277                                         let msg = &format!(
278                                             "`{}=` can be used on '{}', you can dereference `{}`",
279                                             op.node.as_str(),
280                                             rty,
281                                             lstring,
282                                         );
283                                         err.span_suggestion(
284                                             lhs_expr.span,
285                                             msg,
286                                             format!("*{}", lstring),
287                                             errors::Applicability::MachineApplicable,
288                                         );
289                                         suggested_deref = true;
290                                     }
291                                 }
292                             }
293                             let missing_trait = match op.node {
294                                 hir::BinOpKind::Add    => Some("std::ops::AddAssign"),
295                                 hir::BinOpKind::Sub    => Some("std::ops::SubAssign"),
296                                 hir::BinOpKind::Mul    => Some("std::ops::MulAssign"),
297                                 hir::BinOpKind::Div    => Some("std::ops::DivAssign"),
298                                 hir::BinOpKind::Rem    => Some("std::ops::RemAssign"),
299                                 hir::BinOpKind::BitAnd => Some("std::ops::BitAndAssign"),
300                                 hir::BinOpKind::BitXor => Some("std::ops::BitXorAssign"),
301                                 hir::BinOpKind::BitOr  => Some("std::ops::BitOrAssign"),
302                                 hir::BinOpKind::Shl    => Some("std::ops::ShlAssign"),
303                                 hir::BinOpKind::Shr    => Some("std::ops::ShrAssign"),
304                                 _                      => None
305                             };
306                             if let Some(missing_trait) = missing_trait {
307                                 if op.node == hir::BinOpKind::Add &&
308                                     self.check_str_addition(expr, lhs_expr, rhs_expr, lhs_ty,
309                                                             rhs_ty, &mut err, true, op) {
310                                     // This has nothing here because it means we did string
311                                     // concatenation (e.g., "Hello " += "World!"). This means
312                                     // we don't want the note in the else clause to be emitted
313                                 } else if let ty::Param(_) = lhs_ty.sty {
314                                     // FIXME: point to span of param
315                                     err.note(&format!(
316                                         "`{}` might need a bound for `{}`",
317                                         lhs_ty, missing_trait
318                                     ));
319                                 } else if !suggested_deref {
320                                     err.note(&format!(
321                                         "an implementation of `{}` might \
322                                          be missing for `{}`",
323                                         missing_trait, lhs_ty
324                                     ));
325                                 }
326                             }
327                             err.emit();
328                         }
329                         IsAssign::No => {
330                             let mut err = struct_span_err!(self.tcx.sess, op.span, E0369,
331                                 "binary operation `{}` cannot be applied to type `{}`",
332                                 op.node.as_str(),
333                                 lhs_ty);
334
335                             let mut involves_fn = false;
336                             if !lhs_expr.span.eq(&rhs_expr.span) {
337                                 involves_fn |= self.add_type_neq_err_label(
338                                     &mut err,
339                                     lhs_expr.span,
340                                     lhs_ty,
341                                     rhs_ty,
342                                     op,
343                                     is_assign
344                                 );
345                                 involves_fn |= self.add_type_neq_err_label(
346                                     &mut err,
347                                     rhs_expr.span,
348                                     rhs_ty,
349                                     lhs_ty,
350                                     op,
351                                     is_assign
352                                 );
353                             }
354
355                             let mut suggested_deref = false;
356                             if let Ref(_, mut rty, _) = lhs_ty.sty {
357                                 if {
358                                     self.infcx.type_is_copy_modulo_regions(self.param_env,
359                                                                            rty,
360                                                                            lhs_expr.span) &&
361                                         self.lookup_op_method(rty,
362                                                               &[rhs_ty],
363                                                               Op::Binary(op, is_assign))
364                                             .is_ok()
365                                 } {
366                                     if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
367                                         while let Ref(_, rty_inner, _) = rty.sty {
368                                             rty = rty_inner;
369                                         }
370                                         let msg = &format!(
371                                                 "`{}` can be used on '{}', you can \
372                                                 dereference `{2}`: `*{2}`",
373                                                 op.node.as_str(),
374                                                 rty,
375                                                 lstring
376                                         );
377                                         err.help(msg);
378                                         suggested_deref = true;
379                                     }
380                                 }
381                             }
382                             let missing_trait = match op.node {
383                                 hir::BinOpKind::Add    => Some("std::ops::Add"),
384                                 hir::BinOpKind::Sub    => Some("std::ops::Sub"),
385                                 hir::BinOpKind::Mul    => Some("std::ops::Mul"),
386                                 hir::BinOpKind::Div    => Some("std::ops::Div"),
387                                 hir::BinOpKind::Rem    => Some("std::ops::Rem"),
388                                 hir::BinOpKind::BitAnd => Some("std::ops::BitAnd"),
389                                 hir::BinOpKind::BitXor => Some("std::ops::BitXor"),
390                                 hir::BinOpKind::BitOr  => Some("std::ops::BitOr"),
391                                 hir::BinOpKind::Shl    => Some("std::ops::Shl"),
392                                 hir::BinOpKind::Shr    => Some("std::ops::Shr"),
393                                 hir::BinOpKind::Eq |
394                                 hir::BinOpKind::Ne => Some("std::cmp::PartialEq"),
395                                 hir::BinOpKind::Lt |
396                                 hir::BinOpKind::Le |
397                                 hir::BinOpKind::Gt |
398                                 hir::BinOpKind::Ge => Some("std::cmp::PartialOrd"),
399                                 _ => None
400                             };
401                             if let Some(missing_trait) = missing_trait {
402                                 if op.node == hir::BinOpKind::Add &&
403                                     self.check_str_addition(expr, lhs_expr, rhs_expr, lhs_ty,
404                                                             rhs_ty, &mut err, false, op) {
405                                     // This has nothing here because it means we did string
406                                     // concatenation (e.g., "Hello " + "World!"). This means
407                                     // we don't want the note in the else clause to be emitted
408                                 } else if let ty::Param(_) = lhs_ty.sty {
409                                     // FIXME: point to span of param
410                                     err.note(&format!(
411                                         "`{}` might need a bound for `{}`",
412                                         lhs_ty, missing_trait
413                                     ));
414                                 } else if !suggested_deref && !involves_fn {
415                                     err.note(&format!(
416                                         "an implementation of `{}` might \
417                                          be missing for `{}`",
418                                         missing_trait, lhs_ty
419                                     ));
420                                 }
421                             }
422                             err.emit();
423                         }
424                     }
425                 }
426                 self.tcx.types.err
427             }
428         };
429
430         (lhs_ty, rhs_ty, return_ty)
431     }
432
433     /// If one of the types is an uncalled function and calling it would yield the other type,
434     /// suggest calling the function. Returns wether a suggestion was given.
435     fn add_type_neq_err_label(
436         &self,
437         err: &mut errors::DiagnosticBuilder<'_>,
438         span: Span,
439         ty: Ty<'tcx>,
440         other_ty: Ty<'tcx>,
441         op: hir::BinOp,
442         is_assign: IsAssign,
443     ) -> bool /* did we suggest to call a function because of missing parenthesis? */ {
444         err.span_label(span, ty.to_string());
445         if let FnDef(def_id, _) = ty.sty {
446             let source_map = self.tcx.sess.source_map();
447             let hir_id = &self.tcx.hir().as_local_hir_id(def_id).unwrap();
448             let fn_sig = {
449                 match self.tcx.typeck_tables_of(def_id).liberated_fn_sigs().get(*hir_id) {
450                     Some(f) => f.clone(),
451                     None => {
452                         bug!("No fn-sig entry for def_id={:?}", def_id);
453                     }
454                 }
455             };
456
457             let other_ty = if let FnDef(def_id, _) = other_ty.sty {
458                 let hir_id = &self.tcx.hir().as_local_hir_id(def_id).unwrap();
459                 match self.tcx.typeck_tables_of(def_id).liberated_fn_sigs().get(*hir_id) {
460                     Some(f) => f.clone().output(),
461                     None => {
462                         bug!("No fn-sig entry for def_id={:?}", def_id);
463                     }
464                 }
465             } else {
466                 other_ty
467             };
468
469             if self.lookup_op_method(fn_sig.output(),
470                                     &[other_ty],
471                                     Op::Binary(op, is_assign))
472                     .is_ok() {
473                 let (variable_snippet, applicability) = if fn_sig.inputs().len() > 0 {
474                     (format!("{}( /* arguments */ )", source_map.span_to_snippet(span).unwrap()),
475                     Applicability::HasPlaceholders)
476                 } else {
477                     (format!("{}()", source_map.span_to_snippet(span).unwrap()),
478                     Applicability::MaybeIncorrect)
479                 };
480
481                 err.span_suggestion(
482                     span,
483                     "you might have forgotten to call this function",
484                     variable_snippet,
485                     applicability,
486                 );
487                 return true;
488             }
489         }
490         false
491     }
492
493     fn check_str_addition(
494         &self,
495         expr: &'gcx hir::Expr,
496         lhs_expr: &'gcx hir::Expr,
497         rhs_expr: &'gcx hir::Expr,
498         lhs_ty: Ty<'tcx>,
499         rhs_ty: Ty<'tcx>,
500         err: &mut errors::DiagnosticBuilder<'_>,
501         is_assign: bool,
502         op: hir::BinOp,
503     ) -> bool {
504         let source_map = self.tcx.sess.source_map();
505         let msg = "`to_owned()` can be used to create an owned `String` \
506                    from a string reference. String concatenation \
507                    appends the string on the right to the string \
508                    on the left and may require reallocation. This \
509                    requires ownership of the string on the left";
510         // If this function returns true it means a note was printed, so we don't need
511         // to print the normal "implementation of `std::ops::Add` might be missing" note
512         match (&lhs_ty.sty, &rhs_ty.sty) {
513             (&Ref(_, l_ty, _), &Ref(_, r_ty, _))
514             if l_ty.sty == Str && r_ty.sty == Str => {
515                 if !is_assign {
516                     err.span_label(op.span,
517                                    "`+` can't be used to concatenate two `&str` strings");
518                     match source_map.span_to_snippet(lhs_expr.span) {
519                         Ok(lstring) => err.span_suggestion(
520                             lhs_expr.span,
521                             msg,
522                             format!("{}.to_owned()", lstring),
523                             Applicability::MachineApplicable,
524                         ),
525                         _ => err.help(msg),
526                     };
527                 }
528                 true
529             }
530             (&Ref(_, l_ty, _), &Adt(..))
531             if l_ty.sty == Str && &format!("{:?}", rhs_ty) == "std::string::String" => {
532                 err.span_label(expr.span,
533                     "`+` can't be used to concatenate a `&str` with a `String`");
534                 match (
535                     source_map.span_to_snippet(lhs_expr.span),
536                     source_map.span_to_snippet(rhs_expr.span),
537                     is_assign,
538                 ) {
539                     (Ok(l), Ok(r), false) => {
540                         err.multipart_suggestion(
541                             msg,
542                             vec![
543                                 (lhs_expr.span, format!("{}.to_owned()", l)),
544                                 (rhs_expr.span, format!("&{}", r)),
545                             ],
546                             Applicability::MachineApplicable,
547                         );
548                     }
549                     _ => {
550                         err.help(msg);
551                     }
552                 };
553                 true
554             }
555             _ => false,
556         }
557     }
558
559     pub fn check_user_unop(&self,
560                            ex: &'gcx hir::Expr,
561                            operand_ty: Ty<'tcx>,
562                            op: hir::UnOp)
563                            -> Ty<'tcx>
564     {
565         assert!(op.is_by_value());
566         match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) {
567             Ok(method) => {
568                 self.write_method_call(ex.hir_id, method);
569                 method.sig.output()
570             }
571             Err(()) => {
572                 let actual = self.resolve_type_vars_if_possible(&operand_ty);
573                 if !actual.references_error() {
574                     let mut err = struct_span_err!(self.tcx.sess, ex.span, E0600,
575                                      "cannot apply unary operator `{}` to type `{}`",
576                                      op.as_str(), actual);
577                     err.span_label(ex.span, format!("cannot apply unary \
578                                                     operator `{}`", op.as_str()));
579                     match actual.sty {
580                         Uint(_) if op == hir::UnNeg => {
581                             err.note("unsigned values cannot be negated");
582                         },
583                         Str | Never | Char | Tuple(_) | Array(_,_) => {},
584                         Ref(_, ref lty, _) if lty.sty == Str => {},
585                         _ => {
586                             let missing_trait = match op {
587                                 hir::UnNeg => "std::ops::Neg",
588                                 hir::UnNot => "std::ops::Not",
589                                 hir::UnDeref => "std::ops::UnDerf"
590                             };
591                             err.note(&format!("an implementation of `{}` might \
592                                                 be missing for `{}`",
593                                              missing_trait, operand_ty));
594                         }
595                     }
596                     err.emit();
597                 }
598                 self.tcx.types.err
599             }
600         }
601     }
602
603     fn lookup_op_method(&self, lhs_ty: Ty<'tcx>, other_tys: &[Ty<'tcx>], op: Op)
604                         -> Result<MethodCallee<'tcx>, ()>
605     {
606         let lang = self.tcx.lang_items();
607
608         let span = match op {
609             Op::Binary(op, _) => op.span,
610             Op::Unary(_, span) => span
611         };
612         let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
613             match op.node {
614                 hir::BinOpKind::Add => ("add_assign", lang.add_assign_trait()),
615                 hir::BinOpKind::Sub => ("sub_assign", lang.sub_assign_trait()),
616                 hir::BinOpKind::Mul => ("mul_assign", lang.mul_assign_trait()),
617                 hir::BinOpKind::Div => ("div_assign", lang.div_assign_trait()),
618                 hir::BinOpKind::Rem => ("rem_assign", lang.rem_assign_trait()),
619                 hir::BinOpKind::BitXor => ("bitxor_assign", lang.bitxor_assign_trait()),
620                 hir::BinOpKind::BitAnd => ("bitand_assign", lang.bitand_assign_trait()),
621                 hir::BinOpKind::BitOr => ("bitor_assign", lang.bitor_assign_trait()),
622                 hir::BinOpKind::Shl => ("shl_assign", lang.shl_assign_trait()),
623                 hir::BinOpKind::Shr => ("shr_assign", lang.shr_assign_trait()),
624                 hir::BinOpKind::Lt | hir::BinOpKind::Le |
625                 hir::BinOpKind::Ge | hir::BinOpKind::Gt |
626                 hir::BinOpKind::Eq | hir::BinOpKind::Ne |
627                 hir::BinOpKind::And | hir::BinOpKind::Or => {
628                     span_bug!(span,
629                               "impossible assignment operation: {}=",
630                               op.node.as_str())
631                 }
632             }
633         } else if let Op::Binary(op, IsAssign::No) = op {
634             match op.node {
635                 hir::BinOpKind::Add => ("add", lang.add_trait()),
636                 hir::BinOpKind::Sub => ("sub", lang.sub_trait()),
637                 hir::BinOpKind::Mul => ("mul", lang.mul_trait()),
638                 hir::BinOpKind::Div => ("div", lang.div_trait()),
639                 hir::BinOpKind::Rem => ("rem", lang.rem_trait()),
640                 hir::BinOpKind::BitXor => ("bitxor", lang.bitxor_trait()),
641                 hir::BinOpKind::BitAnd => ("bitand", lang.bitand_trait()),
642                 hir::BinOpKind::BitOr => ("bitor", lang.bitor_trait()),
643                 hir::BinOpKind::Shl => ("shl", lang.shl_trait()),
644                 hir::BinOpKind::Shr => ("shr", lang.shr_trait()),
645                 hir::BinOpKind::Lt => ("lt", lang.partial_ord_trait()),
646                 hir::BinOpKind::Le => ("le", lang.partial_ord_trait()),
647                 hir::BinOpKind::Ge => ("ge", lang.partial_ord_trait()),
648                 hir::BinOpKind::Gt => ("gt", lang.partial_ord_trait()),
649                 hir::BinOpKind::Eq => ("eq", lang.eq_trait()),
650                 hir::BinOpKind::Ne => ("ne", lang.eq_trait()),
651                 hir::BinOpKind::And | hir::BinOpKind::Or => {
652                     span_bug!(span, "&& and || are not overloadable")
653                 }
654             }
655         } else if let Op::Unary(hir::UnNot, _) = op {
656             ("not", lang.not_trait())
657         } else if let Op::Unary(hir::UnNeg, _) = op {
658             ("neg", lang.neg_trait())
659         } else {
660             bug!("lookup_op_method: op not supported: {:?}", op)
661         };
662
663         debug!("lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
664                lhs_ty,
665                op,
666                opname,
667                trait_did);
668
669         let method = trait_did.and_then(|trait_did| {
670             let opname = Ident::from_str(opname);
671             self.lookup_method_in_trait(span, opname, trait_did, lhs_ty, Some(other_tys))
672         });
673
674         match method {
675             Some(ok) => {
676                 let method = self.register_infer_ok_obligations(ok);
677                 self.select_obligations_where_possible(false);
678
679                 Ok(method)
680             }
681             None => {
682                 Err(())
683             }
684         }
685     }
686 }
687
688 // Binary operator categories. These categories summarize the behavior
689 // with respect to the builtin operationrs supported.
690 enum BinOpCategory {
691     /// &&, || -- cannot be overridden
692     Shortcircuit,
693
694     /// <<, >> -- when shifting a single integer, rhs can be any
695     /// integer type. For simd, types must match.
696     Shift,
697
698     /// +, -, etc -- takes equal types, produces same type as input,
699     /// applicable to ints/floats/simd
700     Math,
701
702     /// &, |, ^ -- takes equal types, produces same type as input,
703     /// applicable to ints/floats/simd/bool
704     Bitwise,
705
706     /// ==, !=, etc -- takes equal types, produces bools, except for simd,
707     /// which produce the input type
708     Comparison,
709 }
710
711 impl BinOpCategory {
712     fn from(op: hir::BinOp) -> BinOpCategory {
713         match op.node {
714             hir::BinOpKind::Shl | hir::BinOpKind::Shr =>
715                 BinOpCategory::Shift,
716
717             hir::BinOpKind::Add |
718             hir::BinOpKind::Sub |
719             hir::BinOpKind::Mul |
720             hir::BinOpKind::Div |
721             hir::BinOpKind::Rem =>
722                 BinOpCategory::Math,
723
724             hir::BinOpKind::BitXor |
725             hir::BinOpKind::BitAnd |
726             hir::BinOpKind::BitOr =>
727                 BinOpCategory::Bitwise,
728
729             hir::BinOpKind::Eq |
730             hir::BinOpKind::Ne |
731             hir::BinOpKind::Lt |
732             hir::BinOpKind::Le |
733             hir::BinOpKind::Ge |
734             hir::BinOpKind::Gt =>
735                 BinOpCategory::Comparison,
736
737             hir::BinOpKind::And |
738             hir::BinOpKind::Or =>
739                 BinOpCategory::Shortcircuit,
740         }
741     }
742 }
743
744 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
745 #[derive(Clone, Copy, Debug, PartialEq)]
746 enum IsAssign {
747     No,
748     Yes,
749 }
750
751 #[derive(Clone, Copy, Debug)]
752 enum Op {
753     Binary(hir::BinOp, IsAssign),
754     Unary(hir::UnOp, Span),
755 }
756
757 /// Returns `true` if this is a built-in arithmetic operation (e.g., u32
758 /// + u32, i16x4 == i16x4) and false if these types would have to be
759 /// overloaded to be legal. There are two reasons that we distinguish
760 /// builtin operations from overloaded ones (vs trying to drive
761 /// everything uniformly through the trait system and intrinsics or
762 /// something like that):
763 ///
764 /// 1. Builtin operations can trivially be evaluated in constants.
765 /// 2. For comparison operators applied to SIMD types the result is
766 ///    not of type `bool`. For example, `i16x4 == i16x4` yields a
767 ///    type like `i16x4`. This means that the overloaded trait
768 ///    `PartialEq` is not applicable.
769 ///
770 /// Reason #2 is the killer. I tried for a while to always use
771 /// overloaded logic and just check the types in constants/codegen after
772 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
773 fn is_builtin_binop(lhs: Ty<'_>, rhs: Ty<'_>, op: hir::BinOp) -> bool {
774     match BinOpCategory::from(op) {
775         BinOpCategory::Shortcircuit => {
776             true
777         }
778
779         BinOpCategory::Shift => {
780             lhs.references_error() || rhs.references_error() ||
781                 lhs.is_integral() && rhs.is_integral()
782         }
783
784         BinOpCategory::Math => {
785             lhs.references_error() || rhs.references_error() ||
786                 lhs.is_integral() && rhs.is_integral() ||
787                 lhs.is_floating_point() && rhs.is_floating_point()
788         }
789
790         BinOpCategory::Bitwise => {
791             lhs.references_error() || rhs.references_error() ||
792                 lhs.is_integral() && rhs.is_integral() ||
793                 lhs.is_floating_point() && rhs.is_floating_point() ||
794                 lhs.is_bool() && rhs.is_bool()
795         }
796
797         BinOpCategory::Comparison => {
798             lhs.references_error() || rhs.references_error() ||
799                 lhs.is_scalar() && rhs.is_scalar()
800         }
801     }
802 }