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