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