rustc_hir_typeck/
op.rs

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