1 //! Code related to processing overloaded binary and unary operators.
3 use super::method::MethodCallee;
4 use super::{FnCtxt, Needs};
5 use rustc::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability};
6 use rustc::ty::TyKind::{Adt, Array, Char, FnDef, Never, Ref, Str, Tuple, Uint};
7 use rustc::ty::{self, Ty, TypeFoldable};
8 use rustc_ast::ast::Ident;
9 use rustc_errors::{self, struct_span_err, Applicability, DiagnosticBuilder};
11 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
15 /// Checks a `a <op>= b`
16 pub fn check_binop_assign(
18 expr: &'tcx hir::Expr<'tcx>,
20 lhs: &'tcx hir::Expr<'tcx>,
21 rhs: &'tcx hir::Expr<'tcx>,
23 let (lhs_ty, rhs_ty, return_ty) =
24 self.check_overloaded_binop(expr, lhs, rhs, op, IsAssign::Yes);
27 if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() && is_builtin_binop(lhs_ty, rhs_ty, op) {
28 self.enforce_builtin_binop_types(&lhs.span, lhs_ty, &rhs.span, rhs_ty, op);
34 self.check_lhs_assignable(lhs, "E0067", &op.span);
39 /// Checks a potentially overloaded binary operator.
42 expr: &'tcx hir::Expr<'tcx>,
44 lhs_expr: &'tcx hir::Expr<'tcx>,
45 rhs_expr: &'tcx hir::Expr<'tcx>,
50 "check_binop(expr.hir_id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
51 expr.hir_id, expr, op, lhs_expr, rhs_expr
54 match BinOpCategory::from(op) {
55 BinOpCategory::Shortcircuit => {
56 // && and || are a simple case.
57 self.check_expr_coercable_to_type(lhs_expr, tcx.types.bool);
58 let lhs_diverges = self.diverges.get();
59 self.check_expr_coercable_to_type(rhs_expr, tcx.types.bool);
61 // Depending on the LHS' value, the RHS can never execute.
62 self.diverges.set(lhs_diverges);
67 // Otherwise, we always treat operators as if they are
68 // overloaded. This is the way to be most flexible w/r/t
69 // types that get inferred.
70 let (lhs_ty, rhs_ty, return_ty) =
71 self.check_overloaded_binop(expr, lhs_expr, rhs_expr, op, IsAssign::No);
73 // Supply type inference hints if relevant. Probably these
74 // hints should be enforced during select as part of the
75 // `consider_unification_despite_ambiguity` routine, but this
76 // more convenient for now.
78 // The basic idea is to help type inference by taking
79 // advantage of things we know about how the impls for
80 // scalar types are arranged. This is important in a
81 // scenario like `1_u32 << 2`, because it lets us quickly
82 // deduce that the result type should be `u32`, even
83 // though we don't know yet what type 2 has and hence
84 // can't pin this down to a specific impl.
85 if !lhs_ty.is_ty_var()
86 && !rhs_ty.is_ty_var()
87 && is_builtin_binop(lhs_ty, rhs_ty, op)
89 let builtin_return_ty = self.enforce_builtin_binop_types(
96 self.demand_suptype(expr.span, builtin_return_ty, return_ty);
104 fn enforce_builtin_binop_types(
112 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
114 // Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
115 // (See https://github.com/rust-lang/rust/issues/57447.)
116 let (lhs_ty, rhs_ty) = (deref_ty_if_possible(lhs_ty), deref_ty_if_possible(rhs_ty));
119 match BinOpCategory::from(op) {
120 BinOpCategory::Shortcircuit => {
121 self.demand_suptype(*lhs_span, tcx.mk_bool(), lhs_ty);
122 self.demand_suptype(*rhs_span, tcx.mk_bool(), rhs_ty);
126 BinOpCategory::Shift => {
127 // result type is same as LHS always
131 BinOpCategory::Math | BinOpCategory::Bitwise => {
132 // both LHS and RHS and result will have the same type
133 self.demand_suptype(*rhs_span, lhs_ty, rhs_ty);
137 BinOpCategory::Comparison => {
138 // both LHS and RHS and result will have the same type
139 self.demand_suptype(*rhs_span, lhs_ty, rhs_ty);
145 fn check_overloaded_binop(
147 expr: &'tcx hir::Expr<'tcx>,
148 lhs_expr: &'tcx hir::Expr<'tcx>,
149 rhs_expr: &'tcx hir::Expr<'tcx>,
152 ) -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>) {
154 "check_overloaded_binop(expr.hir_id={}, op={:?}, is_assign={:?})",
155 expr.hir_id, op, is_assign
158 let lhs_ty = match is_assign {
160 // Find a suitable supertype of the LHS expression's type, by coercing to
161 // a type variable, to pass as the `Self` to the trait, avoiding invariant
162 // trait matching creating lifetime constraints that are too strict.
163 // e.g., adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
164 // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`.
165 let lhs_ty = self.check_expr_with_needs(lhs_expr, Needs::None);
166 let fresh_var = self.next_ty_var(TypeVariableOrigin {
167 kind: TypeVariableOriginKind::MiscVariable,
170 self.demand_coerce(lhs_expr, lhs_ty, fresh_var, AllowTwoPhase::No)
173 // rust-lang/rust#52126: We have to use strict
174 // equivalence on the LHS of an assign-op like `+=`;
175 // overwritten or mutably-borrowed places cannot be
176 // coerced to a supertype.
177 self.check_expr_with_needs(lhs_expr, Needs::MutPlace)
180 let lhs_ty = self.resolve_vars_with_obligations(lhs_ty);
182 // N.B., as we have not yet type-checked the RHS, we don't have the
183 // type at hand. Make a variable to represent it. The whole reason
184 // for this indirection is so that, below, we can check the expr
185 // using this variable as the expected type, which sometimes lets
186 // us do better coercions than we would be able to do otherwise,
187 // particularly for things like `String + &String`.
188 let rhs_ty_var = self.next_ty_var(TypeVariableOrigin {
189 kind: TypeVariableOriginKind::MiscVariable,
193 let result = self.lookup_op_method(lhs_ty, &[rhs_ty_var], Op::Binary(op, is_assign));
196 let rhs_ty = self.check_expr_coercable_to_type(rhs_expr, rhs_ty_var);
197 let rhs_ty = self.resolve_vars_with_obligations(rhs_ty);
199 let return_ty = match result {
201 let by_ref_binop = !op.node.is_by_value();
202 if is_assign == IsAssign::Yes || by_ref_binop {
203 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
204 let mutbl = match mutbl {
205 hir::Mutability::Not => AutoBorrowMutability::Not,
206 hir::Mutability::Mut => AutoBorrowMutability::Mut {
207 // Allow two-phase borrows for binops in initial deployment
208 // since they desugar to methods
209 allow_two_phase_borrow: AllowTwoPhase::Yes,
212 let autoref = Adjustment {
213 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
214 target: method.sig.inputs()[0],
216 self.apply_adjustments(lhs_expr, vec![autoref]);
220 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[1].kind {
221 let mutbl = match mutbl {
222 hir::Mutability::Not => AutoBorrowMutability::Not,
223 hir::Mutability::Mut => AutoBorrowMutability::Mut {
224 // Allow two-phase borrows for binops in initial deployment
225 // since they desugar to methods
226 allow_two_phase_borrow: AllowTwoPhase::Yes,
229 let autoref = Adjustment {
230 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
231 target: method.sig.inputs()[1],
233 // HACK(eddyb) Bypass checks due to reborrows being in
234 // some cases applied on the RHS, on top of which we need
235 // to autoref, which is not allowed by apply_adjustments.
236 // self.apply_adjustments(rhs_expr, vec![autoref]);
240 .entry(rhs_expr.hir_id)
245 self.write_method_call(expr.hir_id, method);
250 // error types are considered "builtin"
251 if !lhs_ty.references_error() {
252 let source_map = self.tcx.sess.source_map();
255 let mut err = struct_span_err!(
259 "binary assignment operation `{}=` cannot be applied to type `{}`",
265 format!("cannot use `{}=` on type `{}`", op.node.as_str(), lhs_ty),
267 let mut suggested_deref = false;
268 if let Ref(_, rty, _) = lhs_ty.kind {
270 self.infcx.type_is_copy_modulo_regions(
275 .lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign))
278 if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
280 "`{}=` can be used on '{}', you can dereference `{}`",
288 format!("*{}", lstring),
289 rustc_errors::Applicability::MachineApplicable,
291 suggested_deref = true;
295 let missing_trait = match op.node {
296 hir::BinOpKind::Add => Some("std::ops::AddAssign"),
297 hir::BinOpKind::Sub => Some("std::ops::SubAssign"),
298 hir::BinOpKind::Mul => Some("std::ops::MulAssign"),
299 hir::BinOpKind::Div => Some("std::ops::DivAssign"),
300 hir::BinOpKind::Rem => Some("std::ops::RemAssign"),
301 hir::BinOpKind::BitAnd => Some("std::ops::BitAndAssign"),
302 hir::BinOpKind::BitXor => Some("std::ops::BitXorAssign"),
303 hir::BinOpKind::BitOr => Some("std::ops::BitOrAssign"),
304 hir::BinOpKind::Shl => Some("std::ops::ShlAssign"),
305 hir::BinOpKind::Shr => Some("std::ops::ShrAssign"),
308 if let Some(missing_trait) = missing_trait {
309 if op.node == hir::BinOpKind::Add
310 && self.check_str_addition(
311 lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, true, op,
314 // This has nothing here because it means we did string
315 // concatenation (e.g., "Hello " += "World!"). This means
316 // we don't want the note in the else clause to be emitted
317 } else if let ty::Param(_) = lhs_ty.kind {
318 // FIXME: point to span of param
320 "`{}` might need a bound for `{}`",
321 lhs_ty, missing_trait
323 } else if !suggested_deref {
324 suggest_impl_missing(&mut err, lhs_ty, &missing_trait);
330 let (message, missing_trait) = match op.node {
331 hir::BinOpKind::Add => (
332 format!("cannot add `{}` to `{}`", rhs_ty, lhs_ty),
333 Some("std::ops::Add"),
335 hir::BinOpKind::Sub => (
336 format!("cannot subtract `{}` from `{}`", rhs_ty, lhs_ty),
337 Some("std::ops::Sub"),
339 hir::BinOpKind::Mul => (
340 format!("cannot multiply `{}` to `{}`", rhs_ty, lhs_ty),
341 Some("std::ops::Mul"),
343 hir::BinOpKind::Div => (
344 format!("cannot divide `{}` by `{}`", lhs_ty, rhs_ty),
345 Some("std::ops::Div"),
347 hir::BinOpKind::Rem => (
348 format!("cannot mod `{}` by `{}`", lhs_ty, rhs_ty),
349 Some("std::ops::Rem"),
351 hir::BinOpKind::BitAnd => (
352 format!("no implementation for `{} & {}`", lhs_ty, rhs_ty),
353 Some("std::ops::BitAnd"),
355 hir::BinOpKind::BitXor => (
356 format!("no implementation for `{} ^ {}`", lhs_ty, rhs_ty),
357 Some("std::ops::BitXor"),
359 hir::BinOpKind::BitOr => (
360 format!("no implementation for `{} | {}`", lhs_ty, rhs_ty),
361 Some("std::ops::BitOr"),
363 hir::BinOpKind::Shl => (
364 format!("no implementation for `{} << {}`", lhs_ty, rhs_ty),
365 Some("std::ops::Shl"),
367 hir::BinOpKind::Shr => (
368 format!("no implementation for `{} >> {}`", lhs_ty, rhs_ty),
369 Some("std::ops::Shr"),
371 hir::BinOpKind::Eq | hir::BinOpKind::Ne => (
373 "binary operation `{}` cannot be applied to type `{}`",
377 Some("std::cmp::PartialEq"),
382 | hir::BinOpKind::Ge => (
384 "binary operation `{}` cannot be applied to type `{}`",
388 Some("std::cmp::PartialOrd"),
392 "binary operation `{}` cannot be applied to type `{}`",
399 let mut err = struct_span_err!(
407 let mut involves_fn = false;
408 if !lhs_expr.span.eq(&rhs_expr.span) {
409 involves_fn |= self.add_type_neq_err_label(
417 involves_fn |= self.add_type_neq_err_label(
427 let mut suggested_deref = false;
428 if let Ref(_, rty, _) = lhs_ty.kind {
430 self.infcx.type_is_copy_modulo_regions(
435 .lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign))
438 if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
440 "`{}` can be used on '{}', you can \
441 dereference `{2}`: `*{2}`",
446 suggested_deref = true;
450 if let Some(missing_trait) = missing_trait {
451 if op.node == hir::BinOpKind::Add
452 && self.check_str_addition(
453 lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, false, op,
456 // This has nothing here because it means we did string
457 // concatenation (e.g., "Hello " + "World!"). This means
458 // we don't want the note in the else clause to be emitted
459 } else if let ty::Param(_) = lhs_ty.kind {
460 // FIXME: point to span of param
462 "`{}` might need a bound for `{}`",
463 lhs_ty, missing_trait
465 } else if !suggested_deref && !involves_fn {
466 suggest_impl_missing(&mut err, lhs_ty, &missing_trait);
477 (lhs_ty, rhs_ty, return_ty)
480 /// If one of the types is an uncalled function and calling it would yield the other type,
481 /// suggest calling the function. Returns whether a suggestion was given.
482 fn add_type_neq_err_label(
484 err: &mut rustc_errors::DiagnosticBuilder<'_>,
490 ) -> bool /* did we suggest to call a function because of missing parenthesis? */ {
491 err.span_label(span, ty.to_string());
492 if let FnDef(def_id, _) = ty.kind {
493 let source_map = self.tcx.sess.source_map();
494 let hir_id = match self.tcx.hir().as_local_hir_id(def_id) {
495 Some(hir_id) => hir_id,
496 None => return false,
498 if !self.tcx.has_typeck_tables(def_id) {
502 match self.tcx.typeck_tables_of(def_id).liberated_fn_sigs().get(hir_id) {
505 bug!("No fn-sig entry for def_id={:?}", def_id);
510 let other_ty = if let FnDef(def_id, _) = other_ty.kind {
511 let hir_id = match self.tcx.hir().as_local_hir_id(def_id) {
512 Some(hir_id) => hir_id,
513 None => return false,
515 if !self.tcx.has_typeck_tables(def_id) {
518 match self.tcx.typeck_tables_of(def_id).liberated_fn_sigs().get(hir_id) {
519 Some(f) => f.clone().output(),
521 bug!("No fn-sig entry for def_id={:?}", def_id);
529 .lookup_op_method(fn_sig.output(), &[other_ty], Op::Binary(op, is_assign))
532 let (variable_snippet, applicability) = if !fn_sig.inputs().is_empty() {
534 format!("{}( /* arguments */ )", source_map.span_to_snippet(span).unwrap()),
535 Applicability::HasPlaceholders,
539 format!("{}()", source_map.span_to_snippet(span).unwrap()),
540 Applicability::MaybeIncorrect,
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 rustc_errors::DiagnosticBuilder<'_>,
571 let source_map = self.tcx.sess.source_map();
572 let remove_borrow_msg = "String concatenation appends the string on the right to the \
573 string on the left and may require reallocation. This \
574 requires ownership of the string on the left";
576 let msg = "`to_owned()` can be used to create an owned `String` \
577 from a string reference. String concatenation \
578 appends the string on the right to the string \
579 on the left and may require reallocation. This \
580 requires ownership of the string on the left";
582 let is_std_string = |ty| &format!("{:?}", ty) == "std::string::String";
584 match (&lhs_ty.kind, &rhs_ty.kind) {
585 (&Ref(_, l_ty, _), &Ref(_, r_ty, _)) // &str or &String + &str, &String or &&str
586 if (l_ty.kind == Str || is_std_string(l_ty)) && (
587 r_ty.kind == Str || is_std_string(r_ty) ||
588 &format!("{:?}", rhs_ty) == "&&str"
591 if !is_assign { // Do not supply this message if `&str += &str`
594 "`+` cannot be used to concatenate two `&str` strings",
596 match source_map.span_to_snippet(lhs_expr.span) {
600 if lstring.starts_with('&') {
605 if lstring.starts_with('&') {
606 // let a = String::new();
607 // let _ = &a + "bar";
608 lstring[1..].to_string()
610 format!("{}.to_owned()", lstring)
612 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`",
628 source_map.span_to_snippet(lhs_expr.span),
629 source_map.span_to_snippet(rhs_expr.span),
632 (Ok(l), Ok(r), false) => {
633 let to_string = if l.starts_with('&') {
634 // let a = String::new(); let b = String::new();
638 format!("{}.to_owned()", l)
640 err.multipart_suggestion(
643 (lhs_expr.span, to_string),
644 (rhs_expr.span, format!("&{}", r)),
646 Applicability::MachineApplicable,
659 pub fn check_user_unop(
661 ex: &'tcx hir::Expr<'tcx>,
662 operand_ty: Ty<'tcx>,
665 assert!(op.is_by_value());
666 match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) {
668 self.write_method_call(ex.hir_id, method);
672 let actual = self.resolve_vars_if_possible(&operand_ty);
673 if !actual.references_error() {
674 let mut err = struct_span_err!(
678 "cannot apply unary operator `{}` to type `{}`",
685 "cannot apply unary \
691 Uint(_) if op == hir::UnOp::UnNeg => {
692 err.note("unsigned values cannot be negated");
694 Str | Never | Char | Tuple(_) | Array(_, _) => {}
695 Ref(_, ref lty, _) if lty.kind == Str => {}
697 let missing_trait = match op {
698 hir::UnOp::UnNeg => "std::ops::Neg",
699 hir::UnOp::UnNot => "std::ops::Not",
700 hir::UnOp::UnDeref => "std::ops::UnDerf",
702 suggest_impl_missing(&mut err, operand_ty, &missing_trait);
715 other_tys: &[Ty<'tcx>],
717 ) -> Result<MethodCallee<'tcx>, ()> {
718 let lang = self.tcx.lang_items();
720 let span = match op {
721 Op::Binary(op, _) => op.span,
722 Op::Unary(_, span) => span,
724 let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
726 hir::BinOpKind::Add => ("add_assign", lang.add_assign_trait()),
727 hir::BinOpKind::Sub => ("sub_assign", lang.sub_assign_trait()),
728 hir::BinOpKind::Mul => ("mul_assign", lang.mul_assign_trait()),
729 hir::BinOpKind::Div => ("div_assign", lang.div_assign_trait()),
730 hir::BinOpKind::Rem => ("rem_assign", lang.rem_assign_trait()),
731 hir::BinOpKind::BitXor => ("bitxor_assign", lang.bitxor_assign_trait()),
732 hir::BinOpKind::BitAnd => ("bitand_assign", lang.bitand_assign_trait()),
733 hir::BinOpKind::BitOr => ("bitor_assign", lang.bitor_assign_trait()),
734 hir::BinOpKind::Shl => ("shl_assign", lang.shl_assign_trait()),
735 hir::BinOpKind::Shr => ("shr_assign", lang.shr_assign_trait()),
742 | hir::BinOpKind::And
743 | hir::BinOpKind::Or => {
744 span_bug!(span, "impossible assignment operation: {}=", op.node.as_str())
747 } else if let Op::Binary(op, IsAssign::No) = op {
749 hir::BinOpKind::Add => ("add", lang.add_trait()),
750 hir::BinOpKind::Sub => ("sub", lang.sub_trait()),
751 hir::BinOpKind::Mul => ("mul", lang.mul_trait()),
752 hir::BinOpKind::Div => ("div", lang.div_trait()),
753 hir::BinOpKind::Rem => ("rem", lang.rem_trait()),
754 hir::BinOpKind::BitXor => ("bitxor", lang.bitxor_trait()),
755 hir::BinOpKind::BitAnd => ("bitand", lang.bitand_trait()),
756 hir::BinOpKind::BitOr => ("bitor", lang.bitor_trait()),
757 hir::BinOpKind::Shl => ("shl", lang.shl_trait()),
758 hir::BinOpKind::Shr => ("shr", lang.shr_trait()),
759 hir::BinOpKind::Lt => ("lt", lang.partial_ord_trait()),
760 hir::BinOpKind::Le => ("le", lang.partial_ord_trait()),
761 hir::BinOpKind::Ge => ("ge", lang.partial_ord_trait()),
762 hir::BinOpKind::Gt => ("gt", lang.partial_ord_trait()),
763 hir::BinOpKind::Eq => ("eq", lang.eq_trait()),
764 hir::BinOpKind::Ne => ("ne", lang.eq_trait()),
765 hir::BinOpKind::And | hir::BinOpKind::Or => {
766 span_bug!(span, "&& and || are not overloadable")
769 } else if let Op::Unary(hir::UnOp::UnNot, _) = op {
770 ("not", lang.not_trait())
771 } else if let Op::Unary(hir::UnOp::UnNeg, _) = op {
772 ("neg", lang.neg_trait())
774 bug!("lookup_op_method: op not supported: {:?}", op)
778 "lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
779 lhs_ty, op, opname, trait_did
782 let method = trait_did.and_then(|trait_did| {
783 let opname = Ident::from_str(opname);
784 self.lookup_method_in_trait(span, opname, trait_did, lhs_ty, Some(other_tys))
789 let method = self.register_infer_ok_obligations(ok);
790 self.select_obligations_where_possible(false, |_| {});
799 // Binary operator categories. These categories summarize the behavior
800 // with respect to the builtin operationrs supported.
802 /// &&, || -- cannot be overridden
805 /// <<, >> -- when shifting a single integer, rhs can be any
806 /// integer type. For simd, types must match.
809 /// +, -, etc -- takes equal types, produces same type as input,
810 /// applicable to ints/floats/simd
813 /// &, |, ^ -- takes equal types, produces same type as input,
814 /// applicable to ints/floats/simd/bool
817 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
818 /// which produce the input type
823 fn from(op: hir::BinOp) -> BinOpCategory {
825 hir::BinOpKind::Shl | hir::BinOpKind::Shr => BinOpCategory::Shift,
828 | hir::BinOpKind::Sub
829 | hir::BinOpKind::Mul
830 | hir::BinOpKind::Div
831 | hir::BinOpKind::Rem => BinOpCategory::Math,
833 hir::BinOpKind::BitXor | hir::BinOpKind::BitAnd | hir::BinOpKind::BitOr => {
834 BinOpCategory::Bitwise
842 | hir::BinOpKind::Gt => BinOpCategory::Comparison,
844 hir::BinOpKind::And | hir::BinOpKind::Or => BinOpCategory::Shortcircuit,
849 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
850 #[derive(Clone, Copy, Debug, PartialEq)]
856 #[derive(Clone, Copy, Debug)]
858 Binary(hir::BinOp, IsAssign),
859 Unary(hir::UnOp, Span),
862 /// Dereferences a single level of immutable referencing.
863 fn deref_ty_if_possible<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
865 ty::Ref(_, ty, hir::Mutability::Not) => ty,
870 /// Returns `true` if this is a built-in arithmetic operation (e.g., u32
871 /// + u32, i16x4 == i16x4) and false if these types would have to be
872 /// overloaded to be legal. There are two reasons that we distinguish
873 /// builtin operations from overloaded ones (vs trying to drive
874 /// everything uniformly through the trait system and intrinsics or
875 /// something like that):
877 /// 1. Builtin operations can trivially be evaluated in constants.
878 /// 2. For comparison operators applied to SIMD types the result is
879 /// not of type `bool`. For example, `i16x4 == i16x4` yields a
880 /// type like `i16x4`. This means that the overloaded trait
881 /// `PartialEq` is not applicable.
883 /// Reason #2 is the killer. I tried for a while to always use
884 /// overloaded logic and just check the types in constants/codegen after
885 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
886 fn is_builtin_binop<'tcx>(lhs: Ty<'tcx>, rhs: Ty<'tcx>, op: hir::BinOp) -> bool {
887 // Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
888 // (See https://github.com/rust-lang/rust/issues/57447.)
889 let (lhs, rhs) = (deref_ty_if_possible(lhs), deref_ty_if_possible(rhs));
891 match BinOpCategory::from(op) {
892 BinOpCategory::Shortcircuit => true,
894 BinOpCategory::Shift => {
895 lhs.references_error()
896 || rhs.references_error()
897 || lhs.is_integral() && rhs.is_integral()
900 BinOpCategory::Math => {
901 lhs.references_error()
902 || rhs.references_error()
903 || lhs.is_integral() && rhs.is_integral()
904 || lhs.is_floating_point() && rhs.is_floating_point()
907 BinOpCategory::Bitwise => {
908 lhs.references_error()
909 || rhs.references_error()
910 || lhs.is_integral() && rhs.is_integral()
911 || lhs.is_floating_point() && rhs.is_floating_point()
912 || lhs.is_bool() && rhs.is_bool()
915 BinOpCategory::Comparison => {
916 lhs.references_error() || rhs.references_error() || lhs.is_scalar() && rhs.is_scalar()
921 /// If applicable, note that an implementation of `trait` for `ty` may fix the error.
922 fn suggest_impl_missing(err: &mut DiagnosticBuilder<'_>, ty: Ty<'_>, missing_trait: &str) {
923 if let Adt(def, _) = ty.peel_refs().kind {
924 if def.did.is_local() {
926 "an implementation of `{}` might \
927 be missing for `{}`",