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