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