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