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::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::print::with_no_trimmed_paths;
15 use rustc_middle::ty::{
16 self, DefIdTree, IsSuggestable, Ty, TyCtxt, TypeFolder, TypeSuperFoldable, TypeVisitable,
18 use rustc_session::errors::ExprParenthesesNeeded;
19 use rustc_span::source_map::Spanned;
20 use rustc_span::symbol::{sym, Ident};
22 use rustc_trait_selection::infer::InferCtxtExt;
23 use rustc_trait_selection::traits::error_reporting::suggestions::TypeErrCtxtExt as _;
24 use rustc_trait_selection::traits::{self, FulfillmentError};
25 use rustc_type_ir::sty::TyKind::*;
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) {
54 Op::Binary(op, IsAssign::Yes),
59 // If LHS += RHS is an error, but *LHS += RHS is successful, then we will have
60 // emitted a better suggestion during error handling in check_overloaded_binop.
65 Op::Binary(op, IsAssign::Yes),
70 err.downgrade_to_delayed_bug();
72 // Otherwise, it's valid to suggest dereferencing the LHS here.
73 err.span_suggestion_verbose(
74 lhs.span.shrink_to_lo(),
75 "consider dereferencing the left-hand side of this operation",
77 Applicability::MaybeIncorrect,
87 /// Checks a potentially overloaded binary operator.
90 expr: &'tcx hir::Expr<'tcx>,
92 lhs_expr: &'tcx hir::Expr<'tcx>,
93 rhs_expr: &'tcx hir::Expr<'tcx>,
94 expected: Expectation<'tcx>,
99 "check_binop(expr.hir_id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
100 expr.hir_id, expr, op, lhs_expr, rhs_expr
103 match BinOpCategory::from(op) {
104 BinOpCategory::Shortcircuit => {
105 // && and || are a simple case.
106 self.check_expr_coercable_to_type(lhs_expr, tcx.types.bool, None);
107 let lhs_diverges = self.diverges.get();
108 self.check_expr_coercable_to_type(rhs_expr, tcx.types.bool, None);
110 // Depending on the LHS' value, the RHS can never execute.
111 self.diverges.set(lhs_diverges);
116 // Otherwise, we always treat operators as if they are
117 // overloaded. This is the way to be most flexible w/r/t
118 // types that get inferred.
119 let (lhs_ty, rhs_ty, return_ty) = self.check_overloaded_binop(
128 // Supply type inference hints if relevant. Probably these
129 // hints should be enforced during select as part of the
130 // `consider_unification_despite_ambiguity` routine, but this
131 // more convenient for now.
133 // The basic idea is to help type inference by taking
134 // advantage of things we know about how the impls for
135 // scalar types are arranged. This is important in a
136 // scenario like `1_u32 << 2`, because it lets us quickly
137 // deduce that the result type should be `u32`, even
138 // though we don't know yet what type 2 has and hence
139 // can't pin this down to a specific impl.
140 if !lhs_ty.is_ty_var()
141 && !rhs_ty.is_ty_var()
142 && is_builtin_binop(lhs_ty, rhs_ty, op)
144 let builtin_return_ty = self.enforce_builtin_binop_types(
151 self.demand_suptype(expr.span, builtin_return_ty, return_ty);
159 fn enforce_builtin_binop_types(
167 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
169 // Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
170 // (See https://github.com/rust-lang/rust/issues/57447.)
171 let (lhs_ty, rhs_ty) = (deref_ty_if_possible(lhs_ty), deref_ty_if_possible(rhs_ty));
174 match BinOpCategory::from(op) {
175 BinOpCategory::Shortcircuit => {
176 self.demand_suptype(lhs_span, tcx.types.bool, lhs_ty);
177 self.demand_suptype(rhs_span, tcx.types.bool, rhs_ty);
181 BinOpCategory::Shift => {
182 // result type is same as LHS always
186 BinOpCategory::Math | BinOpCategory::Bitwise => {
187 // both LHS and RHS and result will have the same type
188 self.demand_suptype(rhs_span, lhs_ty, rhs_ty);
192 BinOpCategory::Comparison => {
193 // both LHS and RHS and result will have the same type
194 self.demand_suptype(rhs_span, lhs_ty, rhs_ty);
200 fn check_overloaded_binop(
202 expr: &'tcx hir::Expr<'tcx>,
203 lhs_expr: &'tcx hir::Expr<'tcx>,
204 rhs_expr: &'tcx hir::Expr<'tcx>,
207 expected: Expectation<'tcx>,
208 ) -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>) {
210 "check_overloaded_binop(expr.hir_id={}, op={:?}, is_assign={:?})",
211 expr.hir_id, op, is_assign
214 let lhs_ty = match is_assign {
216 // Find a suitable supertype of the LHS expression's type, by coercing to
217 // a type variable, to pass as the `Self` to the trait, avoiding invariant
218 // trait matching creating lifetime constraints that are too strict.
219 // e.g., adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
220 // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`.
221 let lhs_ty = self.check_expr(lhs_expr);
222 let fresh_var = self.next_ty_var(TypeVariableOrigin {
223 kind: TypeVariableOriginKind::MiscVariable,
226 self.demand_coerce(lhs_expr, lhs_ty, fresh_var, Some(rhs_expr), AllowTwoPhase::No)
229 // rust-lang/rust#52126: We have to use strict
230 // equivalence on the LHS of an assign-op like `+=`;
231 // overwritten or mutably-borrowed places cannot be
232 // coerced to a supertype.
233 self.check_expr(lhs_expr)
236 let lhs_ty = self.resolve_vars_with_obligations(lhs_ty);
238 // N.B., as we have not yet type-checked the RHS, we don't have the
239 // type at hand. Make a variable to represent it. The whole reason
240 // for this indirection is so that, below, we can check the expr
241 // using this variable as the expected type, which sometimes lets
242 // us do better coercions than we would be able to do otherwise,
243 // particularly for things like `String + &String`.
244 let rhs_ty_var = self.next_ty_var(TypeVariableOrigin {
245 kind: TypeVariableOriginKind::MiscVariable,
249 let result = self.lookup_op_method(
251 Some((rhs_expr, rhs_ty_var)),
252 Op::Binary(op, is_assign),
257 let rhs_ty = self.check_expr_coercable_to_type(rhs_expr, rhs_ty_var, Some(lhs_expr));
258 let rhs_ty = self.resolve_vars_with_obligations(rhs_ty);
260 let return_ty = match result {
262 let by_ref_binop = !op.node.is_by_value();
263 if is_assign == IsAssign::Yes || by_ref_binop {
264 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind() {
265 let mutbl = AutoBorrowMutability::new(*mutbl, AllowTwoPhase::Yes);
266 let autoref = Adjustment {
267 kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
268 target: method.sig.inputs()[0],
270 self.apply_adjustments(lhs_expr, vec![autoref]);
274 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[1].kind() {
275 // Allow two-phase borrows for binops in initial deployment
276 // since they desugar to methods
277 let mutbl = AutoBorrowMutability::new(*mutbl, AllowTwoPhase::Yes);
279 let autoref = Adjustment {
280 kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
281 target: method.sig.inputs()[1],
283 // HACK(eddyb) Bypass checks due to reborrows being in
284 // some cases applied on the RHS, on top of which we need
285 // to autoref, which is not allowed by apply_adjustments.
286 // self.apply_adjustments(rhs_expr, vec![autoref]);
290 .entry(rhs_expr.hir_id)
295 self.write_method_call(expr.hir_id, method);
299 // error types are considered "builtin"
300 Err(_) if lhs_ty.references_error() || rhs_ty.references_error() => self.tcx.ty_error(),
302 let (_, trait_def_id) =
303 lang_item_for_op(self.tcx, Op::Binary(op, is_assign), op.span);
304 let missing_trait = trait_def_id
305 .map(|def_id| with_no_trimmed_paths!(self.tcx.def_path_str(def_id)));
306 let (mut err, output_def_id) = match is_assign {
308 let mut err = struct_span_err!(
312 "binary assignment operation `{}=` cannot be applied to type `{}`",
318 format!("cannot use `{}=` on type `{}`", op.node.as_str(), lhs_ty),
320 self.note_unmet_impls_on_type(&mut err, errors);
324 let message = match op.node {
325 hir::BinOpKind::Add => {
326 format!("cannot add `{rhs_ty}` to `{lhs_ty}`")
328 hir::BinOpKind::Sub => {
329 format!("cannot subtract `{rhs_ty}` from `{lhs_ty}`")
331 hir::BinOpKind::Mul => {
332 format!("cannot multiply `{lhs_ty}` by `{rhs_ty}`")
334 hir::BinOpKind::Div => {
335 format!("cannot divide `{lhs_ty}` by `{rhs_ty}`")
337 hir::BinOpKind::Rem => {
339 "cannot calculate the remainder of `{lhs_ty}` divided by `{rhs_ty}`"
342 hir::BinOpKind::BitAnd => {
343 format!("no implementation for `{lhs_ty} & {rhs_ty}`")
345 hir::BinOpKind::BitXor => {
346 format!("no implementation for `{lhs_ty} ^ {rhs_ty}`")
348 hir::BinOpKind::BitOr => {
349 format!("no implementation for `{lhs_ty} | {rhs_ty}`")
351 hir::BinOpKind::Shl => {
352 format!("no implementation for `{lhs_ty} << {rhs_ty}`")
354 hir::BinOpKind::Shr => {
355 format!("no implementation for `{lhs_ty} >> {rhs_ty}`")
358 "binary operation `{}` cannot be applied to type `{}`",
363 let output_def_id = trait_def_id.and_then(|def_id| {
365 .associated_item_def_ids(def_id)
367 .find(|item_def_id| {
368 self.tcx.associated_item(*item_def_id).name == sym::Output
372 let mut err = struct_span_err!(self.tcx.sess, op.span, E0369, "{message}");
373 if !lhs_expr.span.eq(&rhs_expr.span) {
374 err.span_label(lhs_expr.span, lhs_ty.to_string());
375 err.span_label(rhs_expr.span, rhs_ty.to_string());
377 self.note_unmet_impls_on_type(&mut err, errors);
382 let mut suggest_deref_binop = |lhs_deref_ty: Ty<'tcx>| {
386 Some((rhs_expr, rhs_ty)),
387 Op::Binary(op, is_assign),
393 "`{}{}` can be used on `{}` if you dereference the left-hand side",
396 IsAssign::Yes => "=",
401 err.span_suggestion_verbose(
402 lhs_expr.span.shrink_to_lo(),
405 rustc_errors::Applicability::MachineApplicable,
410 let is_compatible = |lhs_ty, rhs_ty| {
411 self.lookup_op_method(
413 Some((rhs_expr, rhs_ty)),
414 Op::Binary(op, is_assign),
420 // We should suggest `a + b` => `*a + b` if `a` is copy, and suggest
421 // `a += b` => `*a += b` if a is a mut ref.
422 if !op.span.can_be_used_for_suggestions() {
423 // Suppress suggestions when lhs and rhs are not in the same span as the error
424 } else if is_assign == IsAssign::Yes
425 && let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty)
427 suggest_deref_binop(lhs_deref_ty);
428 } else if is_assign == IsAssign::No
429 && let Ref(_, lhs_deref_ty, _) = lhs_ty.kind()
431 if self.type_is_copy_modulo_regions(
436 suggest_deref_binop(*lhs_deref_ty);
438 } else if self.suggest_fn_call(&mut err, lhs_expr, lhs_ty, |lhs_ty| {
439 is_compatible(lhs_ty, rhs_ty)
440 }) || self.suggest_fn_call(&mut err, rhs_expr, rhs_ty, |rhs_ty| {
441 is_compatible(lhs_ty, rhs_ty)
442 }) || self.suggest_two_fn_call(
448 |lhs_ty, rhs_ty| is_compatible(lhs_ty, rhs_ty),
453 if let Some(missing_trait) = missing_trait {
454 if op.node == hir::BinOpKind::Add
455 && self.check_str_addition(
456 lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, is_assign, op,
459 // This has nothing here because it means we did string
460 // concatenation (e.g., "Hello " + "World!"). This means
461 // we don't want the note in the else clause to be emitted
462 } else if lhs_ty.has_non_region_param() {
463 // Look for a TraitPredicate in the Fulfillment errors,
464 // and use it to generate a suggestion.
466 // Note that lookup_op_method must be called again but
467 // with a specific rhs_ty instead of a placeholder so
468 // the resulting predicate generates a more specific
469 // suggestion for the user.
473 Some((rhs_expr, rhs_ty)),
474 Op::Binary(op, is_assign),
478 if !errors.is_empty() {
479 for error in errors {
480 if let Some(trait_pred) =
481 error.obligation.predicate.to_opt_poly_trait_pred()
483 let output_associated_item = match error.obligation.cause.code()
485 ObligationCauseCode::BinOp {
486 output_ty: Some(output_ty),
489 // Make sure that we're attaching `Output = ..` to the right trait predicate
490 if let Some(output_def_id) = output_def_id
491 && let Some(trait_def_id) = trait_def_id
492 && self.tcx.parent(output_def_id) == trait_def_id
493 && let Some(output_ty) = output_ty.make_suggestable(self.tcx, false)
495 Some(("Output", output_ty))
503 self.err_ctxt().suggest_restricting_param_bound(
506 output_associated_item,
512 // When we know that a missing bound is responsible, we don't show
513 // this note as it is redundant.
515 "the trait `{missing_trait}` is not implemented for `{lhs_ty}`"
520 let reported = err.emit();
521 self.tcx.ty_error_with_guaranteed(reported)
525 (lhs_ty, rhs_ty, return_ty)
528 /// Provide actionable suggestions when trying to add two strings with incorrect types,
529 /// like `&str + &str`, `String + String` and `&str + &String`.
531 /// If this function returns `true` it means a note was printed, so we don't need
532 /// to print the normal "implementation of `std::ops::Add` might be missing" note
533 fn check_str_addition(
535 lhs_expr: &'tcx hir::Expr<'tcx>,
536 rhs_expr: &'tcx hir::Expr<'tcx>,
539 err: &mut Diagnostic,
543 let str_concat_note = "string concatenation requires an owned `String` on the left";
544 let rm_borrow_msg = "remove the borrow to obtain an owned `String`";
545 let to_owned_msg = "create an owned `String` from a string reference";
547 let string_type = self.tcx.lang_items().string();
548 let is_std_string = |ty: Ty<'tcx>| {
549 ty.ty_adt_def().map_or(false, |ty_def| Some(ty_def.did()) == string_type)
552 match (lhs_ty.kind(), rhs_ty.kind()) {
553 (&Ref(_, l_ty, _), &Ref(_, r_ty, _)) // &str or &String + &str, &String or &&str
554 if (*l_ty.kind() == Str || is_std_string(l_ty))
555 && (*r_ty.kind() == Str
556 || is_std_string(r_ty)
558 r_ty.kind(), Ref(_, inner_ty, _) if *inner_ty.kind() == Str
561 if let IsAssign::No = is_assign { // Do not supply this message if `&str += &str`
562 err.span_label(op.span, "`+` cannot be used to concatenate two `&str` strings");
563 err.note(str_concat_note);
564 if let hir::ExprKind::AddrOf(_, _, lhs_inner_expr) = lhs_expr.kind {
565 err.span_suggestion_verbose(
566 lhs_expr.span.until(lhs_inner_expr.span),
569 Applicability::MachineApplicable
572 err.span_suggestion_verbose(
573 lhs_expr.span.shrink_to_hi(),
576 Applicability::MachineApplicable
582 (&Ref(_, l_ty, _), &Adt(..)) // Handle `&str` & `&String` + `String`
583 if (*l_ty.kind() == Str || is_std_string(l_ty)) && is_std_string(rhs_ty) =>
587 "`+` cannot be used to concatenate a `&str` with a `String`",
592 let lhs_sugg = if let hir::ExprKind::AddrOf(_, _, lhs_inner_expr) = lhs_expr.kind {
593 sugg_msg = "remove the borrow on the left and add one on the right";
594 (lhs_expr.span.until(lhs_inner_expr.span), "".to_owned())
596 sugg_msg = "create an owned `String` on the left and add a borrow on the right";
597 (lhs_expr.span.shrink_to_hi(), ".to_owned()".to_owned())
599 let suggestions = vec![
601 (rhs_expr.span.shrink_to_lo(), "&".to_owned()),
603 err.multipart_suggestion_verbose(
606 Applicability::MachineApplicable,
610 err.note(str_concat_note);
619 pub fn check_user_unop(
621 ex: &'tcx hir::Expr<'tcx>,
622 operand_ty: Ty<'tcx>,
624 expected: Expectation<'tcx>,
626 assert!(op.is_by_value());
627 match self.lookup_op_method(operand_ty, None, Op::Unary(op, ex.span), expected) {
629 self.write_method_call(ex.hir_id, method);
633 let actual = self.resolve_vars_if_possible(operand_ty);
634 if !actual.references_error() {
635 let mut err = struct_span_err!(
639 "cannot apply unary operator `{}` to type `{}`",
645 format!("cannot apply unary operator `{}`", op.as_str()),
648 if operand_ty.has_non_region_param() {
649 let predicates = errors.iter().filter_map(|error| {
650 error.obligation.predicate.to_opt_poly_trait_pred()
652 for pred in predicates {
653 self.err_ctxt().suggest_restricting_param_bound(
662 let sp = self.tcx.sess.source_map().start_point(ex.span).with_parent(None);
664 self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
666 // If the previous expression was a block expression, suggest parentheses
667 // (turning this into a binary subtraction operation instead.)
668 // for example, `{2} - 2` -> `({2}) - 2` (see src\test\ui\parser\expr-as-stmt.rs)
669 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
671 match actual.kind() {
672 Uint(_) if op == hir::UnOp::Neg => {
673 err.note("unsigned values cannot be negated");
675 if let hir::ExprKind::Unary(
679 hir::ExprKind::Lit(Spanned {
680 node: ast::LitKind::Int(1, _),
690 "you may have meant the maximum value of `{actual}`",
692 format!("{actual}::MAX"),
693 Applicability::MaybeIncorrect,
697 Str | Never | Char | Tuple(_) | Array(_, _) => {}
698 Ref(_, lty, _) if *lty.kind() == Str => {}
700 self.note_unmet_impls_on_type(&mut err, errors);
714 opt_rhs: Option<(&'tcx hir::Expr<'tcx>, Ty<'tcx>)>,
716 expected: Expectation<'tcx>,
717 ) -> Result<MethodCallee<'tcx>, Vec<FulfillmentError<'tcx>>> {
718 let span = match op {
719 Op::Binary(op, _) => op.span,
720 Op::Unary(_, span) => span,
722 let (opname, trait_did) = lang_item_for_op(self.tcx, op, span);
725 "lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
726 lhs_ty, op, opname, trait_did
729 // Catches cases like #83893, where a lang item is declared with the
730 // wrong number of generic arguments. Should have yielded an error
731 // elsewhere by now, but we have to catch it here so that we do not
732 // index `other_tys` out of bounds (if the lang item has too many
733 // generic arguments, `other_tys` is too short).
734 if !has_expected_num_generic_args(
738 // Binary ops have a generic right-hand side, unary ops don't
745 .delay_span_bug(span, "operator didn't have the right number of generic args");
749 let opname = Ident::with_dummy_span(opname);
751 opt_rhs.as_ref().map(|(_, ty)| std::slice::from_ref(ty)).unwrap_or_default();
752 let cause = self.cause(
755 rhs_span: opt_rhs.map(|(expr, _)| expr.span),
757 .map_or(false, |(expr, _)| matches!(expr.kind, hir::ExprKind::Lit(_))),
758 output_ty: expected.only_has_type(self),
762 let method = trait_did.and_then(|trait_did| {
763 self.lookup_method_in_trait(cause.clone(), opname, trait_did, lhs_ty, Some(input_types))
766 match (method, trait_did) {
768 let method = self.register_infer_ok_obligations(ok);
769 self.select_obligations_where_possible(|_| {});
772 (None, None) => Err(vec![]),
773 (None, Some(trait_did)) => {
774 let (obligation, _) =
775 self.obligation_for_method(cause, trait_did, lhs_ty, Some(input_types));
776 Err(rustc_trait_selection::traits::fully_solve_obligation(self, obligation))
786 ) -> (rustc_span::Symbol, Option<hir::def_id::DefId>) {
787 let lang = tcx.lang_items();
788 if let Op::Binary(op, IsAssign::Yes) = op {
790 hir::BinOpKind::Add => (sym::add_assign, lang.add_assign_trait()),
791 hir::BinOpKind::Sub => (sym::sub_assign, lang.sub_assign_trait()),
792 hir::BinOpKind::Mul => (sym::mul_assign, lang.mul_assign_trait()),
793 hir::BinOpKind::Div => (sym::div_assign, lang.div_assign_trait()),
794 hir::BinOpKind::Rem => (sym::rem_assign, lang.rem_assign_trait()),
795 hir::BinOpKind::BitXor => (sym::bitxor_assign, lang.bitxor_assign_trait()),
796 hir::BinOpKind::BitAnd => (sym::bitand_assign, lang.bitand_assign_trait()),
797 hir::BinOpKind::BitOr => (sym::bitor_assign, lang.bitor_assign_trait()),
798 hir::BinOpKind::Shl => (sym::shl_assign, lang.shl_assign_trait()),
799 hir::BinOpKind::Shr => (sym::shr_assign, lang.shr_assign_trait()),
806 | hir::BinOpKind::And
807 | hir::BinOpKind::Or => {
808 span_bug!(span, "impossible assignment operation: {}=", op.node.as_str())
811 } else if let Op::Binary(op, IsAssign::No) = op {
813 hir::BinOpKind::Add => (sym::add, lang.add_trait()),
814 hir::BinOpKind::Sub => (sym::sub, lang.sub_trait()),
815 hir::BinOpKind::Mul => (sym::mul, lang.mul_trait()),
816 hir::BinOpKind::Div => (sym::div, lang.div_trait()),
817 hir::BinOpKind::Rem => (sym::rem, lang.rem_trait()),
818 hir::BinOpKind::BitXor => (sym::bitxor, lang.bitxor_trait()),
819 hir::BinOpKind::BitAnd => (sym::bitand, lang.bitand_trait()),
820 hir::BinOpKind::BitOr => (sym::bitor, lang.bitor_trait()),
821 hir::BinOpKind::Shl => (sym::shl, lang.shl_trait()),
822 hir::BinOpKind::Shr => (sym::shr, lang.shr_trait()),
823 hir::BinOpKind::Lt => (sym::lt, lang.partial_ord_trait()),
824 hir::BinOpKind::Le => (sym::le, lang.partial_ord_trait()),
825 hir::BinOpKind::Ge => (sym::ge, lang.partial_ord_trait()),
826 hir::BinOpKind::Gt => (sym::gt, lang.partial_ord_trait()),
827 hir::BinOpKind::Eq => (sym::eq, lang.eq_trait()),
828 hir::BinOpKind::Ne => (sym::ne, lang.eq_trait()),
829 hir::BinOpKind::And | hir::BinOpKind::Or => {
830 span_bug!(span, "&& and || are not overloadable")
833 } else if let Op::Unary(hir::UnOp::Not, _) = op {
834 (sym::not, lang.not_trait())
835 } else if let Op::Unary(hir::UnOp::Neg, _) = op {
836 (sym::neg, lang.neg_trait())
838 bug!("lookup_op_method: op not supported: {:?}", op)
842 // Binary operator categories. These categories summarize the behavior
843 // with respect to the builtin operations supported.
845 /// &&, || -- cannot be overridden
848 /// <<, >> -- when shifting a single integer, rhs can be any
849 /// integer type. For simd, types must match.
852 /// +, -, etc -- takes equal types, produces same type as input,
853 /// applicable to ints/floats/simd
856 /// &, |, ^ -- takes equal types, produces same type as input,
857 /// applicable to ints/floats/simd/bool
860 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
861 /// which produce the input type
866 fn from(op: hir::BinOp) -> BinOpCategory {
868 hir::BinOpKind::Shl | hir::BinOpKind::Shr => BinOpCategory::Shift,
871 | hir::BinOpKind::Sub
872 | hir::BinOpKind::Mul
873 | hir::BinOpKind::Div
874 | hir::BinOpKind::Rem => BinOpCategory::Math,
876 hir::BinOpKind::BitXor | hir::BinOpKind::BitAnd | hir::BinOpKind::BitOr => {
877 BinOpCategory::Bitwise
885 | hir::BinOpKind::Gt => BinOpCategory::Comparison,
887 hir::BinOpKind::And | hir::BinOpKind::Or => BinOpCategory::Shortcircuit,
892 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
893 #[derive(Clone, Copy, Debug, PartialEq)]
899 #[derive(Clone, Copy, Debug)]
901 Binary(hir::BinOp, IsAssign),
902 Unary(hir::UnOp, Span),
905 /// Dereferences a single level of immutable referencing.
906 fn deref_ty_if_possible(ty: Ty<'_>) -> Ty<'_> {
908 ty::Ref(_, ty, hir::Mutability::Not) => *ty,
913 /// Returns `true` if this is a built-in arithmetic operation (e.g., u32
914 /// + u32, i16x4 == i16x4) and false if these types would have to be
915 /// overloaded to be legal. There are two reasons that we distinguish
916 /// builtin operations from overloaded ones (vs trying to drive
917 /// everything uniformly through the trait system and intrinsics or
918 /// something like that):
920 /// 1. Builtin operations can trivially be evaluated in constants.
921 /// 2. For comparison operators applied to SIMD types the result is
922 /// not of type `bool`. For example, `i16x4 == i16x4` yields a
923 /// type like `i16x4`. This means that the overloaded trait
924 /// `PartialEq` is not applicable.
926 /// Reason #2 is the killer. I tried for a while to always use
927 /// overloaded logic and just check the types in constants/codegen after
928 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
929 fn is_builtin_binop<'tcx>(lhs: Ty<'tcx>, rhs: Ty<'tcx>, op: hir::BinOp) -> bool {
930 // Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
931 // (See https://github.com/rust-lang/rust/issues/57447.)
932 let (lhs, rhs) = (deref_ty_if_possible(lhs), deref_ty_if_possible(rhs));
934 match BinOpCategory::from(op) {
935 BinOpCategory::Shortcircuit => true,
937 BinOpCategory::Shift => {
938 lhs.references_error()
939 || rhs.references_error()
940 || lhs.is_integral() && rhs.is_integral()
943 BinOpCategory::Math => {
944 lhs.references_error()
945 || rhs.references_error()
946 || lhs.is_integral() && rhs.is_integral()
947 || lhs.is_floating_point() && rhs.is_floating_point()
950 BinOpCategory::Bitwise => {
951 lhs.references_error()
952 || rhs.references_error()
953 || lhs.is_integral() && rhs.is_integral()
954 || lhs.is_floating_point() && rhs.is_floating_point()
955 || lhs.is_bool() && rhs.is_bool()
958 BinOpCategory::Comparison => {
959 lhs.references_error() || rhs.references_error() || lhs.is_scalar() && rhs.is_scalar()
964 struct TypeParamEraser<'a, 'tcx>(&'a FnCtxt<'a, 'tcx>, Span);
966 impl<'tcx> TypeFolder<'tcx> for TypeParamEraser<'_, 'tcx> {
967 fn tcx(&self) -> TyCtxt<'tcx> {
971 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
973 ty::Param(_) => self.0.next_ty_var(TypeVariableOrigin {
974 kind: TypeVariableOriginKind::MiscVariable,
977 _ => ty.super_fold_with(self),