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