1 //! Code related to processing overloaded binary and unary operators.
3 use super::method::MethodCallee;
4 use super::{has_expected_num_generic_args, FnCtxt};
5 use crate::check::Expectation;
7 use rustc_errors::{self, struct_span_err, Applicability, Diagnostic};
9 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
10 use rustc_infer::traits::ObligationCauseCode;
11 use rustc_middle::ty::adjustment::{
12 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
14 use rustc_middle::ty::{
15 self, Ty, TyCtxt, TypeFolder, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, 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::error_reporting::suggestions::InferCtxtExt as _;
22 use rustc_trait_selection::traits::{FulfillmentError, TraitEngine, TraitEngineExt};
23 use rustc_type_ir::sty::TyKind::*;
25 use std::ops::ControlFlow;
27 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
28 /// Checks a `a <op>= b`
29 pub fn check_binop_assign(
31 expr: &'tcx hir::Expr<'tcx>,
33 lhs: &'tcx hir::Expr<'tcx>,
34 rhs: &'tcx hir::Expr<'tcx>,
35 expected: Expectation<'tcx>,
37 let (lhs_ty, rhs_ty, return_ty) =
38 self.check_overloaded_binop(expr, lhs, rhs, op, IsAssign::Yes, expected);
41 if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() && is_builtin_binop(lhs_ty, rhs_ty, op) {
42 self.enforce_builtin_binop_types(lhs.span, lhs_ty, rhs.span, rhs_ty, op);
48 self.check_lhs_assignable(lhs, "E0067", op.span, |err| {
49 if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
55 Op::Binary(op, IsAssign::Yes),
60 // Suppress this error, since we already emitted
61 // a deref suggestion in check_overloaded_binop
62 err.downgrade_to_delayed_bug();
70 /// Checks a potentially overloaded binary operator.
73 expr: &'tcx hir::Expr<'tcx>,
75 lhs_expr: &'tcx hir::Expr<'tcx>,
76 rhs_expr: &'tcx hir::Expr<'tcx>,
77 expected: Expectation<'tcx>,
82 "check_binop(expr.hir_id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
83 expr.hir_id, expr, op, lhs_expr, rhs_expr
86 match BinOpCategory::from(op) {
87 BinOpCategory::Shortcircuit => {
88 // && and || are a simple case.
89 self.check_expr_coercable_to_type(lhs_expr, tcx.types.bool, None);
90 let lhs_diverges = self.diverges.get();
91 self.check_expr_coercable_to_type(rhs_expr, tcx.types.bool, None);
93 // Depending on the LHS' value, the RHS can never execute.
94 self.diverges.set(lhs_diverges);
99 // Otherwise, we always treat operators as if they are
100 // overloaded. This is the way to be most flexible w/r/t
101 // types that get inferred.
102 let (lhs_ty, rhs_ty, return_ty) = self.check_overloaded_binop(
111 // Supply type inference hints if relevant. Probably these
112 // hints should be enforced during select as part of the
113 // `consider_unification_despite_ambiguity` routine, but this
114 // more convenient for now.
116 // The basic idea is to help type inference by taking
117 // advantage of things we know about how the impls for
118 // scalar types are arranged. This is important in a
119 // scenario like `1_u32 << 2`, because it lets us quickly
120 // deduce that the result type should be `u32`, even
121 // though we don't know yet what type 2 has and hence
122 // can't pin this down to a specific impl.
123 if !lhs_ty.is_ty_var()
124 && !rhs_ty.is_ty_var()
125 && is_builtin_binop(lhs_ty, rhs_ty, op)
127 let builtin_return_ty = self.enforce_builtin_binop_types(
134 self.demand_suptype(expr.span, builtin_return_ty, return_ty);
142 fn enforce_builtin_binop_types(
150 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
152 // Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
153 // (See https://github.com/rust-lang/rust/issues/57447.)
154 let (lhs_ty, rhs_ty) = (deref_ty_if_possible(lhs_ty), deref_ty_if_possible(rhs_ty));
157 match BinOpCategory::from(op) {
158 BinOpCategory::Shortcircuit => {
159 self.demand_suptype(lhs_span, tcx.types.bool, lhs_ty);
160 self.demand_suptype(rhs_span, tcx.types.bool, rhs_ty);
164 BinOpCategory::Shift => {
165 // result type is same as LHS always
169 BinOpCategory::Math | BinOpCategory::Bitwise => {
170 // both LHS and RHS and result will have the same type
171 self.demand_suptype(rhs_span, lhs_ty, rhs_ty);
175 BinOpCategory::Comparison => {
176 // both LHS and RHS and result will have the same type
177 self.demand_suptype(rhs_span, lhs_ty, rhs_ty);
183 fn check_overloaded_binop(
185 expr: &'tcx hir::Expr<'tcx>,
186 lhs_expr: &'tcx hir::Expr<'tcx>,
187 rhs_expr: &'tcx hir::Expr<'tcx>,
190 expected: Expectation<'tcx>,
191 ) -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>) {
193 "check_overloaded_binop(expr.hir_id={}, op={:?}, is_assign={:?})",
194 expr.hir_id, op, is_assign
197 let lhs_ty = match is_assign {
199 // Find a suitable supertype of the LHS expression's type, by coercing to
200 // a type variable, to pass as the `Self` to the trait, avoiding invariant
201 // trait matching creating lifetime constraints that are too strict.
202 // e.g., adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
203 // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`.
204 let lhs_ty = self.check_expr(lhs_expr);
205 let fresh_var = self.next_ty_var(TypeVariableOrigin {
206 kind: TypeVariableOriginKind::MiscVariable,
209 self.demand_coerce(lhs_expr, lhs_ty, fresh_var, Some(rhs_expr), AllowTwoPhase::No)
212 // rust-lang/rust#52126: We have to use strict
213 // equivalence on the LHS of an assign-op like `+=`;
214 // overwritten or mutably-borrowed places cannot be
215 // coerced to a supertype.
216 self.check_expr(lhs_expr)
219 let lhs_ty = self.resolve_vars_with_obligations(lhs_ty);
221 // N.B., as we have not yet type-checked the RHS, we don't have the
222 // type at hand. Make a variable to represent it. The whole reason
223 // for this indirection is so that, below, we can check the expr
224 // using this variable as the expected type, which sometimes lets
225 // us do better coercions than we would be able to do otherwise,
226 // particularly for things like `String + &String`.
227 let rhs_ty_var = self.next_ty_var(TypeVariableOrigin {
228 kind: TypeVariableOriginKind::MiscVariable,
232 let result = self.lookup_op_method(
236 Op::Binary(op, is_assign),
241 let rhs_ty = self.check_expr_coercable_to_type(rhs_expr, rhs_ty_var, Some(lhs_expr));
242 let rhs_ty = self.resolve_vars_with_obligations(rhs_ty);
244 let return_ty = match result {
246 let by_ref_binop = !op.node.is_by_value();
247 if is_assign == IsAssign::Yes || by_ref_binop {
248 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind() {
249 let mutbl = match mutbl {
250 hir::Mutability::Not => AutoBorrowMutability::Not,
251 hir::Mutability::Mut => AutoBorrowMutability::Mut {
252 // Allow two-phase borrows for binops in initial deployment
253 // since they desugar to methods
254 allow_two_phase_borrow: AllowTwoPhase::Yes,
257 let autoref = Adjustment {
258 kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
259 target: method.sig.inputs()[0],
261 self.apply_adjustments(lhs_expr, vec![autoref]);
265 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[1].kind() {
266 let mutbl = match mutbl {
267 hir::Mutability::Not => AutoBorrowMutability::Not,
268 hir::Mutability::Mut => AutoBorrowMutability::Mut {
269 // Allow two-phase borrows for binops in initial deployment
270 // since they desugar to methods
271 allow_two_phase_borrow: AllowTwoPhase::Yes,
274 let autoref = Adjustment {
275 kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
276 target: method.sig.inputs()[1],
278 // HACK(eddyb) Bypass checks due to reborrows being in
279 // some cases applied on the RHS, on top of which we need
280 // to autoref, which is not allowed by apply_adjustments.
281 // self.apply_adjustments(rhs_expr, vec![autoref]);
285 .entry(rhs_expr.hir_id)
290 self.write_method_call(expr.hir_id, method);
294 // error types are considered "builtin"
295 Err(_) if lhs_ty.references_error() || rhs_ty.references_error() => self.tcx.ty_error(),
297 let source_map = self.tcx.sess.source_map();
298 let (mut err, missing_trait, use_output) = match is_assign {
300 let mut err = struct_span_err!(
304 "binary assignment operation `{}=` cannot be applied to type `{}`",
310 format!("cannot use `{}=` on type `{}`", op.node.as_str(), lhs_ty),
312 let missing_trait = match op.node {
313 hir::BinOpKind::Add => Some("std::ops::AddAssign"),
314 hir::BinOpKind::Sub => Some("std::ops::SubAssign"),
315 hir::BinOpKind::Mul => Some("std::ops::MulAssign"),
316 hir::BinOpKind::Div => Some("std::ops::DivAssign"),
317 hir::BinOpKind::Rem => Some("std::ops::RemAssign"),
318 hir::BinOpKind::BitAnd => Some("std::ops::BitAndAssign"),
319 hir::BinOpKind::BitXor => Some("std::ops::BitXorAssign"),
320 hir::BinOpKind::BitOr => Some("std::ops::BitOrAssign"),
321 hir::BinOpKind::Shl => Some("std::ops::ShlAssign"),
322 hir::BinOpKind::Shr => Some("std::ops::ShrAssign"),
325 self.note_unmet_impls_on_type(&mut err, errors);
326 (err, missing_trait, false)
329 let (message, missing_trait, use_output) = match op.node {
330 hir::BinOpKind::Add => (
331 format!("cannot add `{rhs_ty}` to `{lhs_ty}`"),
332 Some("std::ops::Add"),
335 hir::BinOpKind::Sub => (
336 format!("cannot subtract `{rhs_ty}` from `{lhs_ty}`"),
337 Some("std::ops::Sub"),
340 hir::BinOpKind::Mul => (
341 format!("cannot multiply `{lhs_ty}` by `{rhs_ty}`"),
342 Some("std::ops::Mul"),
345 hir::BinOpKind::Div => (
346 format!("cannot divide `{lhs_ty}` by `{rhs_ty}`"),
347 Some("std::ops::Div"),
350 hir::BinOpKind::Rem => (
351 format!("cannot mod `{lhs_ty}` by `{rhs_ty}`"),
352 Some("std::ops::Rem"),
355 hir::BinOpKind::BitAnd => (
356 format!("no implementation for `{lhs_ty} & {rhs_ty}`"),
357 Some("std::ops::BitAnd"),
360 hir::BinOpKind::BitXor => (
361 format!("no implementation for `{lhs_ty} ^ {rhs_ty}`"),
362 Some("std::ops::BitXor"),
365 hir::BinOpKind::BitOr => (
366 format!("no implementation for `{lhs_ty} | {rhs_ty}`"),
367 Some("std::ops::BitOr"),
370 hir::BinOpKind::Shl => (
371 format!("no implementation for `{lhs_ty} << {rhs_ty}`"),
372 Some("std::ops::Shl"),
375 hir::BinOpKind::Shr => (
376 format!("no implementation for `{lhs_ty} >> {rhs_ty}`"),
377 Some("std::ops::Shr"),
380 hir::BinOpKind::Eq | hir::BinOpKind::Ne => (
382 "binary operation `{}` cannot be applied to type `{}`",
386 Some("std::cmp::PartialEq"),
392 | hir::BinOpKind::Ge => (
394 "binary operation `{}` cannot be applied to type `{}`",
398 Some("std::cmp::PartialOrd"),
403 "binary operation `{}` cannot be applied to type `{}`",
411 let mut err = struct_span_err!(self.tcx.sess, op.span, E0369, "{message}");
412 if !lhs_expr.span.eq(&rhs_expr.span) {
413 err.span_label(lhs_expr.span, lhs_ty.to_string());
414 err.span_label(rhs_expr.span, rhs_ty.to_string());
416 self.note_unmet_impls_on_type(&mut err, errors);
417 (err, missing_trait, use_output)
421 let mut suggest_deref_binop = |lhs_deref_ty: Ty<'tcx>| {
427 Op::Binary(op, is_assign),
432 if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
434 "`{}{}` can be used on `{}`, you can dereference `{}`",
437 IsAssign::Yes => "=",
440 lhs_deref_ty.peel_refs(),
443 err.span_suggestion_verbose(
444 lhs_expr.span.shrink_to_lo(),
447 rustc_errors::Applicability::MachineApplicable,
453 let is_compatible = |lhs_ty, rhs_ty| {
454 self.lookup_op_method(
458 Op::Binary(op, is_assign),
464 // We should suggest `a + b` => `*a + b` if `a` is copy, and suggest
465 // `a += b` => `*a += b` if a is a mut ref.
466 if !op.span.can_be_used_for_suggestions() {
467 // Suppress suggestions when lhs and rhs are not in the same span as the error
468 } else if is_assign == IsAssign::Yes
469 && let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty)
471 suggest_deref_binop(lhs_deref_ty);
472 } else if is_assign == IsAssign::No
473 && let Ref(_, lhs_deref_ty, _) = lhs_ty.kind()
475 if self.type_is_copy_modulo_regions(
480 suggest_deref_binop(*lhs_deref_ty);
482 } else if self.suggest_fn_call(&mut err, lhs_expr, lhs_ty, |lhs_ty| {
483 is_compatible(lhs_ty, rhs_ty)
484 }) || self.suggest_fn_call(&mut err, rhs_expr, rhs_ty, |rhs_ty| {
485 is_compatible(lhs_ty, rhs_ty)
486 }) || self.suggest_two_fn_call(
492 |lhs_ty, rhs_ty| is_compatible(lhs_ty, rhs_ty),
497 if let Some(missing_trait) = missing_trait {
498 let mut visitor = TypeParamVisitor(vec![]);
499 visitor.visit_ty(lhs_ty);
501 if op.node == hir::BinOpKind::Add
502 && self.check_str_addition(
503 lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, is_assign, op,
506 // This has nothing here because it means we did string
507 // concatenation (e.g., "Hello " + "World!"). This means
508 // we don't want the note in the else clause to be emitted
509 } else if let [ty] = &visitor.0[..] {
510 // Look for a TraitPredicate in the Fulfillment errors,
511 // and use it to generate a suggestion.
513 // Note that lookup_op_method must be called again but
514 // with a specific rhs_ty instead of a placeholder so
515 // the resulting predicate generates a more specific
516 // suggestion for the user.
522 Op::Binary(op, is_assign),
526 if !errors.is_empty() {
527 for error in errors {
528 if let Some(trait_pred) =
529 error.obligation.predicate.to_opt_poly_trait_pred()
531 let proj_pred = match error.obligation.cause.code() {
532 ObligationCauseCode::BinOp {
533 output_pred: Some(output_pred),
536 output_pred.to_opt_poly_projection_pred()
541 self.suggest_restricting_param_bound(
549 } else if *ty != lhs_ty {
550 // When we know that a missing bound is responsible, we don't show
551 // this note as it is redundant.
553 "the trait `{missing_trait}` is not implemented for `{lhs_ty}`"
563 (lhs_ty, rhs_ty, return_ty)
566 /// Provide actionable suggestions when trying to add two strings with incorrect types,
567 /// like `&str + &str`, `String + String` and `&str + &String`.
569 /// If this function returns `true` it means a note was printed, so we don't need
570 /// to print the normal "implementation of `std::ops::Add` might be missing" note
571 fn check_str_addition(
573 lhs_expr: &'tcx hir::Expr<'tcx>,
574 rhs_expr: &'tcx hir::Expr<'tcx>,
577 err: &mut Diagnostic,
581 let str_concat_note = "string concatenation requires an owned `String` on the left";
582 let rm_borrow_msg = "remove the borrow to obtain an owned `String`";
583 let to_owned_msg = "create an owned `String` from a string reference";
585 let is_std_string = |ty: Ty<'tcx>| {
587 .map_or(false, |ty_def| self.tcx.is_diagnostic_item(sym::String, ty_def.did()))
590 match (lhs_ty.kind(), rhs_ty.kind()) {
591 (&Ref(_, l_ty, _), &Ref(_, r_ty, _)) // &str or &String + &str, &String or &&str
592 if (*l_ty.kind() == Str || is_std_string(l_ty))
593 && (*r_ty.kind() == Str
594 || is_std_string(r_ty)
596 r_ty.kind(), Ref(_, inner_ty, _) if *inner_ty.kind() == Str
599 if let IsAssign::No = is_assign { // Do not supply this message if `&str += &str`
600 err.span_label(op.span, "`+` cannot be used to concatenate two `&str` strings");
601 err.note(str_concat_note);
602 if let hir::ExprKind::AddrOf(_, _, lhs_inner_expr) = lhs_expr.kind {
603 err.span_suggestion_verbose(
604 lhs_expr.span.until(lhs_inner_expr.span),
607 Applicability::MachineApplicable
610 err.span_suggestion_verbose(
611 lhs_expr.span.shrink_to_hi(),
614 Applicability::MachineApplicable
620 (&Ref(_, l_ty, _), &Adt(..)) // Handle `&str` & `&String` + `String`
621 if (*l_ty.kind() == Str || is_std_string(l_ty)) && is_std_string(rhs_ty) =>
625 "`+` cannot be used to concatenate a `&str` with a `String`",
630 let lhs_sugg = if let hir::ExprKind::AddrOf(_, _, lhs_inner_expr) = lhs_expr.kind {
631 sugg_msg = "remove the borrow on the left and add one on the right";
632 (lhs_expr.span.until(lhs_inner_expr.span), "".to_owned())
634 sugg_msg = "create an owned `String` on the left and add a borrow on the right";
635 (lhs_expr.span.shrink_to_hi(), ".to_owned()".to_owned())
637 let suggestions = vec![
639 (rhs_expr.span.shrink_to_lo(), "&".to_owned()),
641 err.multipart_suggestion_verbose(
644 Applicability::MachineApplicable,
648 err.note(str_concat_note);
657 pub fn check_user_unop(
659 ex: &'tcx hir::Expr<'tcx>,
660 operand_ty: Ty<'tcx>,
662 expected: Expectation<'tcx>,
664 assert!(op.is_by_value());
665 match self.lookup_op_method(operand_ty, None, None, Op::Unary(op, ex.span), expected) {
667 self.write_method_call(ex.hir_id, method);
671 let actual = self.resolve_vars_if_possible(operand_ty);
672 if !actual.references_error() {
673 let mut err = struct_span_err!(
677 "cannot apply unary operator `{}` to type `{}`",
683 format!("cannot apply unary operator `{}`", op.as_str()),
686 let mut visitor = TypeParamVisitor(vec![]);
687 visitor.visit_ty(operand_ty);
688 if let [_] = &visitor.0[..] && let ty::Param(_) = *operand_ty.kind() {
689 let predicates = errors
691 .filter_map(|error| {
692 error.obligation.predicate.to_opt_poly_trait_pred()
694 for pred in predicates {
695 self.suggest_restricting_param_bound(
704 let sp = self.tcx.sess.source_map().start_point(ex.span);
706 self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
708 // If the previous expression was a block expression, suggest parentheses
709 // (turning this into a binary subtraction operation instead.)
710 // for example, `{2} - 2` -> `({2}) - 2` (see src\test\ui\parser\expr-as-stmt.rs)
711 self.tcx.sess.parse_sess.expr_parentheses_needed(&mut err, *sp);
713 match actual.kind() {
714 Uint(_) if op == hir::UnOp::Neg => {
715 err.note("unsigned values cannot be negated");
717 if let hir::ExprKind::Unary(
721 hir::ExprKind::Lit(Spanned {
722 node: ast::LitKind::Int(1, _),
732 "you may have meant the maximum value of `{actual}`",
734 format!("{actual}::MAX"),
735 Applicability::MaybeIncorrect,
739 Str | Never | Char | Tuple(_) | Array(_, _) => {}
740 Ref(_, lty, _) if *lty.kind() == Str => {}
742 self.note_unmet_impls_on_type(&mut err, errors);
756 other_ty: Option<Ty<'tcx>>,
757 other_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
759 expected: Expectation<'tcx>,
760 ) -> Result<MethodCallee<'tcx>, Vec<FulfillmentError<'tcx>>> {
761 let lang = self.tcx.lang_items();
763 let span = match op {
764 Op::Binary(op, _) => op.span,
765 Op::Unary(_, span) => span,
767 let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
769 hir::BinOpKind::Add => (sym::add_assign, lang.add_assign_trait()),
770 hir::BinOpKind::Sub => (sym::sub_assign, lang.sub_assign_trait()),
771 hir::BinOpKind::Mul => (sym::mul_assign, lang.mul_assign_trait()),
772 hir::BinOpKind::Div => (sym::div_assign, lang.div_assign_trait()),
773 hir::BinOpKind::Rem => (sym::rem_assign, lang.rem_assign_trait()),
774 hir::BinOpKind::BitXor => (sym::bitxor_assign, lang.bitxor_assign_trait()),
775 hir::BinOpKind::BitAnd => (sym::bitand_assign, lang.bitand_assign_trait()),
776 hir::BinOpKind::BitOr => (sym::bitor_assign, lang.bitor_assign_trait()),
777 hir::BinOpKind::Shl => (sym::shl_assign, lang.shl_assign_trait()),
778 hir::BinOpKind::Shr => (sym::shr_assign, lang.shr_assign_trait()),
785 | hir::BinOpKind::And
786 | hir::BinOpKind::Or => {
787 span_bug!(span, "impossible assignment operation: {}=", op.node.as_str())
790 } else if let Op::Binary(op, IsAssign::No) = op {
792 hir::BinOpKind::Add => (sym::add, lang.add_trait()),
793 hir::BinOpKind::Sub => (sym::sub, lang.sub_trait()),
794 hir::BinOpKind::Mul => (sym::mul, lang.mul_trait()),
795 hir::BinOpKind::Div => (sym::div, lang.div_trait()),
796 hir::BinOpKind::Rem => (sym::rem, lang.rem_trait()),
797 hir::BinOpKind::BitXor => (sym::bitxor, lang.bitxor_trait()),
798 hir::BinOpKind::BitAnd => (sym::bitand, lang.bitand_trait()),
799 hir::BinOpKind::BitOr => (sym::bitor, lang.bitor_trait()),
800 hir::BinOpKind::Shl => (sym::shl, lang.shl_trait()),
801 hir::BinOpKind::Shr => (sym::shr, lang.shr_trait()),
802 hir::BinOpKind::Lt => (sym::lt, lang.partial_ord_trait()),
803 hir::BinOpKind::Le => (sym::le, lang.partial_ord_trait()),
804 hir::BinOpKind::Ge => (sym::ge, lang.partial_ord_trait()),
805 hir::BinOpKind::Gt => (sym::gt, lang.partial_ord_trait()),
806 hir::BinOpKind::Eq => (sym::eq, lang.eq_trait()),
807 hir::BinOpKind::Ne => (sym::ne, lang.eq_trait()),
808 hir::BinOpKind::And | hir::BinOpKind::Or => {
809 span_bug!(span, "&& and || are not overloadable")
812 } else if let Op::Unary(hir::UnOp::Not, _) = op {
813 (sym::not, lang.not_trait())
814 } else if let Op::Unary(hir::UnOp::Neg, _) = op {
815 (sym::neg, lang.neg_trait())
817 bug!("lookup_op_method: op not supported: {:?}", op)
821 "lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
822 lhs_ty, op, opname, trait_did
825 // Catches cases like #83893, where a lang item is declared with the
826 // wrong number of generic arguments. Should have yielded an error
827 // elsewhere by now, but we have to catch it here so that we do not
828 // index `other_tys` out of bounds (if the lang item has too many
829 // generic arguments, `other_tys` is too short).
830 if !has_expected_num_generic_args(
834 // Binary ops have a generic right-hand side, unary ops don't
842 let opname = Ident::with_dummy_span(opname);
843 let method = trait_did.and_then(|trait_did| {
844 self.lookup_op_method_in_trait(
855 match (method, trait_did) {
857 let method = self.register_infer_ok_obligations(ok);
858 self.select_obligations_where_possible(false, |_| {});
861 (None, None) => Err(vec![]),
862 (None, Some(trait_did)) => {
863 let (obligation, _) = self.obligation_for_op_method(
871 let mut fulfill = <dyn TraitEngine<'_>>::new(self.tcx);
872 fulfill.register_predicate_obligation(self, obligation);
873 Err(fulfill.select_where_possible(&self.infcx))
879 // Binary operator categories. These categories summarize the behavior
880 // with respect to the builtin operations supported.
882 /// &&, || -- cannot be overridden
885 /// <<, >> -- when shifting a single integer, rhs can be any
886 /// integer type. For simd, types must match.
889 /// +, -, etc -- takes equal types, produces same type as input,
890 /// applicable to ints/floats/simd
893 /// &, |, ^ -- takes equal types, produces same type as input,
894 /// applicable to ints/floats/simd/bool
897 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
898 /// which produce the input type
903 fn from(op: hir::BinOp) -> BinOpCategory {
905 hir::BinOpKind::Shl | hir::BinOpKind::Shr => BinOpCategory::Shift,
908 | hir::BinOpKind::Sub
909 | hir::BinOpKind::Mul
910 | hir::BinOpKind::Div
911 | hir::BinOpKind::Rem => BinOpCategory::Math,
913 hir::BinOpKind::BitXor | hir::BinOpKind::BitAnd | hir::BinOpKind::BitOr => {
914 BinOpCategory::Bitwise
922 | hir::BinOpKind::Gt => BinOpCategory::Comparison,
924 hir::BinOpKind::And | hir::BinOpKind::Or => BinOpCategory::Shortcircuit,
929 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
930 #[derive(Clone, Copy, Debug, PartialEq)]
936 #[derive(Clone, Copy, Debug)]
938 Binary(hir::BinOp, IsAssign),
939 Unary(hir::UnOp, Span),
942 /// Dereferences a single level of immutable referencing.
943 fn deref_ty_if_possible<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
945 ty::Ref(_, ty, hir::Mutability::Not) => *ty,
950 /// Returns `true` if this is a built-in arithmetic operation (e.g., u32
951 /// + u32, i16x4 == i16x4) and false if these types would have to be
952 /// overloaded to be legal. There are two reasons that we distinguish
953 /// builtin operations from overloaded ones (vs trying to drive
954 /// everything uniformly through the trait system and intrinsics or
955 /// something like that):
957 /// 1. Builtin operations can trivially be evaluated in constants.
958 /// 2. For comparison operators applied to SIMD types the result is
959 /// not of type `bool`. For example, `i16x4 == i16x4` yields a
960 /// type like `i16x4`. This means that the overloaded trait
961 /// `PartialEq` is not applicable.
963 /// Reason #2 is the killer. I tried for a while to always use
964 /// overloaded logic and just check the types in constants/codegen after
965 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
966 fn is_builtin_binop<'tcx>(lhs: Ty<'tcx>, rhs: Ty<'tcx>, op: hir::BinOp) -> bool {
967 // Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
968 // (See https://github.com/rust-lang/rust/issues/57447.)
969 let (lhs, rhs) = (deref_ty_if_possible(lhs), deref_ty_if_possible(rhs));
971 match BinOpCategory::from(op) {
972 BinOpCategory::Shortcircuit => true,
974 BinOpCategory::Shift => {
975 lhs.references_error()
976 || rhs.references_error()
977 || lhs.is_integral() && rhs.is_integral()
980 BinOpCategory::Math => {
981 lhs.references_error()
982 || rhs.references_error()
983 || lhs.is_integral() && rhs.is_integral()
984 || lhs.is_floating_point() && rhs.is_floating_point()
987 BinOpCategory::Bitwise => {
988 lhs.references_error()
989 || rhs.references_error()
990 || lhs.is_integral() && rhs.is_integral()
991 || lhs.is_floating_point() && rhs.is_floating_point()
992 || lhs.is_bool() && rhs.is_bool()
995 BinOpCategory::Comparison => {
996 lhs.references_error() || rhs.references_error() || lhs.is_scalar() && rhs.is_scalar()
1001 struct TypeParamVisitor<'tcx>(Vec<Ty<'tcx>>);
1003 impl<'tcx> TypeVisitor<'tcx> for TypeParamVisitor<'tcx> {
1004 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1005 if let ty::Param(_) = ty.kind() {
1008 ty.super_visit_with(self)
1012 struct TypeParamEraser<'a, 'tcx>(&'a FnCtxt<'a, 'tcx>, Span);
1014 impl<'tcx> TypeFolder<'tcx> for TypeParamEraser<'_, 'tcx> {
1015 fn tcx(&self) -> TyCtxt<'tcx> {
1019 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1021 ty::Param(_) => self.0.next_ty_var(TypeVariableOrigin {
1022 kind: TypeVariableOriginKind::MiscVariable,
1025 _ => ty.super_fold_with(self),