Skip to main content

rustc_hir_typeck/
op.rs

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