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