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