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