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::{self, Ty, TyCtxt, TypeFoldable, TypeVisitor};
15 use rustc_span::source_map::Spanned;
16 use rustc_span::symbol::{sym, Ident};
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};
22 use std::ops::ControlFlow;
24 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25 /// Checks a `a <op>= b`
26 pub fn check_binop_assign(
28 expr: &'tcx hir::Expr<'tcx>,
30 lhs: &'tcx hir::Expr<'tcx>,
31 rhs: &'tcx hir::Expr<'tcx>,
33 let (lhs_ty, rhs_ty, return_ty) =
34 self.check_overloaded_binop(expr, lhs, rhs, op, IsAssign::Yes);
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);
44 self.check_lhs_assignable(lhs, "E0067", op.span);
49 /// Checks a potentially overloaded binary operator.
52 expr: &'tcx hir::Expr<'tcx>,
54 lhs_expr: &'tcx hir::Expr<'tcx>,
55 rhs_expr: &'tcx hir::Expr<'tcx>,
60 "check_binop(expr.hir_id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
61 expr.hir_id, expr, op, lhs_expr, rhs_expr
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);
71 // Depending on the LHS' value, the RHS can never execute.
72 self.diverges.set(lhs_diverges);
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);
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.
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)
99 let builtin_return_ty = self.enforce_builtin_binop_types(
106 self.demand_suptype(expr.span, builtin_return_ty, return_ty);
114 fn enforce_builtin_binop_types(
122 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
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));
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);
136 BinOpCategory::Shift => {
137 // result type is same as LHS always
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);
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);
155 fn check_overloaded_binop(
157 expr: &'tcx hir::Expr<'tcx>,
158 lhs_expr: &'tcx hir::Expr<'tcx>,
159 rhs_expr: &'tcx hir::Expr<'tcx>,
162 ) -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>) {
164 "check_overloaded_binop(expr.hir_id={}, op={:?}, is_assign={:?})",
165 expr.hir_id, op, is_assign
168 let lhs_ty = match is_assign {
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,
180 self.demand_coerce(lhs_expr, lhs_ty, fresh_var, Some(rhs_expr), AllowTwoPhase::No)
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)
190 let lhs_ty = self.resolve_vars_with_obligations(lhs_ty);
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,
203 let result = self.lookup_op_method(
207 Op::Binary(op, is_assign),
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);
214 let return_ty = match result {
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,
227 let autoref = Adjustment {
228 kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
229 target: method.sig.inputs()[0],
231 self.apply_adjustments(lhs_expr, vec![autoref]);
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,
244 let autoref = Adjustment {
245 kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
246 target: method.sig.inputs()[1],
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]);
255 .entry(rhs_expr.hir_id)
260 self.write_method_call(expr.hir_id, method);
264 // error types are considered "builtin"
265 Err(_) if lhs_ty.references_error() || rhs_ty.references_error() => self.tcx.ty_error(),
267 let source_map = self.tcx.sess.source_map();
268 let (mut err, missing_trait, _use_output) = match is_assign {
270 let mut err = struct_span_err!(
274 "binary assignment operation `{}=` cannot be applied to type `{}`",
280 format!("cannot use `{}=` on type `{}`", op.node.as_str(), lhs_ty),
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"),
295 self.note_unmet_impls_on_type(&mut err, errors);
296 (err, missing_trait, false)
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"),
305 hir::BinOpKind::Sub => (
306 format!("cannot subtract `{rhs_ty}` from `{lhs_ty}`"),
307 Some("std::ops::Sub"),
310 hir::BinOpKind::Mul => (
311 format!("cannot multiply `{lhs_ty}` by `{rhs_ty}`"),
312 Some("std::ops::Mul"),
315 hir::BinOpKind::Div => (
316 format!("cannot divide `{lhs_ty}` by `{rhs_ty}`"),
317 Some("std::ops::Div"),
320 hir::BinOpKind::Rem => (
321 format!("cannot mod `{lhs_ty}` by `{rhs_ty}`"),
322 Some("std::ops::Rem"),
325 hir::BinOpKind::BitAnd => (
326 format!("no implementation for `{lhs_ty} & {rhs_ty}`"),
327 Some("std::ops::BitAnd"),
330 hir::BinOpKind::BitXor => (
331 format!("no implementation for `{lhs_ty} ^ {rhs_ty}`"),
332 Some("std::ops::BitXor"),
335 hir::BinOpKind::BitOr => (
336 format!("no implementation for `{lhs_ty} | {rhs_ty}`"),
337 Some("std::ops::BitOr"),
340 hir::BinOpKind::Shl => (
341 format!("no implementation for `{lhs_ty} << {rhs_ty}`"),
342 Some("std::ops::Shl"),
345 hir::BinOpKind::Shr => (
346 format!("no implementation for `{lhs_ty} >> {rhs_ty}`"),
347 Some("std::ops::Shr"),
350 hir::BinOpKind::Eq | hir::BinOpKind::Ne => (
352 "binary operation `{}` cannot be applied to type `{}`",
356 Some("std::cmp::PartialEq"),
362 | hir::BinOpKind::Ge => (
364 "binary operation `{}` cannot be applied to type `{}`",
368 Some("std::cmp::PartialOrd"),
373 "binary operation `{}` cannot be applied to type `{}`",
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(
393 self.add_type_neq_err_label(
403 self.note_unmet_impls_on_type(&mut err, errors);
404 (err, missing_trait, use_output)
407 if let Ref(_, rty, _) = lhs_ty.kind() {
408 if self.infcx.type_is_copy_modulo_regions(self.param_env, *rty, lhs_expr.span)
414 Op::Binary(op, is_assign),
418 if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
420 "`{}{}` can be used on `{}`, you can dereference `{}`",
423 IsAssign::Yes => "=",
429 err.span_suggestion_verbose(
430 lhs_expr.span.shrink_to_lo(),
433 rustc_errors::Applicability::MachineApplicable,
438 if let Some(missing_trait) = missing_trait {
439 let mut visitor = TypeParamVisitor(vec![]);
440 visitor.visit_ty(lhs_ty);
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,
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.
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.
463 Op::Binary(op, is_assign),
466 let predicates = errors
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(
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.
482 "the trait `{missing_trait}` is not implemented for `{lhs_ty}`"
492 (lhs_ty, rhs_ty, return_ty)
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(
499 err: &mut Diagnostic,
503 other_expr: &'tcx hir::Expr<'tcx>,
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) {
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 {
519 let other_ty = if let FnDef(def_id, _) = *other_ty.kind() {
520 if !self.tcx.has_typeck_results(def_id) {
523 // We're emitting a suggestion, so we can just ignore regions
524 self.tcx.fn_sig(def_id).skip_binder().output()
534 Op::Binary(op, is_assign),
538 let (variable_snippet, applicability) = if !fn_sig.inputs().is_empty() {
539 ("( /* arguments */ )".to_string(), Applicability::HasPlaceholders)
541 ("()".to_string(), Applicability::MaybeIncorrect)
544 err.span_suggestion_verbose(
546 "you might have forgotten to call this function",
556 /// Provide actionable suggestions when trying to add two strings with incorrect types,
557 /// like `&str + &str`, `String + String` and `&str + &String`.
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(
563 lhs_expr: &'tcx hir::Expr<'tcx>,
564 rhs_expr: &'tcx hir::Expr<'tcx>,
567 err: &mut Diagnostic,
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";
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,
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"
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),
596 Applicability::MachineApplicable
599 err.span_suggestion_verbose(
600 lhs_expr.span.shrink_to_hi(),
602 ".to_owned()".to_owned(),
603 Applicability::MachineApplicable
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) =>
614 "`+` cannot be used to concatenate a `&str` with a `String`",
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())
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())
626 let suggestions = vec![
628 (rhs_expr.span.shrink_to_lo(), "&".to_owned()),
630 err.multipart_suggestion_verbose(
633 Applicability::MachineApplicable,
637 err.note(str_concat_note);
646 pub fn check_user_unop(
648 ex: &'tcx hir::Expr<'tcx>,
649 operand_ty: Ty<'tcx>,
652 assert!(op.is_by_value());
653 match self.lookup_op_method(operand_ty, None, None, Op::Unary(op, ex.span)) {
655 self.write_method_call(ex.hir_id, method);
659 let actual = self.resolve_vars_if_possible(operand_ty);
660 if !actual.references_error() {
661 let mut err = struct_span_err!(
665 "cannot apply unary operator `{}` to type `{}`",
671 format!("cannot apply unary operator `{}`", op.as_str()),
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
679 .filter_map(|error| {
680 error.obligation.predicate.clone().to_opt_poly_trait_pred()
682 for pred in predicates {
683 self.infcx.suggest_restricting_param_bound(
691 let sp = self.tcx.sess.source_map().start_point(ex.span);
693 self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
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);
700 match actual.kind() {
701 Uint(_) if op == hir::UnOp::Neg => {
702 err.note("unsigned values cannot be negated");
704 if let hir::ExprKind::Unary(
708 hir::ExprKind::Lit(Spanned {
709 node: ast::LitKind::Int(1, _),
719 "you may have meant the maximum value of `{actual}`",
721 format!("{actual}::MAX"),
722 Applicability::MaybeIncorrect,
726 Str | Never | Char | Tuple(_) | Array(_, _) => {}
727 Ref(_, lty, _) if *lty.kind() == Str => {}
729 self.note_unmet_impls_on_type(&mut err, errors);
743 other_ty: Option<Ty<'tcx>>,
744 other_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
746 ) -> Result<MethodCallee<'tcx>, Vec<FulfillmentError<'tcx>>> {
747 let lang = self.tcx.lang_items();
749 let span = match op {
750 Op::Binary(op, _) => op.span,
751 Op::Unary(_, span) => span,
753 let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
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()),
771 | hir::BinOpKind::And
772 | hir::BinOpKind::Or => {
773 span_bug!(span, "impossible assignment operation: {}=", op.node.as_str())
776 } else if let Op::Binary(op, IsAssign::No) = op {
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")
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())
803 bug!("lookup_op_method: op not supported: {:?}", op)
807 "lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
808 lhs_ty, op, opname, trait_did
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(
820 // Binary ops have a generic right-hand side, unary ops don't
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)
833 match (method, trait_did) {
835 let method = self.register_infer_ok_obligations(ok);
836 self.select_obligations_where_possible(false, |_| {});
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))
851 // Binary operator categories. These categories summarize the behavior
852 // with respect to the builtin operations supported.
854 /// &&, || -- cannot be overridden
857 /// <<, >> -- when shifting a single integer, rhs can be any
858 /// integer type. For simd, types must match.
861 /// +, -, etc -- takes equal types, produces same type as input,
862 /// applicable to ints/floats/simd
865 /// &, |, ^ -- takes equal types, produces same type as input,
866 /// applicable to ints/floats/simd/bool
869 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
870 /// which produce the input type
875 fn from(op: hir::BinOp) -> BinOpCategory {
877 hir::BinOpKind::Shl | hir::BinOpKind::Shr => BinOpCategory::Shift,
880 | hir::BinOpKind::Sub
881 | hir::BinOpKind::Mul
882 | hir::BinOpKind::Div
883 | hir::BinOpKind::Rem => BinOpCategory::Math,
885 hir::BinOpKind::BitXor | hir::BinOpKind::BitAnd | hir::BinOpKind::BitOr => {
886 BinOpCategory::Bitwise
894 | hir::BinOpKind::Gt => BinOpCategory::Comparison,
896 hir::BinOpKind::And | hir::BinOpKind::Or => BinOpCategory::Shortcircuit,
901 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
902 #[derive(Clone, Copy, Debug, PartialEq)]
908 #[derive(Clone, Copy, Debug)]
910 Binary(hir::BinOp, IsAssign),
911 Unary(hir::UnOp, Span),
914 /// Dereferences a single level of immutable referencing.
915 fn deref_ty_if_possible<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
917 ty::Ref(_, ty, hir::Mutability::Not) => *ty,
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):
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.
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));
943 match BinOpCategory::from(op) {
944 BinOpCategory::Shortcircuit => true,
946 BinOpCategory::Shift => {
947 lhs.references_error()
948 || rhs.references_error()
949 || lhs.is_integral() && rhs.is_integral()
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()
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()
967 BinOpCategory::Comparison => {
968 lhs.references_error() || rhs.references_error() || lhs.is_scalar() && rhs.is_scalar()
973 struct TypeParamVisitor<'tcx>(Vec<Ty<'tcx>>);
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() {
980 ty.super_visit_with(self)
984 struct TypeParamEraser<'a, 'tcx>(&'a FnCtxt<'a, 'tcx>, Span);
986 impl<'tcx> TypeFolder<'tcx> for TypeParamEraser<'_, 'tcx> {
987 fn tcx(&self) -> TyCtxt<'tcx> {
991 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
993 ty::Param(_) => self.0.next_ty_var(TypeVariableOrigin {
994 kind: TypeVariableOriginKind::MiscVariable,
997 _ => ty.super_fold_with(self),