1 //! Code related to processing overloaded binary and unary operators.
3 use super::method::MethodCallee;
4 use super::{FnCtxt, Needs};
5 use rustc_ast::ast::Ident;
6 use rustc_errors::{self, struct_span_err, Applicability, DiagnosticBuilder};
8 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
9 use rustc_middle::ty::adjustment::{
10 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
12 use rustc_middle::ty::TyKind::{Adt, Array, Char, FnDef, Never, Ref, Str, Tuple, Uint};
13 use rustc_middle::ty::{self, suggest_constraining_type_param, Ty, TyCtxt, TypeFoldable};
15 use rustc_trait_selection::infer::InferCtxtExt;
17 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
18 /// Checks a `a <op>= b`
19 pub fn check_binop_assign(
21 expr: &'tcx hir::Expr<'tcx>,
23 lhs: &'tcx hir::Expr<'tcx>,
24 rhs: &'tcx hir::Expr<'tcx>,
26 let (lhs_ty, rhs_ty, return_ty) =
27 self.check_overloaded_binop(expr, lhs, rhs, op, IsAssign::Yes);
30 if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() && is_builtin_binop(lhs_ty, rhs_ty, op) {
31 self.enforce_builtin_binop_types(&lhs.span, lhs_ty, &rhs.span, rhs_ty, op);
37 self.check_lhs_assignable(lhs, "E0067", &op.span);
42 /// Checks a potentially overloaded binary operator.
45 expr: &'tcx hir::Expr<'tcx>,
47 lhs_expr: &'tcx hir::Expr<'tcx>,
48 rhs_expr: &'tcx hir::Expr<'tcx>,
53 "check_binop(expr.hir_id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
54 expr.hir_id, expr, op, lhs_expr, rhs_expr
57 match BinOpCategory::from(op) {
58 BinOpCategory::Shortcircuit => {
59 // && and || are a simple case.
60 self.check_expr_coercable_to_type(lhs_expr, tcx.types.bool);
61 let lhs_diverges = self.diverges.get();
62 self.check_expr_coercable_to_type(rhs_expr, tcx.types.bool);
64 // Depending on the LHS' value, the RHS can never execute.
65 self.diverges.set(lhs_diverges);
70 // Otherwise, we always treat operators as if they are
71 // overloaded. This is the way to be most flexible w/r/t
72 // types that get inferred.
73 let (lhs_ty, rhs_ty, return_ty) =
74 self.check_overloaded_binop(expr, lhs_expr, rhs_expr, op, IsAssign::No);
76 // Supply type inference hints if relevant. Probably these
77 // hints should be enforced during select as part of the
78 // `consider_unification_despite_ambiguity` routine, but this
79 // more convenient for now.
81 // The basic idea is to help type inference by taking
82 // advantage of things we know about how the impls for
83 // scalar types are arranged. This is important in a
84 // scenario like `1_u32 << 2`, because it lets us quickly
85 // deduce that the result type should be `u32`, even
86 // though we don't know yet what type 2 has and hence
87 // can't pin this down to a specific impl.
88 if !lhs_ty.is_ty_var()
89 && !rhs_ty.is_ty_var()
90 && is_builtin_binop(lhs_ty, rhs_ty, op)
92 let builtin_return_ty = self.enforce_builtin_binop_types(
99 self.demand_suptype(expr.span, builtin_return_ty, return_ty);
107 fn enforce_builtin_binop_types(
115 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
117 // Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
118 // (See https://github.com/rust-lang/rust/issues/57447.)
119 let (lhs_ty, rhs_ty) = (deref_ty_if_possible(lhs_ty), deref_ty_if_possible(rhs_ty));
122 match BinOpCategory::from(op) {
123 BinOpCategory::Shortcircuit => {
124 self.demand_suptype(*lhs_span, tcx.mk_bool(), lhs_ty);
125 self.demand_suptype(*rhs_span, tcx.mk_bool(), rhs_ty);
129 BinOpCategory::Shift => {
130 // result type is same as LHS always
134 BinOpCategory::Math | BinOpCategory::Bitwise => {
135 // both LHS and RHS and result will have the same type
136 self.demand_suptype(*rhs_span, lhs_ty, rhs_ty);
140 BinOpCategory::Comparison => {
141 // both LHS and RHS and result will have the same type
142 self.demand_suptype(*rhs_span, lhs_ty, rhs_ty);
148 fn check_overloaded_binop(
150 expr: &'tcx hir::Expr<'tcx>,
151 lhs_expr: &'tcx hir::Expr<'tcx>,
152 rhs_expr: &'tcx hir::Expr<'tcx>,
155 ) -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>) {
157 "check_overloaded_binop(expr.hir_id={}, op={:?}, is_assign={:?})",
158 expr.hir_id, op, is_assign
161 let lhs_ty = match is_assign {
163 // Find a suitable supertype of the LHS expression's type, by coercing to
164 // a type variable, to pass as the `Self` to the trait, avoiding invariant
165 // trait matching creating lifetime constraints that are too strict.
166 // e.g., adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
167 // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`.
168 let lhs_ty = self.check_expr_with_needs(lhs_expr, Needs::None);
169 let fresh_var = self.next_ty_var(TypeVariableOrigin {
170 kind: TypeVariableOriginKind::MiscVariable,
173 self.demand_coerce(lhs_expr, lhs_ty, fresh_var, AllowTwoPhase::No)
176 // rust-lang/rust#52126: We have to use strict
177 // equivalence on the LHS of an assign-op like `+=`;
178 // overwritten or mutably-borrowed places cannot be
179 // coerced to a supertype.
180 self.check_expr_with_needs(lhs_expr, Needs::MutPlace)
183 let lhs_ty = self.resolve_vars_with_obligations(lhs_ty);
185 // N.B., as we have not yet type-checked the RHS, we don't have the
186 // type at hand. Make a variable to represent it. The whole reason
187 // for this indirection is so that, below, we can check the expr
188 // using this variable as the expected type, which sometimes lets
189 // us do better coercions than we would be able to do otherwise,
190 // particularly for things like `String + &String`.
191 let rhs_ty_var = self.next_ty_var(TypeVariableOrigin {
192 kind: TypeVariableOriginKind::MiscVariable,
196 let result = self.lookup_op_method(lhs_ty, &[rhs_ty_var], Op::Binary(op, is_assign));
199 let rhs_ty = self.check_expr_coercable_to_type(rhs_expr, rhs_ty_var);
200 let rhs_ty = self.resolve_vars_with_obligations(rhs_ty);
202 let return_ty = match result {
204 let by_ref_binop = !op.node.is_by_value();
205 if is_assign == IsAssign::Yes || by_ref_binop {
206 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
207 let mutbl = match mutbl {
208 hir::Mutability::Not => AutoBorrowMutability::Not,
209 hir::Mutability::Mut => AutoBorrowMutability::Mut {
210 // Allow two-phase borrows for binops in initial deployment
211 // since they desugar to methods
212 allow_two_phase_borrow: AllowTwoPhase::Yes,
215 let autoref = Adjustment {
216 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
217 target: method.sig.inputs()[0],
219 self.apply_adjustments(lhs_expr, vec![autoref]);
223 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[1].kind {
224 let mutbl = match mutbl {
225 hir::Mutability::Not => AutoBorrowMutability::Not,
226 hir::Mutability::Mut => AutoBorrowMutability::Mut {
227 // Allow two-phase borrows for binops in initial deployment
228 // since they desugar to methods
229 allow_two_phase_borrow: AllowTwoPhase::Yes,
232 let autoref = Adjustment {
233 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
234 target: method.sig.inputs()[1],
236 // HACK(eddyb) Bypass checks due to reborrows being in
237 // some cases applied on the RHS, on top of which we need
238 // to autoref, which is not allowed by apply_adjustments.
239 // self.apply_adjustments(rhs_expr, vec![autoref]);
243 .entry(rhs_expr.hir_id)
248 self.write_method_call(expr.hir_id, method);
253 // error types are considered "builtin"
254 if !lhs_ty.references_error() && !rhs_ty.references_error() {
255 let source_map = self.tcx.sess.source_map();
259 let mut err = struct_span_err!(
263 "binary assignment operation `{}=` cannot be applied to type `{}`",
269 format!("cannot use `{}=` on type `{}`", op.node.as_str(), lhs_ty),
271 let mut suggested_deref = false;
272 if let Ref(_, rty, _) = lhs_ty.kind {
274 self.infcx.type_is_copy_modulo_regions(
279 .lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign))
282 if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
284 "`{}=` can be used on '{}', you can dereference `{}`",
292 format!("*{}", lstring),
293 rustc_errors::Applicability::MachineApplicable,
295 suggested_deref = true;
299 let missing_trait = match op.node {
300 hir::BinOpKind::Add => Some("std::ops::AddAssign"),
301 hir::BinOpKind::Sub => Some("std::ops::SubAssign"),
302 hir::BinOpKind::Mul => Some("std::ops::MulAssign"),
303 hir::BinOpKind::Div => Some("std::ops::DivAssign"),
304 hir::BinOpKind::Rem => Some("std::ops::RemAssign"),
305 hir::BinOpKind::BitAnd => Some("std::ops::BitAndAssign"),
306 hir::BinOpKind::BitXor => Some("std::ops::BitXorAssign"),
307 hir::BinOpKind::BitOr => Some("std::ops::BitOrAssign"),
308 hir::BinOpKind::Shl => Some("std::ops::ShlAssign"),
309 hir::BinOpKind::Shr => Some("std::ops::ShrAssign"),
312 if let Some(missing_trait) = missing_trait {
313 if op.node == hir::BinOpKind::Add
314 && self.check_str_addition(
315 lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, true, op,
318 // This has nothing here because it means we did string
319 // concatenation (e.g., "Hello " += "World!"). This means
320 // we don't want the note in the else clause to be emitted
321 } else if let ty::Param(p) = lhs_ty.kind {
322 suggest_constraining_param(
332 } else if !suggested_deref {
333 suggest_impl_missing(&mut err, lhs_ty, &missing_trait);
339 let (message, missing_trait, use_output) = match op.node {
340 hir::BinOpKind::Add => (
341 format!("cannot add `{}` to `{}`", rhs_ty, lhs_ty),
342 Some("std::ops::Add"),
345 hir::BinOpKind::Sub => (
346 format!("cannot subtract `{}` from `{}`", rhs_ty, lhs_ty),
347 Some("std::ops::Sub"),
350 hir::BinOpKind::Mul => (
351 format!("cannot multiply `{}` to `{}`", rhs_ty, lhs_ty),
352 Some("std::ops::Mul"),
355 hir::BinOpKind::Div => (
356 format!("cannot divide `{}` by `{}`", lhs_ty, rhs_ty),
357 Some("std::ops::Div"),
360 hir::BinOpKind::Rem => (
361 format!("cannot mod `{}` by `{}`", lhs_ty, rhs_ty),
362 Some("std::ops::Rem"),
365 hir::BinOpKind::BitAnd => (
366 format!("no implementation for `{} & {}`", lhs_ty, rhs_ty),
367 Some("std::ops::BitAnd"),
370 hir::BinOpKind::BitXor => (
371 format!("no implementation for `{} ^ {}`", lhs_ty, rhs_ty),
372 Some("std::ops::BitXor"),
375 hir::BinOpKind::BitOr => (
376 format!("no implementation for `{} | {}`", lhs_ty, rhs_ty),
377 Some("std::ops::BitOr"),
380 hir::BinOpKind::Shl => (
381 format!("no implementation for `{} << {}`", lhs_ty, rhs_ty),
382 Some("std::ops::Shl"),
385 hir::BinOpKind::Shr => (
386 format!("no implementation for `{} >> {}`", lhs_ty, rhs_ty),
387 Some("std::ops::Shr"),
390 hir::BinOpKind::Eq | hir::BinOpKind::Ne => (
392 "binary operation `{}` cannot be applied to type `{}`",
396 Some("std::cmp::PartialEq"),
402 | hir::BinOpKind::Ge => (
404 "binary operation `{}` cannot be applied to type `{}`",
408 Some("std::cmp::PartialOrd"),
413 "binary operation `{}` cannot be applied to type `{}`",
421 let mut err = struct_span_err!(
429 let mut involves_fn = false;
430 if !lhs_expr.span.eq(&rhs_expr.span) {
431 involves_fn |= self.add_type_neq_err_label(
439 involves_fn |= self.add_type_neq_err_label(
449 let mut suggested_deref = false;
450 if let Ref(_, rty, _) = lhs_ty.kind {
452 self.infcx.type_is_copy_modulo_regions(
457 .lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign))
460 if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
462 "`{}` can be used on '{}', you can \
463 dereference `{2}`: `*{2}`",
468 suggested_deref = true;
472 if let Some(missing_trait) = missing_trait {
473 if op.node == hir::BinOpKind::Add
474 && self.check_str_addition(
475 lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, false, op,
478 // This has nothing here because it means we did string
479 // concatenation (e.g., "Hello " + "World!"). This means
480 // we don't want the note in the else clause to be emitted
481 } else if let ty::Param(p) = lhs_ty.kind {
482 suggest_constraining_param(
492 } else if !suggested_deref && !involves_fn {
493 suggest_impl_missing(&mut err, lhs_ty, &missing_trait);
504 (lhs_ty, rhs_ty, return_ty)
507 /// If one of the types is an uncalled function and calling it would yield the other type,
508 /// suggest calling the function. Returns `true` if suggestion would apply (even if not given).
509 fn add_type_neq_err_label(
511 err: &mut rustc_errors::DiagnosticBuilder<'_>,
517 ) -> bool /* did we suggest to call a function because of missing parenthesis? */ {
518 err.span_label(span, ty.to_string());
519 if let FnDef(def_id, _) = ty.kind {
520 let source_map = self.tcx.sess.source_map();
521 if !self.tcx.has_typeck_tables(def_id) {
524 // We're emitting a suggestion, so we can just ignore regions
525 let fn_sig = *self.tcx.fn_sig(def_id).skip_binder();
527 let other_ty = if let FnDef(def_id, _) = other_ty.kind {
528 if !self.tcx.has_typeck_tables(def_id) {
531 // We're emitting a suggestion, so we can just ignore regions
532 self.tcx.fn_sig(def_id).skip_binder().output()
538 .lookup_op_method(fn_sig.output(), &[other_ty], Op::Binary(op, is_assign))
541 if let Ok(snippet) = source_map.span_to_snippet(span) {
542 let (variable_snippet, applicability) = if !fn_sig.inputs().is_empty() {
543 (format!("{}( /* arguments */ )", snippet), Applicability::HasPlaceholders)
545 (format!("{}()", snippet), Applicability::MaybeIncorrect)
550 "you might have forgotten to call this function",
561 /// Provide actionable suggestions when trying to add two strings with incorrect types,
562 /// like `&str + &str`, `String + String` and `&str + &String`.
564 /// If this function returns `true` it means a note was printed, so we don't need
565 /// to print the normal "implementation of `std::ops::Add` might be missing" note
566 fn check_str_addition(
568 lhs_expr: &'tcx hir::Expr<'tcx>,
569 rhs_expr: &'tcx hir::Expr<'tcx>,
572 err: &mut rustc_errors::DiagnosticBuilder<'_>,
576 let source_map = self.tcx.sess.source_map();
577 let remove_borrow_msg = "String concatenation appends the string on the right to the \
578 string on the left and may require reallocation. This \
579 requires ownership of the string on the left";
581 let msg = "`to_owned()` can be used to create an owned `String` \
582 from a string reference. String concatenation \
583 appends the string on the right to the string \
584 on the left and may require reallocation. This \
585 requires ownership of the string on the left";
587 let is_std_string = |ty| &format!("{:?}", ty) == "std::string::String";
589 match (&lhs_ty.kind, &rhs_ty.kind) {
590 (&Ref(_, l_ty, _), &Ref(_, r_ty, _)) // &str or &String + &str, &String or &&str
591 if (l_ty.kind == Str || is_std_string(l_ty)) && (
592 r_ty.kind == Str || is_std_string(r_ty) ||
593 &format!("{:?}", rhs_ty) == "&&str"
596 if !is_assign { // Do not supply this message if `&str += &str`
599 "`+` cannot be used to concatenate two `&str` strings",
601 match source_map.span_to_snippet(lhs_expr.span) {
605 if lstring.starts_with('&') {
610 if lstring.starts_with('&') {
611 // let a = String::new();
612 // let _ = &a + "bar";
613 lstring[1..].to_string()
615 format!("{}.to_owned()", lstring)
617 Applicability::MachineApplicable,
625 (&Ref(_, l_ty, _), &Adt(..)) // Handle `&str` & `&String` + `String`
626 if (l_ty.kind == Str || is_std_string(l_ty)) && is_std_string(rhs_ty) =>
630 "`+` cannot be used to concatenate a `&str` with a `String`",
633 source_map.span_to_snippet(lhs_expr.span),
634 source_map.span_to_snippet(rhs_expr.span),
637 (Ok(l), Ok(r), false) => {
638 let to_string = if l.starts_with('&') {
639 // let a = String::new(); let b = String::new();
643 format!("{}.to_owned()", l)
645 err.multipart_suggestion(
648 (lhs_expr.span, to_string),
649 (rhs_expr.span, format!("&{}", r)),
651 Applicability::MachineApplicable,
664 pub fn check_user_unop(
666 ex: &'tcx hir::Expr<'tcx>,
667 operand_ty: Ty<'tcx>,
670 assert!(op.is_by_value());
671 match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) {
673 self.write_method_call(ex.hir_id, method);
677 let actual = self.resolve_vars_if_possible(&operand_ty);
678 if !actual.references_error() {
679 let mut err = struct_span_err!(
683 "cannot apply unary operator `{}` to type `{}`",
690 "cannot apply unary \
696 Uint(_) if op == hir::UnOp::UnNeg => {
697 err.note("unsigned values cannot be negated");
699 Str | Never | Char | Tuple(_) | Array(_, _) => {}
700 Ref(_, ref lty, _) if lty.kind == Str => {}
702 let missing_trait = match op {
703 hir::UnOp::UnNeg => "std::ops::Neg",
704 hir::UnOp::UnNot => "std::ops::Not",
705 hir::UnOp::UnDeref => "std::ops::UnDerf",
707 suggest_impl_missing(&mut err, operand_ty, &missing_trait);
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 /// Dereferences a single level of immutable referencing.
868 fn deref_ty_if_possible(ty: Ty<'tcx>) -> Ty<'tcx> {
870 ty::Ref(_, ty, hir::Mutability::Not) => ty,
875 /// Returns `true` if this is a built-in arithmetic operation (e.g., u32
876 /// + u32, i16x4 == i16x4) and false if these types would have to be
877 /// overloaded to be legal. There are two reasons that we distinguish
878 /// builtin operations from overloaded ones (vs trying to drive
879 /// everything uniformly through the trait system and intrinsics or
880 /// something like that):
882 /// 1. Builtin operations can trivially be evaluated in constants.
883 /// 2. For comparison operators applied to SIMD types the result is
884 /// not of type `bool`. For example, `i16x4 == i16x4` yields a
885 /// type like `i16x4`. This means that the overloaded trait
886 /// `PartialEq` is not applicable.
888 /// Reason #2 is the killer. I tried for a while to always use
889 /// overloaded logic and just check the types in constants/codegen after
890 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
891 fn is_builtin_binop<'tcx>(lhs: Ty<'tcx>, rhs: Ty<'tcx>, op: hir::BinOp) -> bool {
892 // Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
893 // (See https://github.com/rust-lang/rust/issues/57447.)
894 let (lhs, rhs) = (deref_ty_if_possible(lhs), deref_ty_if_possible(rhs));
896 match BinOpCategory::from(op) {
897 BinOpCategory::Shortcircuit => true,
899 BinOpCategory::Shift => {
900 lhs.references_error()
901 || rhs.references_error()
902 || lhs.is_integral() && rhs.is_integral()
905 BinOpCategory::Math => {
906 lhs.references_error()
907 || rhs.references_error()
908 || lhs.is_integral() && rhs.is_integral()
909 || lhs.is_floating_point() && rhs.is_floating_point()
912 BinOpCategory::Bitwise => {
913 lhs.references_error()
914 || rhs.references_error()
915 || lhs.is_integral() && rhs.is_integral()
916 || lhs.is_floating_point() && rhs.is_floating_point()
917 || lhs.is_bool() && rhs.is_bool()
920 BinOpCategory::Comparison => {
921 lhs.references_error() || rhs.references_error() || lhs.is_scalar() && rhs.is_scalar()
926 /// If applicable, note that an implementation of `trait` for `ty` may fix the error.
927 fn suggest_impl_missing(err: &mut DiagnosticBuilder<'_>, ty: Ty<'_>, missing_trait: &str) {
928 if let Adt(def, _) = ty.peel_refs().kind {
929 if def.did.is_local() {
931 "an implementation of `{}` might \
932 be missing for `{}`",
939 fn suggest_constraining_param(
942 mut err: &mut DiagnosticBuilder<'_>,
950 let msg = &format!("`{}` might need a bound for `{}`", lhs_ty, missing_trait);
951 // Try to find the def-id and details for the parameter p. We have only the index,
952 // so we have to find the enclosing function's def-id, then look through its declared
953 // generic parameters to get the declaration.
954 let def_id = hir.body_owner_def_id(hir::BodyId { hir_id: body_id });
955 let generics = tcx.generics_of(def_id);
956 let param_def_id = generics.type_param(&p, tcx).def_id;
957 if let Some(generics) = param_def_id
959 .map(|id| hir.as_local_hir_id(id))
960 .and_then(|id| hir.find(hir.get_parent_item(id)))
962 .and_then(|node| node.generics())
964 let output = if set_output { format!("<Output = {}>", rhs_ty) } else { String::new() };
965 suggest_constraining_type_param(
969 &format!("{}", lhs_ty),
970 &format!("{}{}", missing_trait, output),
974 let span = tcx.def_span(param_def_id);
975 err.span_label(span, msg);