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