1 //! Code related to processing overloaded binary and unary operators.
3 use super::method::MethodCallee;
4 use super::{has_expected_num_generic_args, FnCtxt};
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::fold::TypeFolder;
13 use rustc_middle::ty::TyKind::{Adt, Array, Char, FnDef, Never, Ref, Str, Tuple, Uint};
14 use rustc_middle::ty::{
15 self, suggest_constraining_type_param, Ty, TyCtxt, TypeFoldable, TypeVisitor,
17 use rustc_span::source_map::Spanned;
18 use rustc_span::symbol::{sym, Ident};
20 use rustc_trait_selection::infer::InferCtxtExt;
22 use std::ops::ControlFlow;
24 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25 /// Checks a `a <op>= b`
26 pub fn check_binop_assign(
28 expr: &'tcx hir::Expr<'tcx>,
30 lhs: &'tcx hir::Expr<'tcx>,
31 rhs: &'tcx hir::Expr<'tcx>,
33 let (lhs_ty, rhs_ty, return_ty) =
34 self.check_overloaded_binop(expr, lhs, rhs, op, IsAssign::Yes);
37 if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() && is_builtin_binop(lhs_ty, rhs_ty, op) {
38 self.enforce_builtin_binop_types(&lhs.span, lhs_ty, &rhs.span, rhs_ty, op);
44 self.check_lhs_assignable(lhs, "E0067", &op.span);
49 /// Checks a potentially overloaded binary operator.
52 expr: &'tcx hir::Expr<'tcx>,
54 lhs_expr: &'tcx hir::Expr<'tcx>,
55 rhs_expr: &'tcx hir::Expr<'tcx>,
60 "check_binop(expr.hir_id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
61 expr.hir_id, expr, op, lhs_expr, rhs_expr
64 match BinOpCategory::from(op) {
65 BinOpCategory::Shortcircuit => {
66 // && and || are a simple case.
67 self.check_expr_coercable_to_type(lhs_expr, tcx.types.bool, None);
68 let lhs_diverges = self.diverges.get();
69 self.check_expr_coercable_to_type(rhs_expr, tcx.types.bool, None);
71 // Depending on the LHS' value, the RHS can never execute.
72 self.diverges.set(lhs_diverges);
77 // Otherwise, we always treat operators as if they are
78 // overloaded. This is the way to be most flexible w/r/t
79 // types that get inferred.
80 let (lhs_ty, rhs_ty, return_ty) =
81 self.check_overloaded_binop(expr, lhs_expr, rhs_expr, op, IsAssign::No);
83 // Supply type inference hints if relevant. Probably these
84 // hints should be enforced during select as part of the
85 // `consider_unification_despite_ambiguity` routine, but this
86 // more convenient for now.
88 // The basic idea is to help type inference by taking
89 // advantage of things we know about how the impls for
90 // scalar types are arranged. This is important in a
91 // scenario like `1_u32 << 2`, because it lets us quickly
92 // deduce that the result type should be `u32`, even
93 // though we don't know yet what type 2 has and hence
94 // can't pin this down to a specific impl.
95 if !lhs_ty.is_ty_var()
96 && !rhs_ty.is_ty_var()
97 && is_builtin_binop(lhs_ty, rhs_ty, op)
99 let builtin_return_ty = self.enforce_builtin_binop_types(
106 self.demand_suptype(expr.span, builtin_return_ty, return_ty);
114 fn enforce_builtin_binop_types(
122 debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
124 // Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
125 // (See https://github.com/rust-lang/rust/issues/57447.)
126 let (lhs_ty, rhs_ty) = (deref_ty_if_possible(lhs_ty), deref_ty_if_possible(rhs_ty));
129 match BinOpCategory::from(op) {
130 BinOpCategory::Shortcircuit => {
131 self.demand_suptype(*lhs_span, tcx.types.bool, lhs_ty);
132 self.demand_suptype(*rhs_span, tcx.types.bool, rhs_ty);
136 BinOpCategory::Shift => {
137 // result type is same as LHS always
141 BinOpCategory::Math | BinOpCategory::Bitwise => {
142 // both LHS and RHS and result will have the same type
143 self.demand_suptype(*rhs_span, lhs_ty, rhs_ty);
147 BinOpCategory::Comparison => {
148 // both LHS and RHS and result will have the same type
149 self.demand_suptype(*rhs_span, lhs_ty, rhs_ty);
155 fn check_overloaded_binop(
157 expr: &'tcx hir::Expr<'tcx>,
158 lhs_expr: &'tcx hir::Expr<'tcx>,
159 rhs_expr: &'tcx hir::Expr<'tcx>,
162 ) -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>) {
164 "check_overloaded_binop(expr.hir_id={}, op={:?}, is_assign={:?})",
165 expr.hir_id, op, is_assign
168 let lhs_ty = match is_assign {
170 // Find a suitable supertype of the LHS expression's type, by coercing to
171 // a type variable, to pass as the `Self` to the trait, avoiding invariant
172 // trait matching creating lifetime constraints that are too strict.
173 // e.g., adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
174 // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`.
175 let lhs_ty = self.check_expr(lhs_expr);
176 let fresh_var = self.next_ty_var(TypeVariableOrigin {
177 kind: TypeVariableOriginKind::MiscVariable,
180 self.demand_coerce(lhs_expr, lhs_ty, fresh_var, Some(rhs_expr), AllowTwoPhase::No)
183 // rust-lang/rust#52126: We have to use strict
184 // equivalence on the LHS of an assign-op like `+=`;
185 // overwritten or mutably-borrowed places cannot be
186 // coerced to a supertype.
187 self.check_expr(lhs_expr)
190 let lhs_ty = self.resolve_vars_with_obligations(lhs_ty);
192 // N.B., as we have not yet type-checked the RHS, we don't have the
193 // type at hand. Make a variable to represent it. The whole reason
194 // for this indirection is so that, below, we can check the expr
195 // using this variable as the expected type, which sometimes lets
196 // us do better coercions than we would be able to do otherwise,
197 // particularly for things like `String + &String`.
198 let rhs_ty_var = self.next_ty_var(TypeVariableOrigin {
199 kind: TypeVariableOriginKind::MiscVariable,
203 let result = self.lookup_op_method(lhs_ty, &[rhs_ty_var], Op::Binary(op, is_assign));
206 let rhs_ty = self.check_expr_coercable_to_type(rhs_expr, rhs_ty_var, Some(lhs_expr));
207 let rhs_ty = self.resolve_vars_with_obligations(rhs_ty);
209 let return_ty = match result {
211 let by_ref_binop = !op.node.is_by_value();
212 if is_assign == IsAssign::Yes || by_ref_binop {
213 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].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()[0],
226 self.apply_adjustments(lhs_expr, vec![autoref]);
230 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[1].kind() {
231 let mutbl = match mutbl {
232 hir::Mutability::Not => AutoBorrowMutability::Not,
233 hir::Mutability::Mut => AutoBorrowMutability::Mut {
234 // Allow two-phase borrows for binops in initial deployment
235 // since they desugar to methods
236 allow_two_phase_borrow: AllowTwoPhase::Yes,
239 let autoref = Adjustment {
240 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
241 target: method.sig.inputs()[1],
243 // HACK(eddyb) Bypass checks due to reborrows being in
244 // some cases applied on the RHS, on top of which we need
245 // to autoref, which is not allowed by apply_adjustments.
246 // self.apply_adjustments(rhs_expr, vec![autoref]);
250 .entry(rhs_expr.hir_id)
255 self.write_method_call(expr.hir_id, method);
259 // error types are considered "builtin"
260 Err(()) if lhs_ty.references_error() || rhs_ty.references_error() => {
264 let source_map = self.tcx.sess.source_map();
265 let (mut err, missing_trait, use_output, involves_fn) = match is_assign {
267 let mut err = struct_span_err!(
271 "binary assignment operation `{}=` cannot be applied to type `{}`",
277 format!("cannot use `{}=` on type `{}`", op.node.as_str(), lhs_ty),
279 let missing_trait = match op.node {
280 hir::BinOpKind::Add => Some("std::ops::AddAssign"),
281 hir::BinOpKind::Sub => Some("std::ops::SubAssign"),
282 hir::BinOpKind::Mul => Some("std::ops::MulAssign"),
283 hir::BinOpKind::Div => Some("std::ops::DivAssign"),
284 hir::BinOpKind::Rem => Some("std::ops::RemAssign"),
285 hir::BinOpKind::BitAnd => Some("std::ops::BitAndAssign"),
286 hir::BinOpKind::BitXor => Some("std::ops::BitXorAssign"),
287 hir::BinOpKind::BitOr => Some("std::ops::BitOrAssign"),
288 hir::BinOpKind::Shl => Some("std::ops::ShlAssign"),
289 hir::BinOpKind::Shr => Some("std::ops::ShrAssign"),
292 (err, missing_trait, false, false)
295 let (message, missing_trait, use_output) = match op.node {
296 hir::BinOpKind::Add => (
297 format!("cannot add `{}` to `{}`", rhs_ty, lhs_ty),
298 Some("std::ops::Add"),
301 hir::BinOpKind::Sub => (
302 format!("cannot subtract `{}` from `{}`", rhs_ty, lhs_ty),
303 Some("std::ops::Sub"),
306 hir::BinOpKind::Mul => (
307 format!("cannot multiply `{}` by `{}`", lhs_ty, rhs_ty),
308 Some("std::ops::Mul"),
311 hir::BinOpKind::Div => (
312 format!("cannot divide `{}` by `{}`", lhs_ty, rhs_ty),
313 Some("std::ops::Div"),
316 hir::BinOpKind::Rem => (
317 format!("cannot mod `{}` by `{}`", lhs_ty, rhs_ty),
318 Some("std::ops::Rem"),
321 hir::BinOpKind::BitAnd => (
322 format!("no implementation for `{} & {}`", lhs_ty, rhs_ty),
323 Some("std::ops::BitAnd"),
326 hir::BinOpKind::BitXor => (
327 format!("no implementation for `{} ^ {}`", lhs_ty, rhs_ty),
328 Some("std::ops::BitXor"),
331 hir::BinOpKind::BitOr => (
332 format!("no implementation for `{} | {}`", lhs_ty, rhs_ty),
333 Some("std::ops::BitOr"),
336 hir::BinOpKind::Shl => (
337 format!("no implementation for `{} << {}`", lhs_ty, rhs_ty),
338 Some("std::ops::Shl"),
341 hir::BinOpKind::Shr => (
342 format!("no implementation for `{} >> {}`", lhs_ty, rhs_ty),
343 Some("std::ops::Shr"),
346 hir::BinOpKind::Eq | hir::BinOpKind::Ne => (
348 "binary operation `{}` cannot be applied to type `{}`",
352 Some("std::cmp::PartialEq"),
358 | hir::BinOpKind::Ge => (
360 "binary operation `{}` cannot be applied to type `{}`",
364 Some("std::cmp::PartialOrd"),
369 "binary operation `{}` cannot be applied to type `{}`",
378 struct_span_err!(self.tcx.sess, op.span, E0369, "{}", message.as_str());
379 let mut involves_fn = false;
380 if !lhs_expr.span.eq(&rhs_expr.span) {
381 involves_fn |= self.add_type_neq_err_label(
389 involves_fn |= self.add_type_neq_err_label(
398 (err, missing_trait, use_output, involves_fn)
401 let mut suggested_deref = false;
402 if let Ref(_, rty, _) = lhs_ty.kind() {
404 self.infcx.type_is_copy_modulo_regions(self.param_env, rty, lhs_expr.span)
406 .lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign))
409 if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
411 "`{}{}` can be used on `{}`, you can dereference `{}`",
414 IsAssign::Yes => "=",
420 err.span_suggestion_verbose(
421 lhs_expr.span.shrink_to_lo(),
424 rustc_errors::Applicability::MachineApplicable,
426 suggested_deref = true;
430 if let Some(missing_trait) = missing_trait {
431 let mut visitor = TypeParamVisitor(self.tcx, vec![]);
432 visitor.visit_ty(lhs_ty);
434 if op.node == hir::BinOpKind::Add
435 && self.check_str_addition(
436 lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, is_assign, op,
439 // This has nothing here because it means we did string
440 // concatenation (e.g., "Hello " + "World!"). This means
441 // we don't want the note in the else clause to be emitted
442 } else if let [ty] = &visitor.1[..] {
443 if let ty::Param(p) = *ty.kind() {
444 // Check if the method would be found if the type param wasn't
445 // involved. If so, it means that adding a trait bound to the param is
446 // enough. Otherwise we do not give the suggestion.
447 let mut eraser = TypeParamEraser(&self, expr.span);
448 let needs_bound = self
450 eraser.fold_ty(lhs_ty),
451 &[eraser.fold_ty(rhs_ty)],
452 Op::Binary(op, is_assign),
456 suggest_constraining_param(
466 } else if *ty != lhs_ty {
467 // When we know that a missing bound is responsible, we don't show
468 // this note as it is redundant.
470 "the trait `{}` is not implemented for `{}`",
471 missing_trait, lhs_ty
475 bug!("type param visitor stored a non type param: {:?}", ty.kind());
477 } else if !suggested_deref && !involves_fn {
478 suggest_impl_missing(&mut err, lhs_ty, &missing_trait);
486 (lhs_ty, rhs_ty, return_ty)
489 /// If one of the types is an uncalled function and calling it would yield the other type,
490 /// suggest calling the function. Returns `true` if suggestion would apply (even if not given).
491 fn add_type_neq_err_label(
493 err: &mut rustc_errors::DiagnosticBuilder<'_>,
499 ) -> bool /* did we suggest to call a function because of missing parenthesis? */ {
500 err.span_label(span, ty.to_string());
501 if let FnDef(def_id, _) = *ty.kind() {
502 let source_map = self.tcx.sess.source_map();
503 if !self.tcx.has_typeck_results(def_id) {
506 // FIXME: Instead of exiting early when encountering bound vars in
507 // the function signature, consider keeping the binder here and
508 // propagating it downwards.
509 let fn_sig = if let Some(fn_sig) = self.tcx.fn_sig(def_id).no_bound_vars() {
515 let other_ty = if let FnDef(def_id, _) = *other_ty.kind() {
516 if !self.tcx.has_typeck_results(def_id) {
519 // We're emitting a suggestion, so we can just ignore regions
520 self.tcx.fn_sig(def_id).skip_binder().output()
526 .lookup_op_method(fn_sig.output(), &[other_ty], Op::Binary(op, is_assign))
529 if let Ok(snippet) = source_map.span_to_snippet(span) {
530 let (variable_snippet, applicability) = if !fn_sig.inputs().is_empty() {
531 (format!("{}( /* arguments */ )", snippet), Applicability::HasPlaceholders)
533 (format!("{}()", snippet), Applicability::MaybeIncorrect)
538 "you might have forgotten to call this function",
549 /// Provide actionable suggestions when trying to add two strings with incorrect types,
550 /// like `&str + &str`, `String + String` and `&str + &String`.
552 /// If this function returns `true` it means a note was printed, so we don't need
553 /// to print the normal "implementation of `std::ops::Add` might be missing" note
554 fn check_str_addition(
556 lhs_expr: &'tcx hir::Expr<'tcx>,
557 rhs_expr: &'tcx hir::Expr<'tcx>,
560 err: &mut rustc_errors::DiagnosticBuilder<'_>,
564 let source_map = self.tcx.sess.source_map();
565 let remove_borrow_msg = "String concatenation appends the string on the right to the \
566 string on the left and may require reallocation. This \
567 requires ownership of the string on the left";
569 let msg = "`to_owned()` can be used to create an owned `String` \
570 from a string reference. String concatenation \
571 appends the string on the right to the string \
572 on the left and may require reallocation. This \
573 requires ownership of the string on the left";
575 let string_type = self.tcx.get_diagnostic_item(sym::string_type);
576 let is_std_string = |ty: Ty<'tcx>| match ty.ty_adt_def() {
577 Some(ty_def) => Some(ty_def.did) == string_type,
581 match (lhs_ty.kind(), rhs_ty.kind()) {
582 (&Ref(_, l_ty, _), &Ref(_, r_ty, _)) // &str or &String + &str, &String or &&str
583 if (*l_ty.kind() == Str || is_std_string(l_ty)) && (
584 *r_ty.kind() == Str || is_std_string(r_ty) ||
585 &format!("{:?}", rhs_ty) == "&&str"
588 if let IsAssign::No = is_assign { // Do not supply this message if `&str += &str`
591 "`+` cannot be used to concatenate two `&str` strings",
593 match source_map.span_to_snippet(lhs_expr.span) {
597 if lstring.starts_with('&') {
602 if let Some(stripped) = lstring.strip_prefix('&') {
603 // let a = String::new();
604 // let _ = &a + "bar";
607 format!("{}.to_owned()", lstring)
609 Applicability::MachineApplicable,
617 (&Ref(_, l_ty, _), &Adt(..)) // Handle `&str` & `&String` + `String`
618 if (*l_ty.kind() == Str || is_std_string(l_ty)) && is_std_string(rhs_ty) =>
622 "`+` cannot be used to concatenate a `&str` with a `String`",
625 source_map.span_to_snippet(lhs_expr.span),
626 source_map.span_to_snippet(rhs_expr.span),
629 (Ok(l), Ok(r), IsAssign::No) => {
630 let to_string = if let Some(stripped) = l.strip_prefix('&') {
631 // let a = String::new(); let b = String::new();
635 format!("{}.to_owned()", l)
637 err.multipart_suggestion(
640 (lhs_expr.span, to_string),
641 (rhs_expr.span, format!("&{}", r)),
643 Applicability::MachineApplicable,
656 pub fn check_user_unop(
658 ex: &'tcx hir::Expr<'tcx>,
659 operand_ty: Ty<'tcx>,
662 assert!(op.is_by_value());
663 match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) {
665 self.write_method_call(ex.hir_id, method);
669 let actual = self.resolve_vars_if_possible(operand_ty);
670 if !actual.references_error() {
671 let mut err = struct_span_err!(
675 "cannot apply unary operator `{}` to type `{}`",
681 format!("cannot apply unary operator `{}`", op.as_str()),
684 let sp = self.tcx.sess.source_map().start_point(ex.span);
686 self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
688 // If the previous expression was a block expression, suggest parentheses
689 // (turning this into a binary subtraction operation instead.)
690 // for example, `{2} - 2` -> `({2}) - 2` (see src\test\ui\parser\expr-as-stmt.rs)
691 self.tcx.sess.parse_sess.expr_parentheses_needed(&mut err, *sp);
693 match actual.kind() {
694 Uint(_) if op == hir::UnOp::Neg => {
695 err.note("unsigned values cannot be negated");
697 if let hir::ExprKind::Unary(
701 hir::ExprKind::Lit(Spanned {
702 node: ast::LitKind::Int(1, _),
712 "you may have meant the maximum value of `{}`",
715 format!("{}::MAX", actual),
716 Applicability::MaybeIncorrect,
720 Str | Never | Char | Tuple(_) | Array(_, _) => {}
721 Ref(_, ref lty, _) if *lty.kind() == Str => {}
723 let missing_trait = match op {
724 hir::UnOp::Neg => "std::ops::Neg",
725 hir::UnOp::Not => "std::ops::Not",
726 hir::UnOp::Deref => "std::ops::UnDerf",
728 suggest_impl_missing(&mut err, operand_ty, &missing_trait);
742 other_tys: &[Ty<'tcx>],
744 ) -> Result<MethodCallee<'tcx>, ()> {
745 let lang = self.tcx.lang_items();
747 let span = match op {
748 Op::Binary(op, _) => op.span,
749 Op::Unary(_, span) => span,
751 let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
753 hir::BinOpKind::Add => (sym::add_assign, lang.add_assign_trait()),
754 hir::BinOpKind::Sub => (sym::sub_assign, lang.sub_assign_trait()),
755 hir::BinOpKind::Mul => (sym::mul_assign, lang.mul_assign_trait()),
756 hir::BinOpKind::Div => (sym::div_assign, lang.div_assign_trait()),
757 hir::BinOpKind::Rem => (sym::rem_assign, lang.rem_assign_trait()),
758 hir::BinOpKind::BitXor => (sym::bitxor_assign, lang.bitxor_assign_trait()),
759 hir::BinOpKind::BitAnd => (sym::bitand_assign, lang.bitand_assign_trait()),
760 hir::BinOpKind::BitOr => (sym::bitor_assign, lang.bitor_assign_trait()),
761 hir::BinOpKind::Shl => (sym::shl_assign, lang.shl_assign_trait()),
762 hir::BinOpKind::Shr => (sym::shr_assign, lang.shr_assign_trait()),
769 | hir::BinOpKind::And
770 | hir::BinOpKind::Or => {
771 span_bug!(span, "impossible assignment operation: {}=", op.node.as_str())
774 } else if let Op::Binary(op, IsAssign::No) = op {
776 hir::BinOpKind::Add => (sym::add, lang.add_trait()),
777 hir::BinOpKind::Sub => (sym::sub, lang.sub_trait()),
778 hir::BinOpKind::Mul => (sym::mul, lang.mul_trait()),
779 hir::BinOpKind::Div => (sym::div, lang.div_trait()),
780 hir::BinOpKind::Rem => (sym::rem, lang.rem_trait()),
781 hir::BinOpKind::BitXor => (sym::bitxor, lang.bitxor_trait()),
782 hir::BinOpKind::BitAnd => (sym::bitand, lang.bitand_trait()),
783 hir::BinOpKind::BitOr => (sym::bitor, lang.bitor_trait()),
784 hir::BinOpKind::Shl => (sym::shl, lang.shl_trait()),
785 hir::BinOpKind::Shr => (sym::shr, lang.shr_trait()),
786 hir::BinOpKind::Lt => (sym::lt, lang.partial_ord_trait()),
787 hir::BinOpKind::Le => (sym::le, lang.partial_ord_trait()),
788 hir::BinOpKind::Ge => (sym::ge, lang.partial_ord_trait()),
789 hir::BinOpKind::Gt => (sym::gt, lang.partial_ord_trait()),
790 hir::BinOpKind::Eq => (sym::eq, lang.eq_trait()),
791 hir::BinOpKind::Ne => (sym::ne, lang.eq_trait()),
792 hir::BinOpKind::And | hir::BinOpKind::Or => {
793 span_bug!(span, "&& and || are not overloadable")
796 } else if let Op::Unary(hir::UnOp::Not, _) = op {
797 (sym::not, lang.not_trait())
798 } else if let Op::Unary(hir::UnOp::Neg, _) = op {
799 (sym::neg, lang.neg_trait())
801 bug!("lookup_op_method: op not supported: {:?}", op)
805 "lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
806 lhs_ty, op, opname, trait_did
809 // Catches cases like #83893, where a lang item is declared with the
810 // wrong number of generic arguments. Should have yielded an error
811 // elsewhere by now, but we have to catch it here so that we do not
812 // index `other_tys` out of bounds (if the lang item has too many
813 // generic arguments, `other_tys` is too short).
814 if !has_expected_num_generic_args(
818 // Binary ops have a generic right-hand side, unary ops don't
826 let method = trait_did.and_then(|trait_did| {
827 let opname = Ident::with_dummy_span(opname);
828 self.lookup_method_in_trait(span, opname, trait_did, lhs_ty, Some(other_tys))
833 let method = self.register_infer_ok_obligations(ok);
834 self.select_obligations_where_possible(false, |_| {});
843 // Binary operator categories. These categories summarize the behavior
844 // with respect to the builtin operationrs supported.
846 /// &&, || -- cannot be overridden
849 /// <<, >> -- when shifting a single integer, rhs can be any
850 /// integer type. For simd, types must match.
853 /// +, -, etc -- takes equal types, produces same type as input,
854 /// applicable to ints/floats/simd
857 /// &, |, ^ -- takes equal types, produces same type as input,
858 /// applicable to ints/floats/simd/bool
861 /// ==, !=, etc -- takes equal types, produces bools, except for simd,
862 /// which produce the input type
867 fn from(op: hir::BinOp) -> BinOpCategory {
869 hir::BinOpKind::Shl | hir::BinOpKind::Shr => BinOpCategory::Shift,
872 | hir::BinOpKind::Sub
873 | hir::BinOpKind::Mul
874 | hir::BinOpKind::Div
875 | hir::BinOpKind::Rem => BinOpCategory::Math,
877 hir::BinOpKind::BitXor | hir::BinOpKind::BitAnd | hir::BinOpKind::BitOr => {
878 BinOpCategory::Bitwise
886 | hir::BinOpKind::Gt => BinOpCategory::Comparison,
888 hir::BinOpKind::And | hir::BinOpKind::Or => BinOpCategory::Shortcircuit,
893 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
894 #[derive(Clone, Copy, Debug, PartialEq)]
900 #[derive(Clone, Copy, Debug)]
902 Binary(hir::BinOp, IsAssign),
903 Unary(hir::UnOp, Span),
906 /// Dereferences a single level of immutable referencing.
907 fn deref_ty_if_possible(ty: Ty<'tcx>) -> Ty<'tcx> {
909 ty::Ref(_, ty, hir::Mutability::Not) => ty,
914 /// Returns `true` if this is a built-in arithmetic operation (e.g., u32
915 /// + u32, i16x4 == i16x4) and false if these types would have to be
916 /// overloaded to be legal. There are two reasons that we distinguish
917 /// builtin operations from overloaded ones (vs trying to drive
918 /// everything uniformly through the trait system and intrinsics or
919 /// something like that):
921 /// 1. Builtin operations can trivially be evaluated in constants.
922 /// 2. For comparison operators applied to SIMD types the result is
923 /// not of type `bool`. For example, `i16x4 == i16x4` yields a
924 /// type like `i16x4`. This means that the overloaded trait
925 /// `PartialEq` is not applicable.
927 /// Reason #2 is the killer. I tried for a while to always use
928 /// overloaded logic and just check the types in constants/codegen after
929 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
930 fn is_builtin_binop<'tcx>(lhs: Ty<'tcx>, rhs: Ty<'tcx>, op: hir::BinOp) -> bool {
931 // Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
932 // (See https://github.com/rust-lang/rust/issues/57447.)
933 let (lhs, rhs) = (deref_ty_if_possible(lhs), deref_ty_if_possible(rhs));
935 match BinOpCategory::from(op) {
936 BinOpCategory::Shortcircuit => true,
938 BinOpCategory::Shift => {
939 lhs.references_error()
940 || rhs.references_error()
941 || lhs.is_integral() && rhs.is_integral()
944 BinOpCategory::Math => {
945 lhs.references_error()
946 || rhs.references_error()
947 || lhs.is_integral() && rhs.is_integral()
948 || lhs.is_floating_point() && rhs.is_floating_point()
951 BinOpCategory::Bitwise => {
952 lhs.references_error()
953 || rhs.references_error()
954 || lhs.is_integral() && rhs.is_integral()
955 || lhs.is_floating_point() && rhs.is_floating_point()
956 || lhs.is_bool() && rhs.is_bool()
959 BinOpCategory::Comparison => {
960 lhs.references_error() || rhs.references_error() || lhs.is_scalar() && rhs.is_scalar()
965 /// If applicable, note that an implementation of `trait` for `ty` may fix the error.
966 fn suggest_impl_missing(err: &mut DiagnosticBuilder<'_>, ty: Ty<'_>, missing_trait: &str) {
967 if let Adt(def, _) = ty.peel_refs().kind() {
968 if def.did.is_local() {
970 "an implementation of `{}` might be missing for `{}`",
977 fn suggest_constraining_param(
980 mut err: &mut DiagnosticBuilder<'_>,
988 let msg = &format!("`{}` might need a bound for `{}`", lhs_ty, missing_trait);
989 // Try to find the def-id and details for the parameter p. We have only the index,
990 // so we have to find the enclosing function's def-id, then look through its declared
991 // generic parameters to get the declaration.
992 let def_id = hir.body_owner_def_id(hir::BodyId { hir_id: body_id });
993 let generics = tcx.generics_of(def_id);
994 let param_def_id = generics.type_param(&p, tcx).def_id;
995 if let Some(generics) = param_def_id
997 .map(|id| hir.local_def_id_to_hir_id(id))
998 .and_then(|id| hir.find(hir.get_parent_item(id)))
1000 .and_then(|node| node.generics())
1002 let output = if set_output { format!("<Output = {}>", rhs_ty) } else { String::new() };
1003 suggest_constraining_type_param(
1007 &format!("{}", lhs_ty),
1008 &format!("{}{}", missing_trait, output),
1012 let span = tcx.def_span(param_def_id);
1013 err.span_label(span, msg);
1017 struct TypeParamVisitor<'tcx>(TyCtxt<'tcx>, Vec<Ty<'tcx>>);
1019 impl<'tcx> TypeVisitor<'tcx> for TypeParamVisitor<'tcx> {
1020 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
1023 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1024 if let ty::Param(_) = ty.kind() {
1027 ty.super_visit_with(self)
1031 struct TypeParamEraser<'a, 'tcx>(&'a FnCtxt<'a, 'tcx>, Span);
1033 impl TypeFolder<'tcx> for TypeParamEraser<'_, 'tcx> {
1034 fn tcx(&self) -> TyCtxt<'tcx> {
1038 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1040 ty::Param(_) => self.0.next_ty_var(TypeVariableOrigin {
1041 kind: TypeVariableOriginKind::MiscVariable,
1044 _ => ty.super_fold_with(self),