1 //! Code related to processing overloaded binary and unary operators.
3 use super::method::MethodCallee;
4 use super::{FnCtxt, Needs};
5 use errors::{self, Applicability};
6 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
7 use rustc::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability};
8 use rustc::ty::TyKind::{Adt, Array, Char, FnDef, Never, Ref, Str, Tuple, Uint};
9 use rustc::ty::{self, Ty, TypeFoldable};
12 use syntax::ast::Ident;
14 use rustc_error_codes::*;
16 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17 /// Checks a `a <op>= b`
18 pub fn check_binop_assign(
20 expr: &'tcx hir::Expr<'tcx>,
22 lhs: &'tcx hir::Expr<'tcx>,
23 rhs: &'tcx hir::Expr<'tcx>,
25 let (lhs_ty, rhs_ty, return_ty) =
26 self.check_overloaded_binop(expr, lhs, rhs, op, IsAssign::Yes);
29 if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() && is_builtin_binop(lhs_ty, rhs_ty, op) {
30 self.enforce_builtin_binop_types(lhs, lhs_ty, rhs, rhs_ty, op);
36 self.check_lhs_assignable(lhs, "E0067", &op.span);
41 /// Checks a potentially overloaded binary operator.
44 expr: &'tcx hir::Expr<'tcx>,
46 lhs_expr: &'tcx hir::Expr<'tcx>,
47 rhs_expr: &'tcx hir::Expr<'tcx>,
52 "check_binop(expr.hir_id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
53 expr.hir_id, expr, op, lhs_expr, rhs_expr
56 match BinOpCategory::from(op) {
57 BinOpCategory::Shortcircuit => {
58 // && and || are a simple case.
59 self.check_expr_coercable_to_type(lhs_expr, tcx.types.bool);
60 let lhs_diverges = self.diverges.get();
61 self.check_expr_coercable_to_type(rhs_expr, tcx.types.bool);
63 // Depending on the LHS' value, the RHS can never execute.
64 self.diverges.set(lhs_diverges);
69 // Otherwise, we always treat operators as if they are
70 // overloaded. This is the way to be most flexible w/r/t
71 // types that get inferred.
72 let (lhs_ty, rhs_ty, return_ty) =
73 self.check_overloaded_binop(expr, lhs_expr, rhs_expr, op, IsAssign::No);
75 // Supply type inference hints if relevant. Probably these
76 // hints should be enforced during select as part of the
77 // `consider_unification_despite_ambiguity` routine, but this
78 // more convenient for now.
80 // The basic idea is to help type inference by taking
81 // advantage of things we know about how the impls for
82 // scalar types are arranged. This is important in a
83 // scenario like `1_u32 << 2`, because it lets us quickly
84 // deduce that the result type should be `u32`, even
85 // though we don't know yet what type 2 has and hence
86 // can't pin this down to a specific impl.
87 if !lhs_ty.is_ty_var()
88 && !rhs_ty.is_ty_var()
89 && is_builtin_binop(lhs_ty, rhs_ty, op)
91 let builtin_return_ty =
92 self.enforce_builtin_binop_types(lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
93 self.demand_suptype(expr.span, builtin_return_ty, return_ty);
101 fn enforce_builtin_binop_types(
103 lhs_expr: &'tcx hir::Expr<'tcx>,
105 rhs_expr: &'tcx hir::Expr<'tcx>,
109 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
112 match BinOpCategory::from(op) {
113 BinOpCategory::Shortcircuit => {
114 self.demand_suptype(lhs_expr.span, tcx.mk_bool(), lhs_ty);
115 self.demand_suptype(rhs_expr.span, tcx.mk_bool(), rhs_ty);
119 BinOpCategory::Shift => {
120 // result type is same as LHS always
124 BinOpCategory::Math | BinOpCategory::Bitwise => {
125 // both LHS and RHS and result will have the same type
126 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
130 BinOpCategory::Comparison => {
131 // both LHS and RHS and result will have the same type
132 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
138 fn check_overloaded_binop(
140 expr: &'tcx hir::Expr<'tcx>,
141 lhs_expr: &'tcx hir::Expr<'tcx>,
142 rhs_expr: &'tcx hir::Expr<'tcx>,
145 ) -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>) {
147 "check_overloaded_binop(expr.hir_id={}, op={:?}, is_assign={:?})",
148 expr.hir_id, op, is_assign
151 let lhs_ty = match is_assign {
153 // Find a suitable supertype of the LHS expression's type, by coercing to
154 // a type variable, to pass as the `Self` to the trait, avoiding invariant
155 // trait matching creating lifetime constraints that are too strict.
156 // e.g., adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
157 // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`.
158 let lhs_ty = self.check_expr_with_needs(lhs_expr, Needs::None);
159 let fresh_var = self.next_ty_var(TypeVariableOrigin {
160 kind: TypeVariableOriginKind::MiscVariable,
163 self.demand_coerce(lhs_expr, lhs_ty, fresh_var, AllowTwoPhase::No)
166 // rust-lang/rust#52126: We have to use strict
167 // equivalence on the LHS of an assign-op like `+=`;
168 // overwritten or mutably-borrowed places cannot be
169 // coerced to a supertype.
170 self.check_expr_with_needs(lhs_expr, Needs::MutPlace)
173 let lhs_ty = self.resolve_vars_with_obligations(lhs_ty);
175 // N.B., as we have not yet type-checked the RHS, we don't have the
176 // type at hand. Make a variable to represent it. The whole reason
177 // for this indirection is so that, below, we can check the expr
178 // using this variable as the expected type, which sometimes lets
179 // us do better coercions than we would be able to do otherwise,
180 // particularly for things like `String + &String`.
181 let rhs_ty_var = self.next_ty_var(TypeVariableOrigin {
182 kind: TypeVariableOriginKind::MiscVariable,
186 let result = self.lookup_op_method(lhs_ty, &[rhs_ty_var], Op::Binary(op, is_assign));
189 let rhs_ty = self.check_expr_coercable_to_type(rhs_expr, rhs_ty_var);
190 let rhs_ty = self.resolve_vars_with_obligations(rhs_ty);
192 let return_ty = match result {
194 let by_ref_binop = !op.node.is_by_value();
195 if is_assign == IsAssign::Yes || by_ref_binop {
196 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
197 let mutbl = match mutbl {
198 hir::Mutability::Not => AutoBorrowMutability::Not,
199 hir::Mutability::Mut => AutoBorrowMutability::Mut {
200 // Allow two-phase borrows for binops in initial deployment
201 // since they desugar to methods
202 allow_two_phase_borrow: AllowTwoPhase::Yes,
205 let autoref = Adjustment {
206 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
207 target: method.sig.inputs()[0],
209 self.apply_adjustments(lhs_expr, vec![autoref]);
213 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[1].kind {
214 let mutbl = match mutbl {
215 hir::Mutability::Not => AutoBorrowMutability::Not,
216 hir::Mutability::Mut => AutoBorrowMutability::Mut {
217 // Allow two-phase borrows for binops in initial deployment
218 // since they desugar to methods
219 allow_two_phase_borrow: AllowTwoPhase::Yes,
222 let autoref = Adjustment {
223 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
224 target: method.sig.inputs()[1],
226 // HACK(eddyb) Bypass checks due to reborrows being in
227 // some cases applied on the RHS, on top of which we need
228 // to autoref, which is not allowed by apply_adjustments.
229 // self.apply_adjustments(rhs_expr, vec![autoref]);
233 .entry(rhs_expr.hir_id)
238 self.write_method_call(expr.hir_id, method);
243 // error types are considered "builtin"
244 if !lhs_ty.references_error() {
245 let source_map = self.tcx.sess.source_map();
248 let mut err = struct_span_err!(
252 "binary assignment operation `{}=` cannot be applied to type `{}`",
258 format!("cannot use `{}=` on type `{}`", op.node.as_str(), lhs_ty),
260 let mut suggested_deref = false;
261 if let Ref(_, rty, _) = lhs_ty.kind {
263 self.infcx.type_is_copy_modulo_regions(
268 .lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign))
271 if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
273 "`{}=` can be used on '{}', you can dereference `{}`",
281 format!("*{}", lstring),
282 errors::Applicability::MachineApplicable,
284 suggested_deref = true;
288 let missing_trait = match op.node {
289 hir::BinOpKind::Add => Some("std::ops::AddAssign"),
290 hir::BinOpKind::Sub => Some("std::ops::SubAssign"),
291 hir::BinOpKind::Mul => Some("std::ops::MulAssign"),
292 hir::BinOpKind::Div => Some("std::ops::DivAssign"),
293 hir::BinOpKind::Rem => Some("std::ops::RemAssign"),
294 hir::BinOpKind::BitAnd => Some("std::ops::BitAndAssign"),
295 hir::BinOpKind::BitXor => Some("std::ops::BitXorAssign"),
296 hir::BinOpKind::BitOr => Some("std::ops::BitOrAssign"),
297 hir::BinOpKind::Shl => Some("std::ops::ShlAssign"),
298 hir::BinOpKind::Shr => Some("std::ops::ShrAssign"),
301 if let Some(missing_trait) = missing_trait {
302 if op.node == hir::BinOpKind::Add
303 && self.check_str_addition(
304 lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, true, op,
307 // This has nothing here because it means we did string
308 // concatenation (e.g., "Hello " += "World!"). This means
309 // we don't want the note in the else clause to be emitted
310 } else if let ty::Param(_) = lhs_ty.kind {
311 // FIXME: point to span of param
313 "`{}` might need a bound for `{}`",
314 lhs_ty, missing_trait
316 } else if !suggested_deref {
318 "an implementation of `{}` might \
319 be missing for `{}`",
320 missing_trait, lhs_ty
327 let (message, missing_trait) = match op.node {
328 hir::BinOpKind::Add => (
329 format!("cannot add `{}` to `{}`", rhs_ty, lhs_ty),
330 Some("std::ops::Add"),
332 hir::BinOpKind::Sub => (
333 format!("cannot substract `{}` from `{}`", rhs_ty, lhs_ty),
334 Some("std::ops::Sub"),
336 hir::BinOpKind::Mul => (
337 format!("cannot multiply `{}` to `{}`", rhs_ty, lhs_ty),
338 Some("std::ops::Mul"),
340 hir::BinOpKind::Div => (
341 format!("cannot divide `{}` by `{}`", lhs_ty, rhs_ty),
342 Some("std::ops::Div"),
344 hir::BinOpKind::Rem => (
345 format!("cannot mod `{}` by `{}`", lhs_ty, rhs_ty),
346 Some("std::ops::Rem"),
348 hir::BinOpKind::BitAnd => (
349 format!("no implementation for `{} & {}`", lhs_ty, rhs_ty),
350 Some("std::ops::BitAnd"),
352 hir::BinOpKind::BitXor => (
353 format!("no implementation for `{} ^ {}`", lhs_ty, rhs_ty),
354 Some("std::ops::BitXor"),
356 hir::BinOpKind::BitOr => (
357 format!("no implementation for `{} | {}`", lhs_ty, rhs_ty),
358 Some("std::ops::BitOr"),
360 hir::BinOpKind::Shl => (
361 format!("no implementation for `{} << {}`", lhs_ty, rhs_ty),
362 Some("std::ops::Shl"),
364 hir::BinOpKind::Shr => (
365 format!("no implementation for `{} >> {}`", lhs_ty, rhs_ty),
366 Some("std::ops::Shr"),
368 hir::BinOpKind::Eq | hir::BinOpKind::Ne => (
370 "binary operation `{}` cannot be applied to type `{}`",
374 Some("std::cmp::PartialEq"),
379 | hir::BinOpKind::Ge => (
381 "binary operation `{}` cannot be applied to type `{}`",
385 Some("std::cmp::PartialOrd"),
389 "binary operation `{}` cannot be applied to type `{}`",
396 let mut err = struct_span_err!(
404 let mut involves_fn = false;
405 if !lhs_expr.span.eq(&rhs_expr.span) {
406 involves_fn |= self.add_type_neq_err_label(
414 involves_fn |= self.add_type_neq_err_label(
424 let mut suggested_deref = false;
425 if let Ref(_, rty, _) = lhs_ty.kind {
427 self.infcx.type_is_copy_modulo_regions(
432 .lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign))
435 if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
437 "`{}` can be used on '{}', you can \
438 dereference `{2}`: `*{2}`",
443 suggested_deref = true;
447 if let Some(missing_trait) = missing_trait {
448 if op.node == hir::BinOpKind::Add
449 && self.check_str_addition(
450 lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, false, op,
453 // This has nothing here because it means we did string
454 // concatenation (e.g., "Hello " + "World!"). This means
455 // we don't want the note in the else clause to be emitted
456 } else if let ty::Param(_) = lhs_ty.kind {
457 // FIXME: point to span of param
459 "`{}` might need a bound for `{}`",
460 lhs_ty, missing_trait
462 } else if !suggested_deref && !involves_fn {
464 "an implementation of `{}` might \
465 be missing for `{}`",
466 missing_trait, lhs_ty
478 (lhs_ty, rhs_ty, return_ty)
481 /// If one of the types is an uncalled function and calling it would yield the other type,
482 /// suggest calling the function. Returns wether a suggestion was given.
483 fn add_type_neq_err_label(
485 err: &mut errors::DiagnosticBuilder<'_>,
491 ) -> bool /* did we suggest to call a function because of missing parenthesis? */ {
492 err.span_label(span, ty.to_string());
493 if let FnDef(def_id, _) = ty.kind {
494 let source_map = self.tcx.sess.source_map();
495 let hir_id = match self.tcx.hir().as_local_hir_id(def_id) {
496 Some(hir_id) => hir_id,
497 None => return false,
499 if self.tcx.has_typeck_tables(def_id) == false {
503 match self.tcx.typeck_tables_of(def_id).liberated_fn_sigs().get(hir_id) {
504 Some(f) => f.clone(),
506 bug!("No fn-sig entry for def_id={:?}", def_id);
511 let other_ty = if let FnDef(def_id, _) = other_ty.kind {
512 let hir_id = match self.tcx.hir().as_local_hir_id(def_id) {
513 Some(hir_id) => hir_id,
514 None => return false,
516 if self.tcx.has_typeck_tables(def_id) == false {
519 match self.tcx.typeck_tables_of(def_id).liberated_fn_sigs().get(hir_id) {
520 Some(f) => f.clone().output(),
522 bug!("No fn-sig entry for def_id={:?}", def_id);
530 .lookup_op_method(fn_sig.output(), &[other_ty], Op::Binary(op, is_assign))
533 let (variable_snippet, applicability) = if fn_sig.inputs().len() > 0 {
535 format!("{}( /* arguments */ )", source_map.span_to_snippet(span).unwrap()),
536 Applicability::HasPlaceholders,
540 format!("{}()", source_map.span_to_snippet(span).unwrap()),
541 Applicability::MaybeIncorrect,
547 "you might have forgotten to call this function",
557 /// Provide actionable suggestions when trying to add two strings with incorrect types,
558 /// like `&str + &str`, `String + String` and `&str + &String`.
560 /// If this function returns `true` it means a note was printed, so we don't need
561 /// to print the normal "implementation of `std::ops::Add` might be missing" note
562 fn check_str_addition(
564 lhs_expr: &'tcx hir::Expr<'tcx>,
565 rhs_expr: &'tcx hir::Expr<'tcx>,
568 err: &mut errors::DiagnosticBuilder<'_>,
572 let source_map = self.tcx.sess.source_map();
573 let remove_borrow_msg = "String concatenation appends the string on the right to the \
574 string on the left and may require reallocation. This \
575 requires ownership of the string on the left";
577 let msg = "`to_owned()` can be used to create an owned `String` \
578 from a string reference. String concatenation \
579 appends the string on the right to the string \
580 on the left and may require reallocation. This \
581 requires ownership of the string on the left";
583 let is_std_string = |ty| &format!("{:?}", ty) == "std::string::String";
585 match (&lhs_ty.kind, &rhs_ty.kind) {
586 (&Ref(_, l_ty, _), &Ref(_, r_ty, _)) // &str or &String + &str, &String or &&str
587 if (l_ty.kind == Str || is_std_string(l_ty)) && (
588 r_ty.kind == Str || is_std_string(r_ty) ||
589 &format!("{:?}", rhs_ty) == "&&str"
592 if !is_assign { // Do not supply this message if `&str += &str`
595 "`+` cannot be used to concatenate two `&str` strings",
597 match source_map.span_to_snippet(lhs_expr.span) {
601 if lstring.starts_with("&") {
606 if lstring.starts_with("&") {
607 // let a = String::new();
608 // let _ = &a + "bar";
609 format!("{}", &lstring[1..])
611 format!("{}.to_owned()", lstring)
613 Applicability::MachineApplicable,
621 (&Ref(_, l_ty, _), &Adt(..)) // Handle `&str` & `&String` + `String`
622 if (l_ty.kind == Str || is_std_string(l_ty)) && is_std_string(rhs_ty) =>
626 "`+` cannot be used to concatenate a `&str` with a `String`",
629 source_map.span_to_snippet(lhs_expr.span),
630 source_map.span_to_snippet(rhs_expr.span),
633 (Ok(l), Ok(r), false) => {
634 let to_string = if l.starts_with("&") {
635 // let a = String::new(); let b = String::new();
637 format!("{}", &l[1..])
639 format!("{}.to_owned()", l)
641 err.multipart_suggestion(
644 (lhs_expr.span, to_string),
645 (rhs_expr.span, format!("&{}", r)),
647 Applicability::MachineApplicable,
660 pub fn check_user_unop(
662 ex: &'tcx hir::Expr<'tcx>,
663 operand_ty: Ty<'tcx>,
666 assert!(op.is_by_value());
667 match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) {
669 self.write_method_call(ex.hir_id, method);
673 let actual = self.resolve_vars_if_possible(&operand_ty);
674 if !actual.references_error() {
675 let mut err = struct_span_err!(
679 "cannot apply unary operator `{}` to type `{}`",
686 "cannot apply unary \
692 Uint(_) if op == hir::UnOp::UnNeg => {
693 err.note("unsigned values cannot be negated");
695 Str | Never | Char | Tuple(_) | Array(_, _) => {}
696 Ref(_, ref lty, _) if lty.kind == Str => {}
698 let missing_trait = match op {
699 hir::UnOp::UnNeg => "std::ops::Neg",
700 hir::UnOp::UnNot => "std::ops::Not",
701 hir::UnOp::UnDeref => "std::ops::UnDerf",
704 "an implementation of `{}` might \
705 be missing for `{}`",
706 missing_trait, operand_ty
720 other_tys: &[Ty<'tcx>],
722 ) -> Result<MethodCallee<'tcx>, ()> {
723 let lang = self.tcx.lang_items();
725 let span = match op {
726 Op::Binary(op, _) => op.span,
727 Op::Unary(_, span) => span,
729 let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
731 hir::BinOpKind::Add => ("add_assign", lang.add_assign_trait()),
732 hir::BinOpKind::Sub => ("sub_assign", lang.sub_assign_trait()),
733 hir::BinOpKind::Mul => ("mul_assign", lang.mul_assign_trait()),
734 hir::BinOpKind::Div => ("div_assign", lang.div_assign_trait()),
735 hir::BinOpKind::Rem => ("rem_assign", lang.rem_assign_trait()),
736 hir::BinOpKind::BitXor => ("bitxor_assign", lang.bitxor_assign_trait()),
737 hir::BinOpKind::BitAnd => ("bitand_assign", lang.bitand_assign_trait()),
738 hir::BinOpKind::BitOr => ("bitor_assign", lang.bitor_assign_trait()),
739 hir::BinOpKind::Shl => ("shl_assign", lang.shl_assign_trait()),
740 hir::BinOpKind::Shr => ("shr_assign", lang.shr_assign_trait()),
747 | hir::BinOpKind::And
748 | hir::BinOpKind::Or => {
749 span_bug!(span, "impossible assignment operation: {}=", op.node.as_str())
752 } else if let Op::Binary(op, IsAssign::No) = op {
754 hir::BinOpKind::Add => ("add", lang.add_trait()),
755 hir::BinOpKind::Sub => ("sub", lang.sub_trait()),
756 hir::BinOpKind::Mul => ("mul", lang.mul_trait()),
757 hir::BinOpKind::Div => ("div", lang.div_trait()),
758 hir::BinOpKind::Rem => ("rem", lang.rem_trait()),
759 hir::BinOpKind::BitXor => ("bitxor", lang.bitxor_trait()),
760 hir::BinOpKind::BitAnd => ("bitand", lang.bitand_trait()),
761 hir::BinOpKind::BitOr => ("bitor", lang.bitor_trait()),
762 hir::BinOpKind::Shl => ("shl", lang.shl_trait()),
763 hir::BinOpKind::Shr => ("shr", lang.shr_trait()),
764 hir::BinOpKind::Lt => ("lt", lang.partial_ord_trait()),
765 hir::BinOpKind::Le => ("le", lang.partial_ord_trait()),
766 hir::BinOpKind::Ge => ("ge", lang.partial_ord_trait()),
767 hir::BinOpKind::Gt => ("gt", lang.partial_ord_trait()),
768 hir::BinOpKind::Eq => ("eq", lang.eq_trait()),
769 hir::BinOpKind::Ne => ("ne", lang.eq_trait()),
770 hir::BinOpKind::And | hir::BinOpKind::Or => {
771 span_bug!(span, "&& and || are not overloadable")
774 } else if let Op::Unary(hir::UnOp::UnNot, _) = op {
775 ("not", lang.not_trait())
776 } else if let Op::Unary(hir::UnOp::UnNeg, _) = op {
777 ("neg", lang.neg_trait())
779 bug!("lookup_op_method: op not supported: {:?}", op)
783 "lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
784 lhs_ty, op, opname, trait_did
787 let method = trait_did.and_then(|trait_did| {
788 let opname = Ident::from_str(opname);
789 self.lookup_method_in_trait(span, opname, trait_did, lhs_ty, Some(other_tys))
794 let method = self.register_infer_ok_obligations(ok);
795 self.select_obligations_where_possible(false, |_| {});
804 // Binary operator categories. These categories summarize the behavior
805 // with respect to the builtin operationrs supported.
807 /// &&, || -- cannot be overridden
810 /// <<, >> -- when shifting a single integer, rhs can be any
811 /// integer type. For simd, types must match.
814 /// +, -, etc -- takes equal types, produces same type as input,
815 /// applicable to ints/floats/simd
818 /// &, |, ^ -- takes equal types, produces same type as input,
819 /// applicable to ints/floats/simd/bool
822 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
823 /// which produce the input type
828 fn from(op: hir::BinOp) -> BinOpCategory {
830 hir::BinOpKind::Shl | hir::BinOpKind::Shr => BinOpCategory::Shift,
833 | hir::BinOpKind::Sub
834 | hir::BinOpKind::Mul
835 | hir::BinOpKind::Div
836 | hir::BinOpKind::Rem => BinOpCategory::Math,
838 hir::BinOpKind::BitXor | hir::BinOpKind::BitAnd | hir::BinOpKind::BitOr => {
839 BinOpCategory::Bitwise
847 | hir::BinOpKind::Gt => BinOpCategory::Comparison,
849 hir::BinOpKind::And | hir::BinOpKind::Or => BinOpCategory::Shortcircuit,
854 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
855 #[derive(Clone, Copy, Debug, PartialEq)]
861 #[derive(Clone, Copy, Debug)]
863 Binary(hir::BinOp, IsAssign),
864 Unary(hir::UnOp, Span),
867 /// Returns `true` if this is a built-in arithmetic operation (e.g., u32
868 /// + u32, i16x4 == i16x4) and false if these types would have to be
869 /// overloaded to be legal. There are two reasons that we distinguish
870 /// builtin operations from overloaded ones (vs trying to drive
871 /// everything uniformly through the trait system and intrinsics or
872 /// something like that):
874 /// 1. Builtin operations can trivially be evaluated in constants.
875 /// 2. For comparison operators applied to SIMD types the result is
876 /// not of type `bool`. For example, `i16x4 == i16x4` yields a
877 /// type like `i16x4`. This means that the overloaded trait
878 /// `PartialEq` is not applicable.
880 /// Reason #2 is the killer. I tried for a while to always use
881 /// overloaded logic and just check the types in constants/codegen after
882 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
883 fn is_builtin_binop(lhs: Ty<'_>, rhs: Ty<'_>, op: hir::BinOp) -> bool {
884 match BinOpCategory::from(op) {
885 BinOpCategory::Shortcircuit => true,
887 BinOpCategory::Shift => {
888 lhs.references_error()
889 || rhs.references_error()
890 || lhs.is_integral() && rhs.is_integral()
893 BinOpCategory::Math => {
894 lhs.references_error()
895 || rhs.references_error()
896 || lhs.is_integral() && rhs.is_integral()
897 || lhs.is_floating_point() && rhs.is_floating_point()
900 BinOpCategory::Bitwise => {
901 lhs.references_error()
902 || rhs.references_error()
903 || lhs.is_integral() && rhs.is_integral()
904 || lhs.is_floating_point() && rhs.is_floating_point()
905 || lhs.is_bool() && rhs.is_bool()
908 BinOpCategory::Comparison => {
909 lhs.references_error() || rhs.references_error() || lhs.is_scalar() && rhs.is_scalar()