1 //! Code related to processing overloaded binary and unary operators.
3 use super::method::MethodCallee;
4 use super::{has_expected_num_generic_args, FnCtxt};
6 use rustc_errors::{self, struct_span_err, Applicability, Diagnostic};
8 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
9 use rustc_middle::ty::adjustment::{
10 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
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,
17 use rustc_span::source_map::Spanned;
18 use rustc_span::symbol::{sym, Ident};
20 use rustc_trait_selection::infer::InferCtxtExt;
21 use rustc_trait_selection::traits::{FulfillmentError, TraitEngine, TraitEngineExt};
23 use std::ops::ControlFlow;
25 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
26 /// Checks a `a <op>= b`
27 pub fn check_binop_assign(
29 expr: &'tcx hir::Expr<'tcx>,
31 lhs: &'tcx hir::Expr<'tcx>,
32 rhs: &'tcx hir::Expr<'tcx>,
34 let (lhs_ty, rhs_ty, return_ty) =
35 self.check_overloaded_binop(expr, lhs, rhs, op, IsAssign::Yes);
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);
45 self.check_lhs_assignable(lhs, "E0067", op.span);
50 /// Checks a potentially overloaded binary operator.
53 expr: &'tcx hir::Expr<'tcx>,
55 lhs_expr: &'tcx hir::Expr<'tcx>,
56 rhs_expr: &'tcx hir::Expr<'tcx>,
61 "check_binop(expr.hir_id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
62 expr.hir_id, expr, op, lhs_expr, rhs_expr
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);
72 // Depending on the LHS' value, the RHS can never execute.
73 self.diverges.set(lhs_diverges);
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);
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.
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)
100 let builtin_return_ty = self.enforce_builtin_binop_types(
107 self.demand_suptype(expr.span, builtin_return_ty, return_ty);
115 fn enforce_builtin_binop_types(
123 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
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));
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);
137 BinOpCategory::Shift => {
138 // result type is same as LHS always
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);
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);
156 fn check_overloaded_binop(
158 expr: &'tcx hir::Expr<'tcx>,
159 lhs_expr: &'tcx hir::Expr<'tcx>,
160 rhs_expr: &'tcx hir::Expr<'tcx>,
163 ) -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>) {
165 "check_overloaded_binop(expr.hir_id={}, op={:?}, is_assign={:?})",
166 expr.hir_id, op, is_assign
169 let lhs_ty = match is_assign {
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,
181 self.demand_coerce(lhs_expr, lhs_ty, fresh_var, Some(rhs_expr), AllowTwoPhase::No)
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)
191 let lhs_ty = self.resolve_vars_with_obligations(lhs_ty);
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,
204 let result = self.lookup_op_method(
208 Op::Binary(op, is_assign),
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);
215 let return_ty = match result {
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,
228 let autoref = Adjustment {
229 kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
230 target: method.sig.inputs()[0],
232 self.apply_adjustments(lhs_expr, vec![autoref]);
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,
245 let autoref = Adjustment {
246 kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
247 target: method.sig.inputs()[1],
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]);
256 .entry(rhs_expr.hir_id)
261 self.write_method_call(expr.hir_id, method);
265 // error types are considered "builtin"
266 Err(_) if lhs_ty.references_error() || rhs_ty.references_error() => self.tcx.ty_error(),
268 let source_map = self.tcx.sess.source_map();
269 let (mut err, missing_trait, use_output) = match is_assign {
271 let mut err = struct_span_err!(
275 "binary assignment operation `{}=` cannot be applied to type `{}`",
281 format!("cannot use `{}=` on type `{}`", op.node.as_str(), lhs_ty),
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"),
296 self.note_unmet_impls_on_type(&mut err, errors);
297 (err, missing_trait, false)
300 let (message, missing_trait, use_output) = match op.node {
301 hir::BinOpKind::Add => (
302 format!("cannot add `{rhs_ty}` to `{lhs_ty}`"),
303 Some("std::ops::Add"),
306 hir::BinOpKind::Sub => (
307 format!("cannot subtract `{rhs_ty}` from `{lhs_ty}`"),
308 Some("std::ops::Sub"),
311 hir::BinOpKind::Mul => (
312 format!("cannot multiply `{lhs_ty}` by `{rhs_ty}`"),
313 Some("std::ops::Mul"),
316 hir::BinOpKind::Div => (
317 format!("cannot divide `{lhs_ty}` by `{rhs_ty}`"),
318 Some("std::ops::Div"),
321 hir::BinOpKind::Rem => (
322 format!("cannot mod `{lhs_ty}` by `{rhs_ty}`"),
323 Some("std::ops::Rem"),
326 hir::BinOpKind::BitAnd => (
327 format!("no implementation for `{lhs_ty} & {rhs_ty}`"),
328 Some("std::ops::BitAnd"),
331 hir::BinOpKind::BitXor => (
332 format!("no implementation for `{lhs_ty} ^ {rhs_ty}`"),
333 Some("std::ops::BitXor"),
336 hir::BinOpKind::BitOr => (
337 format!("no implementation for `{lhs_ty} | {rhs_ty}`"),
338 Some("std::ops::BitOr"),
341 hir::BinOpKind::Shl => (
342 format!("no implementation for `{lhs_ty} << {rhs_ty}`"),
343 Some("std::ops::Shl"),
346 hir::BinOpKind::Shr => (
347 format!("no implementation for `{lhs_ty} >> {rhs_ty}`"),
348 Some("std::ops::Shr"),
351 hir::BinOpKind::Eq | hir::BinOpKind::Ne => (
353 "binary operation `{}` cannot be applied to type `{}`",
357 Some("std::cmp::PartialEq"),
363 | hir::BinOpKind::Ge => (
365 "binary operation `{}` cannot be applied to type `{}`",
369 Some("std::cmp::PartialOrd"),
374 "binary operation `{}` cannot be applied to type `{}`",
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(
394 self.add_type_neq_err_label(
404 self.note_unmet_impls_on_type(&mut err, errors);
405 (err, missing_trait, use_output)
408 if let Ref(_, rty, _) = lhs_ty.kind() {
409 if self.infcx.type_is_copy_modulo_regions(self.param_env, *rty, lhs_expr.span)
415 Op::Binary(op, is_assign),
419 if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
421 "`{}{}` can be used on `{}`, you can dereference `{}`",
424 IsAssign::Yes => "=",
430 err.span_suggestion_verbose(
431 lhs_expr.span.shrink_to_lo(),
434 rustc_errors::Applicability::MachineApplicable,
439 if let Some(missing_trait) = missing_trait {
440 let mut visitor = TypeParamVisitor(vec![]);
441 visitor.visit_ty(lhs_ty);
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,
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
459 eraser.fold_ty(lhs_ty),
460 Some(eraser.fold_ty(rhs_ty)),
462 Op::Binary(op, is_assign),
466 suggest_constraining_param(
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.
480 "the trait `{missing_trait}` is not implemented for `{lhs_ty}`"
484 bug!("type param visitor stored a non type param: {:?}", ty.kind());
493 (lhs_ty, rhs_ty, return_ty)
496 /// If one of the types is an uncalled function and calling it would yield the other type,
497 /// suggest calling the function. Returns `true` if suggestion would apply (even if not given).
498 fn add_type_neq_err_label(
500 err: &mut Diagnostic,
504 other_expr: &'tcx hir::Expr<'tcx>,
507 ) -> bool /* did we suggest to call a function because of missing parentheses? */ {
508 err.span_label(span, ty.to_string());
509 if let FnDef(def_id, _) = *ty.kind() {
510 if !self.tcx.has_typeck_results(def_id) {
513 // FIXME: Instead of exiting early when encountering bound vars in
514 // the function signature, consider keeping the binder here and
515 // propagating it downwards.
516 let Some(fn_sig) = self.tcx.fn_sig(def_id).no_bound_vars() else {
520 let other_ty = if let FnDef(def_id, _) = *other_ty.kind() {
521 if !self.tcx.has_typeck_results(def_id) {
524 // We're emitting a suggestion, so we can just ignore regions
525 self.tcx.fn_sig(def_id).skip_binder().output()
535 Op::Binary(op, is_assign),
539 let (variable_snippet, applicability) = if !fn_sig.inputs().is_empty() {
540 ("( /* arguments */ )".to_string(), Applicability::HasPlaceholders)
542 ("()".to_string(), Applicability::MaybeIncorrect)
545 err.span_suggestion_verbose(
547 "you might have forgotten to call this function",
557 /// Provide actionable suggestions when trying to add two strings with incorrect types,
558 /// like `&str + &str`, `String + String` and `&str + &String`.
560 /// If this function returns `true` it means a note was printed, so we don't need
561 /// to print the normal "implementation of `std::ops::Add` might be missing" note
562 fn check_str_addition(
564 lhs_expr: &'tcx hir::Expr<'tcx>,
565 rhs_expr: &'tcx hir::Expr<'tcx>,
568 err: &mut Diagnostic,
572 let str_concat_note = "string concatenation requires an owned `String` on the left";
573 let rm_borrow_msg = "remove the borrow to obtain an owned `String`";
574 let to_owned_msg = "create an owned `String` from a string reference";
576 let string_type = self.tcx.get_diagnostic_item(sym::String);
577 let is_std_string = |ty: Ty<'tcx>| match ty.ty_adt_def() {
578 Some(ty_def) => Some(ty_def.did()) == string_type,
582 match (lhs_ty.kind(), rhs_ty.kind()) {
583 (&Ref(_, l_ty, _), &Ref(_, r_ty, _)) // &str or &String + &str, &String or &&str
584 if (*l_ty.kind() == Str || is_std_string(l_ty)) && (
585 *r_ty.kind() == Str || is_std_string(r_ty) ||
586 &format!("{:?}", rhs_ty) == "&&str"
589 if let IsAssign::No = is_assign { // Do not supply this message if `&str += &str`
590 err.span_label(op.span, "`+` cannot be used to concatenate two `&str` strings");
591 err.note(str_concat_note);
592 if let hir::ExprKind::AddrOf(_, _, lhs_inner_expr) = lhs_expr.kind {
593 err.span_suggestion_verbose(
594 lhs_expr.span.until(lhs_inner_expr.span),
597 Applicability::MachineApplicable
600 err.span_suggestion_verbose(
601 lhs_expr.span.shrink_to_hi(),
603 ".to_owned()".to_owned(),
604 Applicability::MachineApplicable
610 (&Ref(_, l_ty, _), &Adt(..)) // Handle `&str` & `&String` + `String`
611 if (*l_ty.kind() == Str || is_std_string(l_ty)) && is_std_string(rhs_ty) =>
615 "`+` cannot be used to concatenate a `&str` with a `String`",
620 let lhs_sugg = if let hir::ExprKind::AddrOf(_, _, lhs_inner_expr) = lhs_expr.kind {
621 sugg_msg = "remove the borrow on the left and add one on the right";
622 (lhs_expr.span.until(lhs_inner_expr.span), "".to_owned())
624 sugg_msg = "create an owned `String` on the left and add a borrow on the right";
625 (lhs_expr.span.shrink_to_hi(), ".to_owned()".to_owned())
627 let suggestions = vec![
629 (rhs_expr.span.shrink_to_lo(), "&".to_owned()),
631 err.multipart_suggestion_verbose(
634 Applicability::MachineApplicable,
638 err.note(str_concat_note);
647 pub fn check_user_unop(
649 ex: &'tcx hir::Expr<'tcx>,
650 operand_ty: Ty<'tcx>,
653 assert!(op.is_by_value());
654 match self.lookup_op_method(operand_ty, None, None, Op::Unary(op, ex.span)) {
656 self.write_method_call(ex.hir_id, method);
660 let actual = self.resolve_vars_if_possible(operand_ty);
661 if !actual.references_error() {
662 let mut err = struct_span_err!(
666 "cannot apply unary operator `{}` to type `{}`",
672 format!("cannot apply unary operator `{}`", op.as_str()),
674 let missing_trait = match op {
675 hir::UnOp::Deref => unreachable!("check unary op `-` or `!` only"),
676 hir::UnOp::Not => "std::ops::Not",
677 hir::UnOp::Neg => "std::ops::Neg",
679 let mut visitor = TypeParamVisitor(vec![]);
680 visitor.visit_ty(operand_ty);
681 if let [ty] = &visitor.0[..] && let ty::Param(p) = *operand_ty.kind() {
682 suggest_constraining_param(
694 let sp = self.tcx.sess.source_map().start_point(ex.span);
696 self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
698 // If the previous expression was a block expression, suggest parentheses
699 // (turning this into a binary subtraction operation instead.)
700 // for example, `{2} - 2` -> `({2}) - 2` (see src\test\ui\parser\expr-as-stmt.rs)
701 self.tcx.sess.parse_sess.expr_parentheses_needed(&mut err, *sp);
703 match actual.kind() {
704 Uint(_) if op == hir::UnOp::Neg => {
705 err.note("unsigned values cannot be negated");
707 if let hir::ExprKind::Unary(
711 hir::ExprKind::Lit(Spanned {
712 node: ast::LitKind::Int(1, _),
722 "you may have meant the maximum value of `{actual}`",
724 format!("{actual}::MAX"),
725 Applicability::MaybeIncorrect,
729 Str | Never | Char | Tuple(_) | Array(_, _) => {}
730 Ref(_, lty, _) if *lty.kind() == Str => {}
732 self.note_unmet_impls_on_type(&mut err, errors);
746 other_ty: Option<Ty<'tcx>>,
747 other_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
749 ) -> Result<MethodCallee<'tcx>, Vec<FulfillmentError<'tcx>>> {
750 let lang = self.tcx.lang_items();
752 let span = match op {
753 Op::Binary(op, _) => op.span,
754 Op::Unary(_, span) => span,
756 let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
758 hir::BinOpKind::Add => (sym::add_assign, lang.add_assign_trait()),
759 hir::BinOpKind::Sub => (sym::sub_assign, lang.sub_assign_trait()),
760 hir::BinOpKind::Mul => (sym::mul_assign, lang.mul_assign_trait()),
761 hir::BinOpKind::Div => (sym::div_assign, lang.div_assign_trait()),
762 hir::BinOpKind::Rem => (sym::rem_assign, lang.rem_assign_trait()),
763 hir::BinOpKind::BitXor => (sym::bitxor_assign, lang.bitxor_assign_trait()),
764 hir::BinOpKind::BitAnd => (sym::bitand_assign, lang.bitand_assign_trait()),
765 hir::BinOpKind::BitOr => (sym::bitor_assign, lang.bitor_assign_trait()),
766 hir::BinOpKind::Shl => (sym::shl_assign, lang.shl_assign_trait()),
767 hir::BinOpKind::Shr => (sym::shr_assign, lang.shr_assign_trait()),
774 | hir::BinOpKind::And
775 | hir::BinOpKind::Or => {
776 span_bug!(span, "impossible assignment operation: {}=", op.node.as_str())
779 } else if let Op::Binary(op, IsAssign::No) = op {
781 hir::BinOpKind::Add => (sym::add, lang.add_trait()),
782 hir::BinOpKind::Sub => (sym::sub, lang.sub_trait()),
783 hir::BinOpKind::Mul => (sym::mul, lang.mul_trait()),
784 hir::BinOpKind::Div => (sym::div, lang.div_trait()),
785 hir::BinOpKind::Rem => (sym::rem, lang.rem_trait()),
786 hir::BinOpKind::BitXor => (sym::bitxor, lang.bitxor_trait()),
787 hir::BinOpKind::BitAnd => (sym::bitand, lang.bitand_trait()),
788 hir::BinOpKind::BitOr => (sym::bitor, lang.bitor_trait()),
789 hir::BinOpKind::Shl => (sym::shl, lang.shl_trait()),
790 hir::BinOpKind::Shr => (sym::shr, lang.shr_trait()),
791 hir::BinOpKind::Lt => (sym::lt, lang.partial_ord_trait()),
792 hir::BinOpKind::Le => (sym::le, lang.partial_ord_trait()),
793 hir::BinOpKind::Ge => (sym::ge, lang.partial_ord_trait()),
794 hir::BinOpKind::Gt => (sym::gt, lang.partial_ord_trait()),
795 hir::BinOpKind::Eq => (sym::eq, lang.eq_trait()),
796 hir::BinOpKind::Ne => (sym::ne, lang.eq_trait()),
797 hir::BinOpKind::And | hir::BinOpKind::Or => {
798 span_bug!(span, "&& and || are not overloadable")
801 } else if let Op::Unary(hir::UnOp::Not, _) = op {
802 (sym::not, lang.not_trait())
803 } else if let Op::Unary(hir::UnOp::Neg, _) = op {
804 (sym::neg, lang.neg_trait())
806 bug!("lookup_op_method: op not supported: {:?}", op)
810 "lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
811 lhs_ty, op, opname, trait_did
814 // Catches cases like #83893, where a lang item is declared with the
815 // wrong number of generic arguments. Should have yielded an error
816 // elsewhere by now, but we have to catch it here so that we do not
817 // index `other_tys` out of bounds (if the lang item has too many
818 // generic arguments, `other_tys` is too short).
819 if !has_expected_num_generic_args(
823 // Binary ops have a generic right-hand side, unary ops don't
831 let opname = Ident::with_dummy_span(opname);
832 let method = trait_did.and_then(|trait_did| {
833 self.lookup_op_method_in_trait(span, opname, trait_did, lhs_ty, other_ty, other_ty_expr)
836 match (method, trait_did) {
838 let method = self.register_infer_ok_obligations(ok);
839 self.select_obligations_where_possible(false, |_| {});
842 (None, None) => Err(vec![]),
843 (None, Some(trait_did)) => {
844 let (obligation, _) =
845 self.obligation_for_op_method(span, trait_did, lhs_ty, other_ty, other_ty_expr);
846 let mut fulfill = <dyn TraitEngine<'_>>::new(self.tcx);
847 fulfill.register_predicate_obligation(self, obligation);
848 Err(fulfill.select_where_possible(&self.infcx))
854 // Binary operator categories. These categories summarize the behavior
855 // with respect to the builtin operations supported.
857 /// &&, || -- cannot be overridden
860 /// <<, >> -- when shifting a single integer, rhs can be any
861 /// integer type. For simd, types must match.
864 /// +, -, etc -- takes equal types, produces same type as input,
865 /// applicable to ints/floats/simd
868 /// &, |, ^ -- takes equal types, produces same type as input,
869 /// applicable to ints/floats/simd/bool
872 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
873 /// which produce the input type
878 fn from(op: hir::BinOp) -> BinOpCategory {
880 hir::BinOpKind::Shl | hir::BinOpKind::Shr => BinOpCategory::Shift,
883 | hir::BinOpKind::Sub
884 | hir::BinOpKind::Mul
885 | hir::BinOpKind::Div
886 | hir::BinOpKind::Rem => BinOpCategory::Math,
888 hir::BinOpKind::BitXor | hir::BinOpKind::BitAnd | hir::BinOpKind::BitOr => {
889 BinOpCategory::Bitwise
897 | hir::BinOpKind::Gt => BinOpCategory::Comparison,
899 hir::BinOpKind::And | hir::BinOpKind::Or => BinOpCategory::Shortcircuit,
904 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
905 #[derive(Clone, Copy, Debug, PartialEq)]
911 #[derive(Clone, Copy, Debug)]
913 Binary(hir::BinOp, IsAssign),
914 Unary(hir::UnOp, Span),
917 /// Dereferences a single level of immutable referencing.
918 fn deref_ty_if_possible<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
920 ty::Ref(_, ty, hir::Mutability::Not) => *ty,
925 /// Returns `true` if this is a built-in arithmetic operation (e.g., u32
926 /// + u32, i16x4 == i16x4) and false if these types would have to be
927 /// overloaded to be legal. There are two reasons that we distinguish
928 /// builtin operations from overloaded ones (vs trying to drive
929 /// everything uniformly through the trait system and intrinsics or
930 /// something like that):
932 /// 1. Builtin operations can trivially be evaluated in constants.
933 /// 2. For comparison operators applied to SIMD types the result is
934 /// not of type `bool`. For example, `i16x4 == i16x4` yields a
935 /// type like `i16x4`. This means that the overloaded trait
936 /// `PartialEq` is not applicable.
938 /// Reason #2 is the killer. I tried for a while to always use
939 /// overloaded logic and just check the types in constants/codegen after
940 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
941 fn is_builtin_binop<'tcx>(lhs: Ty<'tcx>, rhs: Ty<'tcx>, op: hir::BinOp) -> bool {
942 // Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
943 // (See https://github.com/rust-lang/rust/issues/57447.)
944 let (lhs, rhs) = (deref_ty_if_possible(lhs), deref_ty_if_possible(rhs));
946 match BinOpCategory::from(op) {
947 BinOpCategory::Shortcircuit => true,
949 BinOpCategory::Shift => {
950 lhs.references_error()
951 || rhs.references_error()
952 || lhs.is_integral() && rhs.is_integral()
955 BinOpCategory::Math => {
956 lhs.references_error()
957 || rhs.references_error()
958 || lhs.is_integral() && rhs.is_integral()
959 || lhs.is_floating_point() && rhs.is_floating_point()
962 BinOpCategory::Bitwise => {
963 lhs.references_error()
964 || rhs.references_error()
965 || lhs.is_integral() && rhs.is_integral()
966 || lhs.is_floating_point() && rhs.is_floating_point()
967 || lhs.is_bool() && rhs.is_bool()
970 BinOpCategory::Comparison => {
971 lhs.references_error() || rhs.references_error() || lhs.is_scalar() && rhs.is_scalar()
976 fn suggest_constraining_param(
979 mut err: &mut Diagnostic,
987 let msg = &format!("`{lhs_ty}` might need a bound for `{missing_trait}`");
988 // Try to find the def-id and details for the parameter p. We have only the index,
989 // so we have to find the enclosing function's def-id, then look through its declared
990 // generic parameters to get the declaration.
991 let def_id = hir.body_owner_def_id(hir::BodyId { hir_id: body_id });
992 let generics = tcx.generics_of(def_id);
993 let param_def_id = generics.type_param(&p, tcx).def_id;
994 if let Some(generics) = param_def_id
996 .map(|id| hir.local_def_id_to_hir_id(id))
997 .and_then(|id| hir.find_by_def_id(hir.get_parent_item(id)))
999 .and_then(|node| node.generics())
1001 let output = if set_output { format!("<Output = {rhs_ty}>") } else { String::new() };
1002 suggest_constraining_type_param(
1006 &lhs_ty.to_string(),
1007 &format!("{missing_trait}{output}"),
1011 let span = tcx.def_span(param_def_id);
1012 err.span_label(span, msg);
1016 struct TypeParamVisitor<'tcx>(Vec<Ty<'tcx>>);
1018 impl<'tcx> TypeVisitor<'tcx> for TypeParamVisitor<'tcx> {
1019 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1020 if let ty::Param(_) = ty.kind() {
1023 ty.super_visit_with(self)
1027 struct TypeParamEraser<'a, 'tcx>(&'a FnCtxt<'a, 'tcx>, Span);
1029 impl<'tcx> TypeFolder<'tcx> for TypeParamEraser<'_, 'tcx> {
1030 fn tcx(&self) -> TyCtxt<'tcx> {
1034 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1036 ty::Param(_) => self.0.next_ty_var(TypeVariableOrigin {
1037 kind: TypeVariableOriginKind::MiscVariable,
1040 _ => ty.super_fold_with(self),