1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
//! Code related to processing overloaded binary and unary operators.
use rustc_data_structures::packed::Pu128;
use rustc_errors::codes::*;
use rustc_errors::{struct_span_code_err, Applicability, Diag};
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::ty::adjustment::{
Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
};
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt, TypeVisitableExt};
use rustc_middle::{bug, span_bug};
use rustc_session::errors::ExprParenthesesNeeded;
use rustc_span::source_map::Spanned;
use rustc_span::symbol::{sym, Ident};
use rustc_span::Span;
use rustc_trait_selection::infer::InferCtxtExt;
use rustc_trait_selection::traits::{FulfillmentError, ObligationCtxt};
use rustc_type_ir::TyKind::*;
use tracing::debug;
use {rustc_ast as ast, rustc_hir as hir};
use super::method::MethodCallee;
use super::FnCtxt;
use crate::Expectation;
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// Checks a `a <op>= b`
pub(crate) fn check_binop_assign(
&self,
expr: &'tcx hir::Expr<'tcx>,
op: hir::BinOp,
lhs: &'tcx hir::Expr<'tcx>,
rhs: &'tcx hir::Expr<'tcx>,
expected: Expectation<'tcx>,
) -> Ty<'tcx> {
let (lhs_ty, rhs_ty, return_ty) =
self.check_overloaded_binop(expr, lhs, rhs, op, IsAssign::Yes, expected);
let ty =
if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() && is_builtin_binop(lhs_ty, rhs_ty, op) {
self.enforce_builtin_binop_types(lhs.span, lhs_ty, rhs.span, rhs_ty, op);
self.tcx.types.unit
} else {
return_ty
};
self.check_lhs_assignable(lhs, E0067, op.span, |err| {
if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
if self
.lookup_op_method(
(lhs, lhs_deref_ty),
Some((rhs, rhs_ty)),
Op::Binary(op, IsAssign::Yes),
expected,
)
.is_ok()
{
// If LHS += RHS is an error, but *LHS += RHS is successful, then we will have
// emitted a better suggestion during error handling in check_overloaded_binop.
if self
.lookup_op_method(
(lhs, lhs_ty),
Some((rhs, rhs_ty)),
Op::Binary(op, IsAssign::Yes),
expected,
)
.is_err()
{
err.downgrade_to_delayed_bug();
} else {
// Otherwise, it's valid to suggest dereferencing the LHS here.
err.span_suggestion_verbose(
lhs.span.shrink_to_lo(),
"consider dereferencing the left-hand side of this operation",
"*",
Applicability::MaybeIncorrect,
);
}
}
}
});
ty
}
/// Checks a potentially overloaded binary operator.
pub(crate) fn check_binop(
&self,
expr: &'tcx hir::Expr<'tcx>,
op: hir::BinOp,
lhs_expr: &'tcx hir::Expr<'tcx>,
rhs_expr: &'tcx hir::Expr<'tcx>,
expected: Expectation<'tcx>,
) -> Ty<'tcx> {
let tcx = self.tcx;
debug!(
"check_binop(expr.hir_id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
expr.hir_id, expr, op, lhs_expr, rhs_expr
);
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => {
// && and || are a simple case.
self.check_expr_coercible_to_type(lhs_expr, tcx.types.bool, None);
let lhs_diverges = self.diverges.get();
self.check_expr_coercible_to_type(rhs_expr, tcx.types.bool, None);
// Depending on the LHS' value, the RHS can never execute.
self.diverges.set(lhs_diverges);
tcx.types.bool
}
_ => {
// Otherwise, we always treat operators as if they are
// overloaded. This is the way to be most flexible w/r/t
// types that get inferred.
let (lhs_ty, rhs_ty, return_ty) = self.check_overloaded_binop(
expr,
lhs_expr,
rhs_expr,
op,
IsAssign::No,
expected,
);
// Supply type inference hints if relevant. Probably these
// hints should be enforced during select as part of the
// `consider_unification_despite_ambiguity` routine, but this
// more convenient for now.
//
// The basic idea is to help type inference by taking
// advantage of things we know about how the impls for
// scalar types are arranged. This is important in a
// scenario like `1_u32 << 2`, because it lets us quickly
// deduce that the result type should be `u32`, even
// though we don't know yet what type 2 has and hence
// can't pin this down to a specific impl.
if !lhs_ty.is_ty_var()
&& !rhs_ty.is_ty_var()
&& is_builtin_binop(lhs_ty, rhs_ty, op)
{
let builtin_return_ty = self.enforce_builtin_binop_types(
lhs_expr.span,
lhs_ty,
rhs_expr.span,
rhs_ty,
op,
);
self.demand_eqtype(expr.span, builtin_return_ty, return_ty);
builtin_return_ty
} else {
return_ty
}
}
}
}
fn enforce_builtin_binop_types(
&self,
lhs_span: Span,
lhs_ty: Ty<'tcx>,
rhs_span: Span,
rhs_ty: Ty<'tcx>,
op: hir::BinOp,
) -> Ty<'tcx> {
debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
// Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
// (See https://github.com/rust-lang/rust/issues/57447.)
let (lhs_ty, rhs_ty) = (deref_ty_if_possible(lhs_ty), deref_ty_if_possible(rhs_ty));
let tcx = self.tcx;
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => {
self.demand_suptype(lhs_span, tcx.types.bool, lhs_ty);
self.demand_suptype(rhs_span, tcx.types.bool, rhs_ty);
tcx.types.bool
}
BinOpCategory::Shift => {
// result type is same as LHS always
lhs_ty
}
BinOpCategory::Math | BinOpCategory::Bitwise => {
// both LHS and RHS and result will have the same type
self.demand_suptype(rhs_span, lhs_ty, rhs_ty);
lhs_ty
}
BinOpCategory::Comparison => {
// both LHS and RHS and result will have the same type
self.demand_suptype(rhs_span, lhs_ty, rhs_ty);
tcx.types.bool
}
}
}
fn check_overloaded_binop(
&self,
expr: &'tcx hir::Expr<'tcx>,
lhs_expr: &'tcx hir::Expr<'tcx>,
rhs_expr: &'tcx hir::Expr<'tcx>,
op: hir::BinOp,
is_assign: IsAssign,
expected: Expectation<'tcx>,
) -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>) {
debug!(
"check_overloaded_binop(expr.hir_id={}, op={:?}, is_assign={:?})",
expr.hir_id, op, is_assign
);
let lhs_ty = match is_assign {
IsAssign::No => {
// Find a suitable supertype of the LHS expression's type, by coercing to
// a type variable, to pass as the `Self` to the trait, avoiding invariant
// trait matching creating lifetime constraints that are too strict.
// e.g., adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
// in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`.
let lhs_ty = self.check_expr(lhs_expr);
let fresh_var = self.next_ty_var(lhs_expr.span);
self.demand_coerce(lhs_expr, lhs_ty, fresh_var, Some(rhs_expr), AllowTwoPhase::No)
}
IsAssign::Yes => {
// rust-lang/rust#52126: We have to use strict
// equivalence on the LHS of an assign-op like `+=`;
// overwritten or mutably-borrowed places cannot be
// coerced to a supertype.
self.check_expr(lhs_expr)
}
};
let lhs_ty = self.resolve_vars_with_obligations(lhs_ty);
// N.B., as we have not yet type-checked the RHS, we don't have the
// type at hand. Make a variable to represent it. The whole reason
// for this indirection is so that, below, we can check the expr
// using this variable as the expected type, which sometimes lets
// us do better coercions than we would be able to do otherwise,
// particularly for things like `String + &String`.
let rhs_ty_var = self.next_ty_var(rhs_expr.span);
let result = self.lookup_op_method(
(lhs_expr, lhs_ty),
Some((rhs_expr, rhs_ty_var)),
Op::Binary(op, is_assign),
expected,
);
// see `NB` above
let rhs_ty = self.check_expr_coercible_to_type(rhs_expr, rhs_ty_var, Some(lhs_expr));
let rhs_ty = self.resolve_vars_with_obligations(rhs_ty);
let return_ty = match result {
Ok(method) => {
let by_ref_binop = !op.node.is_by_value();
if is_assign == IsAssign::Yes || by_ref_binop {
if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind() {
let mutbl = AutoBorrowMutability::new(*mutbl, AllowTwoPhase::Yes);
let autoref = Adjustment {
kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
target: method.sig.inputs()[0],
};
self.apply_adjustments(lhs_expr, vec![autoref]);
}
}
if by_ref_binop {
if let ty::Ref(region, _, mutbl) = method.sig.inputs()[1].kind() {
// Allow two-phase borrows for binops in initial deployment
// since they desugar to methods
let mutbl = AutoBorrowMutability::new(*mutbl, AllowTwoPhase::Yes);
let autoref = Adjustment {
kind: Adjust::Borrow(AutoBorrow::Ref(*region, mutbl)),
target: method.sig.inputs()[1],
};
// HACK(eddyb) Bypass checks due to reborrows being in
// some cases applied on the RHS, on top of which we need
// to autoref, which is not allowed by apply_adjustments.
// self.apply_adjustments(rhs_expr, vec![autoref]);
self.typeck_results
.borrow_mut()
.adjustments_mut()
.entry(rhs_expr.hir_id)
.or_default()
.push(autoref);
}
}
self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
method.sig.output()
}
// error types are considered "builtin"
Err(_) if lhs_ty.references_error() || rhs_ty.references_error() => {
Ty::new_misc_error(self.tcx)
}
Err(errors) => {
let (_, trait_def_id) =
lang_item_for_op(self.tcx, Op::Binary(op, is_assign), op.span);
let missing_trait = trait_def_id
.map(|def_id| with_no_trimmed_paths!(self.tcx.def_path_str(def_id)));
let (mut err, output_def_id) = match is_assign {
IsAssign::Yes => {
let mut err = struct_span_code_err!(
self.dcx(),
expr.span,
E0368,
"binary assignment operation `{}=` cannot be applied to type `{}`",
op.node.as_str(),
lhs_ty,
);
err.span_label(
lhs_expr.span,
format!("cannot use `{}=` on type `{}`", op.node.as_str(), lhs_ty),
);
self.note_unmet_impls_on_type(&mut err, errors, false);
(err, None)
}
IsAssign::No => {
let message = match op.node {
hir::BinOpKind::Add => {
format!("cannot add `{rhs_ty}` to `{lhs_ty}`")
}
hir::BinOpKind::Sub => {
format!("cannot subtract `{rhs_ty}` from `{lhs_ty}`")
}
hir::BinOpKind::Mul => {
format!("cannot multiply `{lhs_ty}` by `{rhs_ty}`")
}
hir::BinOpKind::Div => {
format!("cannot divide `{lhs_ty}` by `{rhs_ty}`")
}
hir::BinOpKind::Rem => {
format!(
"cannot calculate the remainder of `{lhs_ty}` divided by `{rhs_ty}`"
)
}
hir::BinOpKind::BitAnd => {
format!("no implementation for `{lhs_ty} & {rhs_ty}`")
}
hir::BinOpKind::BitXor => {
format!("no implementation for `{lhs_ty} ^ {rhs_ty}`")
}
hir::BinOpKind::BitOr => {
format!("no implementation for `{lhs_ty} | {rhs_ty}`")
}
hir::BinOpKind::Shl => {
format!("no implementation for `{lhs_ty} << {rhs_ty}`")
}
hir::BinOpKind::Shr => {
format!("no implementation for `{lhs_ty} >> {rhs_ty}`")
}
_ => format!(
"binary operation `{}` cannot be applied to type `{}`",
op.node.as_str(),
lhs_ty
),
};
let output_def_id = trait_def_id.and_then(|def_id| {
self.tcx
.associated_item_def_ids(def_id)
.iter()
.find(|item_def_id| {
self.tcx.associated_item(*item_def_id).name == sym::Output
})
.cloned()
});
let mut err =
struct_span_code_err!(self.dcx(), op.span, E0369, "{message}");
if !lhs_expr.span.eq(&rhs_expr.span) {
err.span_label(lhs_expr.span, lhs_ty.to_string());
err.span_label(rhs_expr.span, rhs_ty.to_string());
}
let suggest_derive = self.can_eq(self.param_env, lhs_ty, rhs_ty);
self.note_unmet_impls_on_type(&mut err, errors, suggest_derive);
(err, output_def_id)
}
};
// Try to suggest a semicolon if it's `A \n *B` where `B` is a place expr
let maybe_missing_semi = self.check_for_missing_semi(expr, &mut err);
// We defer to the later error produced by `check_lhs_assignable`.
// We only downgrade this if it's the LHS, though, and if this is a
// valid assignment statement.
if maybe_missing_semi
&& let hir::Node::Expr(parent) = self.tcx.parent_hir_node(expr.hir_id)
&& let hir::ExprKind::Assign(lhs, _, _) = parent.kind
&& let hir::Node::Stmt(stmt) = self.tcx.parent_hir_node(parent.hir_id)
&& let hir::StmtKind::Expr(_) | hir::StmtKind::Semi(_) = stmt.kind
&& lhs.hir_id == expr.hir_id
{
err.downgrade_to_delayed_bug();
}
let suggest_deref_binop = |err: &mut Diag<'_, _>, lhs_deref_ty: Ty<'tcx>| {
if self
.lookup_op_method(
(lhs_expr, lhs_deref_ty),
Some((rhs_expr, rhs_ty)),
Op::Binary(op, is_assign),
expected,
)
.is_ok()
{
let msg = format!(
"`{}{}` can be used on `{}` if you dereference the left-hand side",
op.node.as_str(),
match is_assign {
IsAssign::Yes => "=",
IsAssign::No => "",
},
lhs_deref_ty,
);
err.span_suggestion_verbose(
lhs_expr.span.shrink_to_lo(),
msg,
"*",
rustc_errors::Applicability::MachineApplicable,
);
}
};
let suggest_different_borrow =
|err: &mut Diag<'_, _>,
lhs_adjusted_ty,
lhs_new_mutbl: Option<ast::Mutability>,
rhs_adjusted_ty,
rhs_new_mutbl: Option<ast::Mutability>| {
if self
.lookup_op_method(
(lhs_expr, lhs_adjusted_ty),
Some((rhs_expr, rhs_adjusted_ty)),
Op::Binary(op, is_assign),
expected,
)
.is_ok()
{
let op_str = op.node.as_str();
err.note(format!("an implementation for `{lhs_adjusted_ty} {op_str} {rhs_adjusted_ty}` exists"));
if let Some(lhs_new_mutbl) = lhs_new_mutbl
&& let Some(rhs_new_mutbl) = rhs_new_mutbl
&& lhs_new_mutbl.is_not()
&& rhs_new_mutbl.is_not()
{
err.multipart_suggestion_verbose(
"consider reborrowing both sides",
vec![
(lhs_expr.span.shrink_to_lo(), "&*".to_string()),
(rhs_expr.span.shrink_to_lo(), "&*".to_string()),
],
rustc_errors::Applicability::MachineApplicable,
);
} else {
let mut suggest_new_borrow =
|new_mutbl: ast::Mutability, sp: Span| {
// Can reborrow (&mut -> &)
if new_mutbl.is_not() {
err.span_suggestion_verbose(
sp.shrink_to_lo(),
"consider reborrowing this side",
"&*",
rustc_errors::Applicability::MachineApplicable,
);
// Works on &mut but have &
} else {
err.span_help(
sp,
"consider making this expression a mutable borrow",
);
}
};
if let Some(lhs_new_mutbl) = lhs_new_mutbl {
suggest_new_borrow(lhs_new_mutbl, lhs_expr.span);
}
if let Some(rhs_new_mutbl) = rhs_new_mutbl {
suggest_new_borrow(rhs_new_mutbl, rhs_expr.span);
}
}
}
};
let is_compatible_after_call = |lhs_ty, rhs_ty| {
self.lookup_op_method(
(lhs_expr, lhs_ty),
Some((rhs_expr, rhs_ty)),
Op::Binary(op, is_assign),
expected,
)
.is_ok()
// Suggest calling even if, after calling, the types don't
// implement the operator, since it'll lead to better
// diagnostics later.
|| self.can_eq(self.param_env, lhs_ty, rhs_ty)
};
// We should suggest `a + b` => `*a + b` if `a` is copy, and suggest
// `a += b` => `*a += b` if a is a mut ref.
if !op.span.can_be_used_for_suggestions() {
// Suppress suggestions when lhs and rhs are not in the same span as the error
} else if is_assign == IsAssign::Yes
&& let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty)
{
suggest_deref_binop(&mut err, lhs_deref_ty);
} else if is_assign == IsAssign::No
&& let Ref(region, lhs_deref_ty, mutbl) = lhs_ty.kind()
{
if self.type_is_copy_modulo_regions(self.param_env, *lhs_deref_ty) {
suggest_deref_binop(&mut err, *lhs_deref_ty);
} else {
let lhs_inv_mutbl = mutbl.invert();
let lhs_inv_mutbl_ty =
Ty::new_ref(self.tcx, *region, *lhs_deref_ty, lhs_inv_mutbl);
suggest_different_borrow(
&mut err,
lhs_inv_mutbl_ty,
Some(lhs_inv_mutbl),
rhs_ty,
None,
);
if let Ref(region, rhs_deref_ty, mutbl) = rhs_ty.kind() {
let rhs_inv_mutbl = mutbl.invert();
let rhs_inv_mutbl_ty =
Ty::new_ref(self.tcx, *region, *rhs_deref_ty, rhs_inv_mutbl);
suggest_different_borrow(
&mut err,
lhs_ty,
None,
rhs_inv_mutbl_ty,
Some(rhs_inv_mutbl),
);
suggest_different_borrow(
&mut err,
lhs_inv_mutbl_ty,
Some(lhs_inv_mutbl),
rhs_inv_mutbl_ty,
Some(rhs_inv_mutbl),
);
}
}
} else if self.suggest_fn_call(&mut err, lhs_expr, lhs_ty, |lhs_ty| {
is_compatible_after_call(lhs_ty, rhs_ty)
}) || self.suggest_fn_call(&mut err, rhs_expr, rhs_ty, |rhs_ty| {
is_compatible_after_call(lhs_ty, rhs_ty)
}) || self.suggest_two_fn_call(
&mut err,
rhs_expr,
rhs_ty,
lhs_expr,
lhs_ty,
|lhs_ty, rhs_ty| is_compatible_after_call(lhs_ty, rhs_ty),
) {
// Cool
}
if let Some(missing_trait) = missing_trait {
if op.node == hir::BinOpKind::Add
&& self.check_str_addition(
lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, is_assign, op,
)
{
// This has nothing here because it means we did string
// concatenation (e.g., "Hello " + "World!"). This means
// we don't want the note in the else clause to be emitted
} else if lhs_ty.has_non_region_param() {
// Look for a TraitPredicate in the Fulfillment errors,
// and use it to generate a suggestion.
//
// Note that lookup_op_method must be called again but
// with a specific rhs_ty instead of a placeholder so
// the resulting predicate generates a more specific
// suggestion for the user.
let errors = self
.lookup_op_method(
(lhs_expr, lhs_ty),
Some((rhs_expr, rhs_ty)),
Op::Binary(op, is_assign),
expected,
)
.unwrap_err();
if !errors.is_empty() {
for error in errors {
if let Some(trait_pred) =
error.obligation.predicate.as_trait_clause()
{
let output_associated_item = match error.obligation.cause.code()
{
ObligationCauseCode::BinOp {
output_ty: Some(output_ty),
..
} => {
// Make sure that we're attaching `Output = ..` to the right trait predicate
if let Some(output_def_id) = output_def_id
&& let Some(trait_def_id) = trait_def_id
&& self.tcx.parent(output_def_id) == trait_def_id
&& let Some(output_ty) = output_ty
.make_suggestable(self.tcx, false, None)
{
Some(("Output", output_ty))
} else {
None
}
}
_ => None,
};
self.err_ctxt().suggest_restricting_param_bound(
&mut err,
trait_pred,
output_associated_item,
self.body_id,
);
}
}
} else {
// When we know that a missing bound is responsible, we don't show
// this note as it is redundant.
err.note(format!(
"the trait `{missing_trait}` is not implemented for `{lhs_ty}`"
));
}
}
}
// Suggest using `add`, `offset` or `offset_from` for pointer - {integer},
// pointer + {integer} or pointer - pointer.
if op.span.can_be_used_for_suggestions() {
match op.node {
hir::BinOpKind::Add if lhs_ty.is_unsafe_ptr() && rhs_ty.is_integral() => {
err.multipart_suggestion(
"consider using `wrapping_add` or `add` for pointer + {integer}",
vec![
(
lhs_expr.span.between(rhs_expr.span),
".wrapping_add(".to_owned(),
),
(rhs_expr.span.shrink_to_hi(), ")".to_owned()),
],
Applicability::MaybeIncorrect,
);
}
hir::BinOpKind::Sub => {
if lhs_ty.is_unsafe_ptr() && rhs_ty.is_integral() {
err.multipart_suggestion(
"consider using `wrapping_sub` or `sub` for pointer - {integer}",
vec![
(lhs_expr.span.between(rhs_expr.span), ".wrapping_sub(".to_owned()),
(rhs_expr.span.shrink_to_hi(), ")".to_owned()),
],
Applicability::MaybeIncorrect
);
}
if lhs_ty.is_unsafe_ptr() && rhs_ty.is_unsafe_ptr() {
err.multipart_suggestion(
"consider using `offset_from` for pointer - pointer if the pointers point to the same allocation",
vec![
(lhs_expr.span.shrink_to_lo(), "unsafe { ".to_owned()),
(lhs_expr.span.between(rhs_expr.span), ".offset_from(".to_owned()),
(rhs_expr.span.shrink_to_hi(), ") }".to_owned()),
],
Applicability::MaybeIncorrect
);
}
}
_ => {}
}
}
let reported = err.emit();
Ty::new_error(self.tcx, reported)
}
};
(lhs_ty, rhs_ty, return_ty)
}
/// Provide actionable suggestions when trying to add two strings with incorrect types,
/// like `&str + &str`, `String + String` and `&str + &String`.
///
/// If this function returns `true` it means a note was printed, so we don't need
/// to print the normal "implementation of `std::ops::Add` might be missing" note
fn check_str_addition(
&self,
lhs_expr: &'tcx hir::Expr<'tcx>,
rhs_expr: &'tcx hir::Expr<'tcx>,
lhs_ty: Ty<'tcx>,
rhs_ty: Ty<'tcx>,
err: &mut Diag<'_>,
is_assign: IsAssign,
op: hir::BinOp,
) -> bool {
let str_concat_note = "string concatenation requires an owned `String` on the left";
let rm_borrow_msg = "remove the borrow to obtain an owned `String`";
let to_owned_msg = "create an owned `String` from a string reference";
let string_type = self.tcx.lang_items().string();
let is_std_string =
|ty: Ty<'tcx>| ty.ty_adt_def().is_some_and(|ty_def| Some(ty_def.did()) == string_type);
match (lhs_ty.kind(), rhs_ty.kind()) {
(&Ref(_, l_ty, _), &Ref(_, r_ty, _)) // &str or &String + &str, &String or &&str
if (*l_ty.kind() == Str || is_std_string(l_ty))
&& (*r_ty.kind() == Str
|| is_std_string(r_ty)
|| matches!(
r_ty.kind(), Ref(_, inner_ty, _) if *inner_ty.kind() == Str
)) =>
{
if let IsAssign::No = is_assign { // Do not supply this message if `&str += &str`
err.span_label(op.span, "`+` cannot be used to concatenate two `&str` strings");
err.note(str_concat_note);
if let hir::ExprKind::AddrOf(_, _, lhs_inner_expr) = lhs_expr.kind {
err.span_suggestion_verbose(
lhs_expr.span.until(lhs_inner_expr.span),
rm_borrow_msg,
"",
Applicability::MachineApplicable
);
} else {
err.span_suggestion_verbose(
lhs_expr.span.shrink_to_hi(),
to_owned_msg,
".to_owned()",
Applicability::MachineApplicable
);
}
}
true
}
(&Ref(_, l_ty, _), &Adt(..)) // Handle `&str` & `&String` + `String`
if (*l_ty.kind() == Str || is_std_string(l_ty)) && is_std_string(rhs_ty) =>
{
err.span_label(
op.span,
"`+` cannot be used to concatenate a `&str` with a `String`",
);
match is_assign {
IsAssign::No => {
let sugg_msg;
let lhs_sugg = if let hir::ExprKind::AddrOf(_, _, lhs_inner_expr) = lhs_expr.kind {
sugg_msg = "remove the borrow on the left and add one on the right";
(lhs_expr.span.until(lhs_inner_expr.span), "".to_owned())
} else {
sugg_msg = "create an owned `String` on the left and add a borrow on the right";
(lhs_expr.span.shrink_to_hi(), ".to_owned()".to_owned())
};
let suggestions = vec![
lhs_sugg,
(rhs_expr.span.shrink_to_lo(), "&".to_owned()),
];
err.multipart_suggestion_verbose(
sugg_msg,
suggestions,
Applicability::MachineApplicable,
);
}
IsAssign::Yes => {
err.note(str_concat_note);
}
}
true
}
_ => false,
}
}
pub(crate) fn check_user_unop(
&self,
ex: &'tcx hir::Expr<'tcx>,
operand_ty: Ty<'tcx>,
op: hir::UnOp,
expected: Expectation<'tcx>,
) -> Ty<'tcx> {
assert!(op.is_by_value());
match self.lookup_op_method((ex, operand_ty), None, Op::Unary(op, ex.span), expected) {
Ok(method) => {
self.write_method_call_and_enforce_effects(ex.hir_id, ex.span, method);
method.sig.output()
}
Err(errors) => {
let actual = self.resolve_vars_if_possible(operand_ty);
let guar = actual.error_reported().err().unwrap_or_else(|| {
let mut err = struct_span_code_err!(
self.dcx(),
ex.span,
E0600,
"cannot apply unary operator `{}` to type `{}`",
op.as_str(),
actual
);
err.span_label(
ex.span,
format!("cannot apply unary operator `{}`", op.as_str()),
);
if operand_ty.has_non_region_param() {
let predicates = errors
.iter()
.filter_map(|error| error.obligation.predicate.as_trait_clause());
for pred in predicates {
self.err_ctxt().suggest_restricting_param_bound(
&mut err,
pred,
None,
self.body_id,
);
}
}
let sp = self.tcx.sess.source_map().start_point(ex.span).with_parent(None);
if let Some(sp) =
self.tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp)
{
// If the previous expression was a block expression, suggest parentheses
// (turning this into a binary subtraction operation instead.)
// for example, `{2} - 2` -> `({2}) - 2` (see src\test\ui\parser\expr-as-stmt.rs)
err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
} else {
match actual.kind() {
Uint(_) if op == hir::UnOp::Neg => {
err.note("unsigned values cannot be negated");
if let hir::ExprKind::Unary(
_,
hir::Expr {
kind:
hir::ExprKind::Lit(Spanned {
node: ast::LitKind::Int(Pu128(1), _),
..
}),
..
},
) = ex.kind
{
let span = if let hir::Node::Expr(parent) =
self.tcx.parent_hir_node(ex.hir_id)
&& let hir::ExprKind::Cast(..) = parent.kind
{
// `-1 as usize` -> `usize::MAX`
parent.span
} else {
ex.span
};
err.span_suggestion_verbose(
span,
format!(
"you may have meant the maximum value of `{actual}`",
),
format!("{actual}::MAX"),
Applicability::MaybeIncorrect,
);
}
}
Str | Never | Char | Tuple(_) | Array(_, _) => {}
Ref(_, lty, _) if *lty.kind() == Str => {}
_ => {
self.note_unmet_impls_on_type(&mut err, errors, true);
}
}
}
err.emit()
});
Ty::new_error(self.tcx, guar)
}
}
}
fn lookup_op_method(
&self,
(lhs_expr, lhs_ty): (&'tcx hir::Expr<'tcx>, Ty<'tcx>),
opt_rhs: Option<(&'tcx hir::Expr<'tcx>, Ty<'tcx>)>,
op: Op,
expected: Expectation<'tcx>,
) -> Result<MethodCallee<'tcx>, Vec<FulfillmentError<'tcx>>> {
let span = match op {
Op::Binary(op, _) => op.span,
Op::Unary(_, span) => span,
};
let (opname, Some(trait_did)) = lang_item_for_op(self.tcx, op, span) else {
// Bail if the operator trait is not defined.
return Err(vec![]);
};
debug!(
"lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
lhs_ty, op, opname, trait_did
);
let opname = Ident::with_dummy_span(opname);
let (opt_rhs_expr, opt_rhs_ty) = opt_rhs.unzip();
let input_types = opt_rhs_ty.as_slice();
let cause = self.cause(
span,
ObligationCauseCode::BinOp {
lhs_hir_id: lhs_expr.hir_id,
rhs_hir_id: opt_rhs_expr.map(|expr| expr.hir_id),
rhs_span: opt_rhs_expr.map(|expr| expr.span),
rhs_is_lit: opt_rhs_expr
.is_some_and(|expr| matches!(expr.kind, hir::ExprKind::Lit(_))),
output_ty: expected.only_has_type(self),
},
);
let method = self.lookup_method_in_trait(
cause.clone(),
opname,
trait_did,
lhs_ty,
Some(input_types),
);
match method {
Some(ok) => {
let method = self.register_infer_ok_obligations(ok);
self.select_obligations_where_possible(|_| {});
Ok(method)
}
None => {
// This path may do some inference, so make sure we've really
// doomed compilation so as to not accidentally stabilize new
// inference or something here...
self.dcx().span_delayed_bug(span, "this path really should be doomed...");
// Guide inference for the RHS expression if it's provided --
// this will allow us to better error reporting, at the expense
// of making some error messages a bit more specific.
if let Some((rhs_expr, rhs_ty)) = opt_rhs
&& rhs_ty.is_ty_var()
{
self.check_expr_coercible_to_type(rhs_expr, rhs_ty, None);
}
let (obligation, _) =
self.obligation_for_method(cause, trait_did, lhs_ty, Some(input_types));
// FIXME: This should potentially just add the obligation to the `FnCtxt`
let ocx = ObligationCtxt::new_with_diagnostics(&self.infcx);
ocx.register_obligation(obligation);
Err(ocx.select_all_or_error())
}
}
}
}
fn lang_item_for_op(
tcx: TyCtxt<'_>,
op: Op,
span: Span,
) -> (rustc_span::Symbol, Option<hir::def_id::DefId>) {
let lang = tcx.lang_items();
if let Op::Binary(op, IsAssign::Yes) = op {
match op.node {
hir::BinOpKind::Add => (sym::add_assign, lang.add_assign_trait()),
hir::BinOpKind::Sub => (sym::sub_assign, lang.sub_assign_trait()),
hir::BinOpKind::Mul => (sym::mul_assign, lang.mul_assign_trait()),
hir::BinOpKind::Div => (sym::div_assign, lang.div_assign_trait()),
hir::BinOpKind::Rem => (sym::rem_assign, lang.rem_assign_trait()),
hir::BinOpKind::BitXor => (sym::bitxor_assign, lang.bitxor_assign_trait()),
hir::BinOpKind::BitAnd => (sym::bitand_assign, lang.bitand_assign_trait()),
hir::BinOpKind::BitOr => (sym::bitor_assign, lang.bitor_assign_trait()),
hir::BinOpKind::Shl => (sym::shl_assign, lang.shl_assign_trait()),
hir::BinOpKind::Shr => (sym::shr_assign, lang.shr_assign_trait()),
hir::BinOpKind::Lt
| hir::BinOpKind::Le
| hir::BinOpKind::Ge
| hir::BinOpKind::Gt
| hir::BinOpKind::Eq
| hir::BinOpKind::Ne
| hir::BinOpKind::And
| hir::BinOpKind::Or => {
span_bug!(span, "impossible assignment operation: {}=", op.node.as_str())
}
}
} else if let Op::Binary(op, IsAssign::No) = op {
match op.node {
hir::BinOpKind::Add => (sym::add, lang.add_trait()),
hir::BinOpKind::Sub => (sym::sub, lang.sub_trait()),
hir::BinOpKind::Mul => (sym::mul, lang.mul_trait()),
hir::BinOpKind::Div => (sym::div, lang.div_trait()),
hir::BinOpKind::Rem => (sym::rem, lang.rem_trait()),
hir::BinOpKind::BitXor => (sym::bitxor, lang.bitxor_trait()),
hir::BinOpKind::BitAnd => (sym::bitand, lang.bitand_trait()),
hir::BinOpKind::BitOr => (sym::bitor, lang.bitor_trait()),
hir::BinOpKind::Shl => (sym::shl, lang.shl_trait()),
hir::BinOpKind::Shr => (sym::shr, lang.shr_trait()),
hir::BinOpKind::Lt => (sym::lt, lang.partial_ord_trait()),
hir::BinOpKind::Le => (sym::le, lang.partial_ord_trait()),
hir::BinOpKind::Ge => (sym::ge, lang.partial_ord_trait()),
hir::BinOpKind::Gt => (sym::gt, lang.partial_ord_trait()),
hir::BinOpKind::Eq => (sym::eq, lang.eq_trait()),
hir::BinOpKind::Ne => (sym::ne, lang.eq_trait()),
hir::BinOpKind::And | hir::BinOpKind::Or => {
span_bug!(span, "&& and || are not overloadable")
}
}
} else if let Op::Unary(hir::UnOp::Not, _) = op {
(sym::not, lang.not_trait())
} else if let Op::Unary(hir::UnOp::Neg, _) = op {
(sym::neg, lang.neg_trait())
} else {
bug!("lookup_op_method: op not supported: {:?}", op)
}
}
// Binary operator categories. These categories summarize the behavior
// with respect to the builtin operations supported.
enum BinOpCategory {
/// &&, || -- cannot be overridden
Shortcircuit,
/// <<, >> -- when shifting a single integer, rhs can be any
/// integer type. For simd, types must match.
Shift,
/// +, -, etc -- takes equal types, produces same type as input,
/// applicable to ints/floats/simd
Math,
/// &, |, ^ -- takes equal types, produces same type as input,
/// applicable to ints/floats/simd/bool
Bitwise,
/// ==, !=, etc -- takes equal types, produces bools, except for simd,
/// which produce the input type
Comparison,
}
impl BinOpCategory {
fn from(op: hir::BinOp) -> BinOpCategory {
match op.node {
hir::BinOpKind::Shl | hir::BinOpKind::Shr => BinOpCategory::Shift,
hir::BinOpKind::Add
| hir::BinOpKind::Sub
| hir::BinOpKind::Mul
| hir::BinOpKind::Div
| hir::BinOpKind::Rem => BinOpCategory::Math,
hir::BinOpKind::BitXor | hir::BinOpKind::BitAnd | hir::BinOpKind::BitOr => {
BinOpCategory::Bitwise
}
hir::BinOpKind::Eq
| hir::BinOpKind::Ne
| hir::BinOpKind::Lt
| hir::BinOpKind::Le
| hir::BinOpKind::Ge
| hir::BinOpKind::Gt => BinOpCategory::Comparison,
hir::BinOpKind::And | hir::BinOpKind::Or => BinOpCategory::Shortcircuit,
}
}
}
/// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
#[derive(Clone, Copy, Debug, PartialEq)]
enum IsAssign {
No,
Yes,
}
#[derive(Clone, Copy, Debug)]
enum Op {
Binary(hir::BinOp, IsAssign),
Unary(hir::UnOp, Span),
}
/// Dereferences a single level of immutable referencing.
fn deref_ty_if_possible(ty: Ty<'_>) -> Ty<'_> {
match ty.kind() {
ty::Ref(_, ty, hir::Mutability::Not) => *ty,
_ => ty,
}
}
/// Returns `true` if this is a built-in arithmetic operation (e.g., u32
/// + u32, i16x4 == i16x4) and false if these types would have to be
/// overloaded to be legal. There are two reasons that we distinguish
/// builtin operations from overloaded ones (vs trying to drive
/// everything uniformly through the trait system and intrinsics or
/// something like that):
///
/// 1. Builtin operations can trivially be evaluated in constants.
/// 2. For comparison operators applied to SIMD types the result is
/// not of type `bool`. For example, `i16x4 == i16x4` yields a
/// type like `i16x4`. This means that the overloaded trait
/// `PartialEq` is not applicable.
///
/// Reason #2 is the killer. I tried for a while to always use
/// overloaded logic and just check the types in constants/codegen after
/// the fact, and it worked fine, except for SIMD types. -nmatsakis
fn is_builtin_binop<'tcx>(lhs: Ty<'tcx>, rhs: Ty<'tcx>, op: hir::BinOp) -> bool {
// Special-case a single layer of referencing, so that things like `5.0 + &6.0f32` work.
// (See https://github.com/rust-lang/rust/issues/57447.)
let (lhs, rhs) = (deref_ty_if_possible(lhs), deref_ty_if_possible(rhs));
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => true,
BinOpCategory::Shift => {
lhs.references_error()
|| rhs.references_error()
|| lhs.is_integral() && rhs.is_integral()
}
BinOpCategory::Math => {
lhs.references_error()
|| rhs.references_error()
|| lhs.is_integral() && rhs.is_integral()
|| lhs.is_floating_point() && rhs.is_floating_point()
}
BinOpCategory::Bitwise => {
lhs.references_error()
|| rhs.references_error()
|| lhs.is_integral() && rhs.is_integral()
|| lhs.is_floating_point() && rhs.is_floating_point()
|| lhs.is_bool() && rhs.is_bool()
}
BinOpCategory::Comparison => {
lhs.references_error() || rhs.references_error() || lhs.is_scalar() && rhs.is_scalar()
}
}
}