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