]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_typeck/src/check/demand.rs
New upstream version 1.50.0+dfsg1
[rustc.git] / compiler / rustc_typeck / src / check / demand.rs
CommitLineData
9fa01778 1use crate::check::FnCtxt;
74b04a01 2use rustc_infer::infer::InferOk;
ba9703b0 3use rustc_trait_selection::infer::InferCtxtExt as _;
f9f354fc 4use rustc_trait_selection::traits::ObligationCause;
1a4d82fc 5
74b04a01 6use rustc_ast::util::parser::PREC_POSTFIX;
dfeec247
XL
7use rustc_errors::{Applicability, DiagnosticBuilder};
8use rustc_hir as hir;
3dfed10e 9use rustc_hir::lang_items::LangItem;
ba9703b0
XL
10use rustc_hir::{is_range_literal, Node};
11use rustc_middle::ty::adjustment::AllowTwoPhase;
f9f354fc 12use rustc_middle::ty::{self, AssocItem, Ty, TypeAndMut};
dfeec247
XL
13use rustc_span::symbol::sym;
14use rustc_span::Span;
32a655c1
SL
15
16use super::method::probe;
1a4d82fc 17
f035d41b
XL
18use std::fmt;
19
dc9dc135 20impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
60c5eb7d
XL
21 pub fn emit_coerce_suggestions(
22 &self,
23 err: &mut DiagnosticBuilder<'_>,
dfeec247 24 expr: &hir::Expr<'_>,
60c5eb7d 25 expr_ty: Ty<'tcx>,
dfeec247 26 expected: Ty<'tcx>,
f035d41b 27 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
60c5eb7d
XL
28 ) {
29 self.annotate_expected_due_to_let_ty(err, expr);
30 self.suggest_compatible_variants(err, expr, expected, expr_ty);
f035d41b 31 self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr);
74b04a01
XL
32 if self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty) {
33 return;
34 }
60c5eb7d 35 self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty);
3dfed10e 36 self.suggest_missing_parentheses(err, expr);
f035d41b 37 self.note_need_for_fn_pointer(err, expected, expr_ty);
3dfed10e 38 self.note_internal_mutation_in_method(err, expr, expected, expr_ty);
60c5eb7d
XL
39 }
40
a7813a04
XL
41 // Requires that the two types unify, and prints an error message if
42 // they don't.
43 pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
f9f354fc
XL
44 if let Some(mut e) = self.demand_suptype_diag(sp, expected, actual) {
45 e.emit();
46 }
041b39d2
XL
47 }
48
dfeec247
XL
49 pub fn demand_suptype_diag(
50 &self,
51 sp: Span,
52 expected: Ty<'tcx>,
53 actual: Ty<'tcx>,
54 ) -> Option<DiagnosticBuilder<'tcx>> {
74b04a01
XL
55 self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
56 }
57
58 pub fn demand_suptype_with_origin(
59 &self,
60 cause: &ObligationCause<'tcx>,
61 expected: Ty<'tcx>,
62 actual: Ty<'tcx>,
63 ) -> Option<DiagnosticBuilder<'tcx>> {
7cac9316 64 match self.at(cause, self.param_env).sup(expected, actual) {
476ff2be
SL
65 Ok(InferOk { obligations, value: () }) => {
66 self.register_predicates(obligations);
041b39d2 67 None
a7813a04 68 }
dfeec247 69 Err(e) => Some(self.report_mismatched_types(&cause, expected, actual, e)),
54a0048b 70 }
1a4d82fc 71 }
1a4d82fc 72
a7813a04 73 pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
32a655c1
SL
74 if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
75 err.emit();
76 }
77 }
78
dfeec247
XL
79 pub fn demand_eqtype_diag(
80 &self,
81 sp: Span,
82 expected: Ty<'tcx>,
83 actual: Ty<'tcx>,
84 ) -> Option<DiagnosticBuilder<'tcx>> {
32a655c1 85 self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
5bcae85e
SL
86 }
87
dfeec247
XL
88 pub fn demand_eqtype_with_origin(
89 &self,
90 cause: &ObligationCause<'tcx>,
91 expected: Ty<'tcx>,
92 actual: Ty<'tcx>,
93 ) -> Option<DiagnosticBuilder<'tcx>> {
7cac9316 94 match self.at(cause, self.param_env).eq(expected, actual) {
476ff2be
SL
95 Ok(InferOk { obligations, value: () }) => {
96 self.register_predicates(obligations);
32a655c1 97 None
3b2f2976 98 }
dfeec247 99 Err(e) => Some(self.report_mismatched_types(cause, expected, actual, e)),
54a0048b 100 }
1a4d82fc 101 }
1a4d82fc 102
dfeec247 103 pub fn demand_coerce(
e74abb32 104 &self,
dfeec247
XL
105 expr: &hir::Expr<'_>,
106 checked_ty: Ty<'tcx>,
e74abb32 107 expected: Ty<'tcx>,
f035d41b 108 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
dfeec247
XL
109 allow_two_phase: AllowTwoPhase,
110 ) -> Ty<'tcx> {
f035d41b
XL
111 let (ty, err) =
112 self.demand_coerce_diag(expr, checked_ty, expected, expected_ty_expr, allow_two_phase);
abe05a73 113 if let Some(mut err) = err {
041b39d2
XL
114 err.emit();
115 }
abe05a73 116 ty
041b39d2
XL
117 }
118
1b1a35ee
XL
119 /// Checks that the type of `expr` can be coerced to `expected`.
120 ///
121 /// N.B., this code relies on `self.diverges` to be accurate. In particular, assignments to `!`
122 /// will be permitted if the diverges flag is currently "always".
60c5eb7d
XL
123 pub fn demand_coerce_diag(
124 &self,
dfeec247 125 expr: &hir::Expr<'_>,
60c5eb7d
XL
126 checked_ty: Ty<'tcx>,
127 expected: Ty<'tcx>,
f035d41b 128 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
60c5eb7d
XL
129 allow_two_phase: AllowTwoPhase,
130 ) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx>>) {
e74abb32 131 let expected = self.resolve_vars_with_obligations(expected);
cc61c64b 132
83c7162d 133 let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase) {
abe05a73 134 Ok(ty) => return (ty, None),
dfeec247 135 Err(e) => e,
abe05a73
XL
136 };
137
e74abb32 138 let expr = expr.peel_drop_temps();
abe05a73 139 let cause = self.misc(expr.span);
e74abb32 140 let expr_ty = self.resolve_vars_with_obligations(checked_ty);
abe05a73
XL
141 let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
142
532ac7d7
XL
143 if self.is_assign_to_bool(expr, expected) {
144 // Error reported in `check_assign` so avoid emitting error again.
145 err.delay_as_bug();
dfeec247 146 return (expected, None);
abe05a73 147 }
3b2f2976 148
f035d41b 149 self.emit_coerce_suggestions(&mut err, expr, expr_ty, expected, expected_ty_expr);
8faf50e0 150
abe05a73 151 (expected, Some(err))
32a655c1
SL
152 }
153
dfeec247
XL
154 fn annotate_expected_due_to_let_ty(
155 &self,
156 err: &mut DiagnosticBuilder<'_>,
157 expr: &hir::Expr<'_>,
158 ) {
60c5eb7d 159 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
dfeec247
XL
160 if let Some(hir::Node::Local(hir::Local { ty: Some(ty), init: Some(init), .. })) =
161 self.tcx.hir().find(parent)
162 {
60c5eb7d
XL
163 if init.hir_id == expr.hir_id {
164 // Point at `let` assignment type.
165 err.span_label(ty.span, "expected due to this");
166 }
167 }
168 }
169
532ac7d7 170 /// Returns whether the expected type is `bool` and the expression is `x = y`.
dfeec247 171 pub fn is_assign_to_bool(&self, expr: &hir::Expr<'_>, expected: Ty<'tcx>) -> bool {
e74abb32 172 if let hir::ExprKind::Assign(..) = expr.kind {
532ac7d7
XL
173 return expected == self.tcx.types.bool;
174 }
175 false
176 }
177
178 /// If the expected type is an enum (Issue #55250) with any variants whose
179 /// sole field is of the found type, suggest such variants. (Issue #42764)
180 fn suggest_compatible_variants(
181 &self,
182 err: &mut DiagnosticBuilder<'_>,
dfeec247 183 expr: &hir::Expr<'_>,
532ac7d7
XL
184 expected: Ty<'tcx>,
185 expr_ty: Ty<'tcx>,
186 ) {
1b1a35ee 187 if let ty::Adt(expected_adt, substs) = expected.kind() {
532ac7d7
XL
188 if !expected_adt.is_enum() {
189 return;
190 }
191
dfeec247
XL
192 let mut compatible_variants = expected_adt
193 .variants
532ac7d7
XL
194 .iter()
195 .filter(|variant| variant.fields.len() == 1)
196 .filter_map(|variant| {
197 let sole_field = &variant.fields[0];
198 let sole_field_ty = sole_field.ty(self.tcx, substs);
199 if self.can_coerce(expr_ty, sole_field_ty) {
200 let variant_path = self.tcx.def_path_str(variant.def_id);
201 // FIXME #56861: DRYer prelude filtering
202 Some(variant_path.trim_start_matches("std::prelude::v1::").to_string())
203 } else {
204 None
205 }
dfeec247
XL
206 })
207 .peekable();
532ac7d7
XL
208
209 if compatible_variants.peek().is_some() {
ba9703b0
XL
210 if let Ok(expr_text) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
211 let suggestions = compatible_variants.map(|v| format!("{}({})", v, expr_text));
212 let msg = "try using a variant of the expected enum";
213 err.span_suggestions(
214 expr.span,
215 msg,
216 suggestions,
217 Applicability::MaybeIncorrect,
218 );
219 }
532ac7d7
XL
220 }
221 }
222 }
223
dfeec247
XL
224 pub fn get_conversion_methods(
225 &self,
226 span: Span,
227 expected: Ty<'tcx>,
228 checked_ty: Ty<'tcx>,
ba9703b0 229 hir_id: hir::HirId,
dfeec247 230 ) -> Vec<AssocItem> {
ba9703b0
XL
231 let mut methods =
232 self.probe_for_return_type(span, probe::Mode::MethodCall, expected, checked_ty, hir_id);
2c00a5a8 233 methods.retain(|m| {
ba9703b0 234 self.has_only_self_parameter(m)
dfeec247
XL
235 && self
236 .tcx
237 .get_attrs(m.def_id)
238 .iter()
f035d41b 239 // This special internal attribute is used to permit
dfeec247
XL
240 // "identity-like" conversion methods to be suggested here.
241 //
242 // FIXME (#46459 and #46460): ideally
243 // `std::convert::Into::into` and `std::borrow:ToOwned` would
244 // also be `#[rustc_conversion_suggestion]`, if not for
245 // method-probing false-positives and -negatives (respectively).
246 //
247 // FIXME? Other potential candidate methods: `as_ref` and
248 // `as_mut`?
3dfed10e 249 .any(|a| self.sess().check_name(a, sym::rustc_conversion_suggestion))
2c00a5a8 250 });
32a655c1 251
2c00a5a8 252 methods
32a655c1
SL
253 }
254
ba9703b0
XL
255 /// This function checks whether the method is not static and does not accept other parameters than `self`.
256 fn has_only_self_parameter(&self, method: &AssocItem) -> bool {
48663c56 257 match method.kind {
ba9703b0
XL
258 ty::AssocKind::Fn => {
259 method.fn_has_self_parameter
260 && self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
32a655c1
SL
261 }
262 _ => false,
a7813a04
XL
263 }
264 }
cc61c64b 265
94b46f34
XL
266 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
267 ///
268 /// Given the following code:
269 /// ```
270 /// struct Foo;
271 /// fn takes_ref(_: &Foo) {}
272 /// let ref opt = Some(Foo);
273 ///
e1599b0c 274 /// opt.map(|param| takes_ref(param));
94b46f34 275 /// ```
e1599b0c 276 /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
94b46f34
XL
277 ///
278 /// It only checks for `Option` and `Result` and won't work with
279 /// ```
e1599b0c 280 /// opt.map(|param| { takes_ref(param) });
94b46f34 281 /// ```
dfeec247 282 fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Span, &'static str, String)> {
e74abb32 283 let path = match expr.kind {
416331ca 284 hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => path,
dfeec247 285 _ => return None,
416331ca
XL
286 };
287
288 let local_id = match path.res {
289 hir::def::Res::Local(id) => id,
dfeec247 290 _ => return None,
416331ca
XL
291 };
292
293 let local_parent = self.tcx.hir().get_parent_node(local_id);
e1599b0c
XL
294 let param_hir_id = match self.tcx.hir().find(local_parent) {
295 Some(Node::Param(hir::Param { hir_id, .. })) => hir_id,
dfeec247 296 _ => return None,
416331ca
XL
297 };
298
e1599b0c
XL
299 let param_parent = self.tcx.hir().get_parent_node(*param_hir_id);
300 let (expr_hir_id, closure_fn_decl) = match self.tcx.hir().find(param_parent) {
dfeec247
XL
301 Some(Node::Expr(hir::Expr {
302 hir_id,
303 kind: hir::ExprKind::Closure(_, decl, ..),
304 ..
305 })) => (hir_id, decl),
306 _ => return None,
416331ca
XL
307 };
308
309 let expr_parent = self.tcx.hir().get_parent_node(*expr_hir_id);
310 let hir = self.tcx.hir().find(expr_parent);
311 let closure_params_len = closure_fn_decl.inputs.len();
312 let (method_path, method_span, method_expr) = match (hir, closure_params_len) {
dfeec247
XL
313 (
314 Some(Node::Expr(hir::Expr {
f035d41b 315 kind: hir::ExprKind::MethodCall(path, span, expr, _),
dfeec247
XL
316 ..
317 })),
318 1,
319 ) => (path, span, expr),
320 _ => return None,
416331ca
XL
321 };
322
3dfed10e 323 let self_ty = self.typeck_results.borrow().node_type(method_expr[0].hir_id);
416331ca 324 let self_ty = format!("{:?}", self_ty);
3dfed10e 325 let name = method_path.ident.name;
dfeec247
XL
326 let is_as_ref_able = (self_ty.starts_with("&std::option::Option")
327 || self_ty.starts_with("&std::result::Result")
328 || self_ty.starts_with("std::option::Option")
329 || self_ty.starts_with("std::result::Result"))
3dfed10e 330 && (name == sym::map || name == sym::and_then);
416331ca
XL
331 match (is_as_ref_able, self.sess().source_map().span_to_snippet(*method_span)) {
332 (true, Ok(src)) => {
333 let suggestion = format!("as_ref().{}", src);
334 Some((*method_span, "consider using `as_ref` instead", suggestion))
dfeec247
XL
335 }
336 _ => None,
94b46f34 337 }
94b46f34
XL
338 }
339
dc9dc135
XL
340 crate fn is_hir_id_from_struct_pattern_shorthand_field(
341 &self,
342 hir_id: hir::HirId,
343 sp: Span,
344 ) -> bool {
74b04a01 345 let sm = self.sess().source_map();
dc9dc135
XL
346 let parent_id = self.tcx.hir().get_parent_node(hir_id);
347 if let Some(parent) = self.tcx.hir().find(parent_id) {
532ac7d7 348 // Account for fields
dfeec247
XL
349 if let Node::Expr(hir::Expr { kind: hir::ExprKind::Struct(_, fields, ..), .. }) = parent
350 {
74b04a01 351 if let Ok(src) = sm.span_to_snippet(sp) {
dfeec247 352 for field in *fields {
60c5eb7d 353 if field.ident.as_str() == src && field.is_shorthand {
532ac7d7
XL
354 return true;
355 }
356 }
357 }
358 }
359 }
360 false
361 }
362
cc61c64b
XL
363 /// This function is used to determine potential "simple" improvements or users' errors and
364 /// provide them useful help. For example:
365 ///
366 /// ```
367 /// fn some_fn(s: &str) {}
368 ///
369 /// let x = "hey!".to_owned();
370 /// some_fn(x); // error
371 /// ```
372 ///
373 /// No need to find every potential function which could make a coercion to transform a
374 /// `String` into a `&str` since a `&` would do the trick!
375 ///
376 /// In addition of this check, it also checks between references mutability state. If the
377 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
378 /// `&mut`!".
dc9dc135
XL
379 pub fn check_ref(
380 &self,
dfeec247 381 expr: &hir::Expr<'_>,
dc9dc135
XL
382 checked_ty: Ty<'tcx>,
383 expected: Ty<'tcx>,
f9f354fc 384 ) -> Option<(Span, &'static str, String, Applicability)> {
74b04a01 385 let sm = self.sess().source_map();
532ac7d7 386 let sp = expr.span;
ba9703b0 387 if sm.is_imported(sp) {
532ac7d7
XL
388 // Ignore if span is from within a macro #41858, #58298. We previously used the macro
389 // call span, but that breaks down when the type error comes from multiple calls down.
8faf50e0
XL
390 return None;
391 }
392
fc512014
XL
393 let replace_prefix = |s: &str, old: &str, new: &str| {
394 s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
395 };
396
dfeec247
XL
397 let is_struct_pat_shorthand_field =
398 self.is_hir_id_from_struct_pattern_shorthand_field(expr.hir_id, sp);
532ac7d7 399
e1599b0c
XL
400 // If the span is from a macro, then it's hard to extract the text
401 // and make a good suggestion, so don't bother.
e74abb32
XL
402 let is_macro = sp.from_expansion() && sp.desugaring_kind().is_none();
403
404 // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
405 let expr = expr.peel_drop_temps();
48663c56 406
1b1a35ee
XL
407 match (&expr.kind, expected.kind(), checked_ty.kind()) {
408 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (exp.kind(), check.kind()) {
ba9703b0 409 (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
e74abb32 410 if let hir::ExprKind::Lit(_) = expr.kind {
74b04a01 411 if let Ok(src) = sm.span_to_snippet(sp) {
fc512014 412 if let Some(src) = replace_prefix(&src, "b\"", "\"") {
dfeec247
XL
413 return Some((
414 sp,
415 "consider removing the leading `b`",
f9f354fc
XL
416 src,
417 Applicability::MachineApplicable,
dfeec247 418 ));
8faf50e0 419 }
ea8adc8c
XL
420 }
421 }
dfeec247 422 }
ba9703b0 423 (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
e74abb32 424 if let hir::ExprKind::Lit(_) = expr.kind {
74b04a01 425 if let Ok(src) = sm.span_to_snippet(sp) {
fc512014 426 if let Some(src) = replace_prefix(&src, "\"", "b\"") {
dfeec247
XL
427 return Some((
428 sp,
429 "consider adding a leading `b`",
f9f354fc
XL
430 src,
431 Applicability::MachineApplicable,
dfeec247 432 ));
8faf50e0 433 }
ea8adc8c
XL
434 }
435 }
ea8adc8c 436 }
94b46f34 437 _ => {}
ea8adc8c 438 },
48663c56 439 (_, &ty::Ref(_, _, mutability), _) => {
cc61c64b
XL
440 // Check if it can work when put into a ref. For example:
441 //
442 // ```
443 // fn bar(x: &mut i32) {}
444 //
445 // let x = 0u32;
446 // bar(&x); // error, expected &mut
447 // ```
94b46f34 448 let ref_ty = match mutability {
dfeec247 449 hir::Mutability::Mut => {
532ac7d7
XL
450 self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
451 }
dfeec247 452 hir::Mutability::Not => {
532ac7d7
XL
453 self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
454 }
cc61c64b
XL
455 };
456 if self.can_coerce(ref_ty, expected) {
dc9dc135 457 let mut sugg_sp = sp;
f035d41b 458 if let hir::ExprKind::MethodCall(ref segment, sp, ref args, _) = expr.kind {
3dfed10e 459 let clone_trait = self.tcx.require_lang_item(LangItem::Clone, Some(sp));
60c5eb7d 460 if let ([arg], Some(true), sym::clone) = (
dc9dc135 461 &args[..],
3dfed10e
XL
462 self.typeck_results.borrow().type_dependent_def_id(expr.hir_id).map(
463 |did| {
464 let ai = self.tcx.associated_item(did);
465 ai.container == ty::TraitContainer(clone_trait)
466 },
467 ),
60c5eb7d 468 segment.ident.name,
dc9dc135
XL
469 ) {
470 // If this expression had a clone call when suggesting borrowing
60c5eb7d 471 // we want to suggest removing it because it'd now be unnecessary.
dc9dc135
XL
472 sugg_sp = arg.span;
473 }
474 }
74b04a01 475 if let Ok(src) = sm.span_to_snippet(sugg_sp) {
e74abb32 476 let needs_parens = match expr.kind {
0bf4aa26 477 // parenthesize if needed (Issue #46756)
dfeec247 478 hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
0bf4aa26 479 // parenthesize borrows of range literals (Issue #54505)
3dfed10e 480 _ if is_range_literal(expr) => true,
0bf4aa26
XL
481 _ => false,
482 };
dfeec247 483 let sugg_expr = if needs_parens { format!("({})", src) } else { src };
0bf4aa26 484
94b46f34 485 if let Some(sugg) = self.can_use_as_ref(expr) {
f9f354fc
XL
486 return Some((
487 sugg.0,
488 sugg.1,
489 sugg.2,
490 Applicability::MachineApplicable,
491 ));
94b46f34 492 }
532ac7d7
XL
493 let field_name = if is_struct_pat_shorthand_field {
494 format!("{}: ", sugg_expr)
495 } else {
496 String::new()
497 };
dc9dc135 498 if let Some(hir::Node::Expr(hir::Expr {
dfeec247 499 kind: hir::ExprKind::Assign(left_expr, ..),
dc9dc135 500 ..
dfeec247
XL
501 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
502 {
503 if mutability == hir::Mutability::Mut {
dc9dc135
XL
504 // Found the following case:
505 // fn foo(opt: &mut Option<String>){ opt = None }
506 // --- ^^^^
507 // | |
508 // consider dereferencing here: `*opt` |
509 // expected mutable reference, found enum `Option`
74b04a01 510 if let Ok(src) = sm.span_to_snippet(left_expr.span) {
dc9dc135
XL
511 return Some((
512 left_expr.span,
513 "consider dereferencing here to assign to the mutable \
514 borrowed piece of memory",
515 format!("*{}", src),
f9f354fc 516 Applicability::MachineApplicable,
dc9dc135
XL
517 ));
518 }
519 }
520 }
521
94b46f34 522 return Some(match mutability {
dfeec247 523 hir::Mutability::Mut => (
532ac7d7
XL
524 sp,
525 "consider mutably borrowing here",
526 format!("{}&mut {}", field_name, sugg_expr),
f9f354fc 527 Applicability::MachineApplicable,
532ac7d7 528 ),
dfeec247 529 hir::Mutability::Not => (
532ac7d7
XL
530 sp,
531 "consider borrowing here",
532 format!("{}&{}", field_name, sugg_expr),
f9f354fc 533 Applicability::MachineApplicable,
532ac7d7 534 ),
ff7c6d11 535 });
cc61c64b
XL
536 }
537 }
dfeec247 538 }
60c5eb7d
XL
539 (
540 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
541 _,
dfeec247 542 &ty::Ref(_, checked, _),
60c5eb7d 543 ) if {
48663c56 544 self.infcx.can_sub(self.param_env, checked, &expected).is_ok() && !is_macro
dfeec247
XL
545 } =>
546 {
ea8adc8c 547 // We have `&T`, check if what was expected was `T`. If so,
48663c56 548 // we may want to suggest removing a `&`.
ba9703b0 549 if sm.is_imported(expr.span) {
f9f354fc 550 if let Ok(src) = sm.span_to_snippet(sp) {
fc512014 551 if let Some(src) = src.strip_prefix('&') {
48663c56
XL
552 return Some((
553 sp,
554 "consider removing the borrow",
fc512014 555 src.to_string(),
f9f354fc 556 Applicability::MachineApplicable,
48663c56 557 ));
2c00a5a8 558 }
ea8adc8c 559 }
48663c56 560 return None;
ea8adc8c 561 }
74b04a01 562 if let Ok(code) = sm.span_to_snippet(expr.span) {
f9f354fc
XL
563 return Some((
564 sp,
565 "consider removing the borrow",
566 code,
567 Applicability::MachineApplicable,
568 ));
569 }
570 }
571 (
572 _,
573 &ty::RawPtr(TypeAndMut { ty: ty_b, mutbl: mutbl_b }),
574 &ty::Ref(_, ty_a, mutbl_a),
575 ) => {
576 if let Some(steps) = self.deref_steps(ty_a, ty_b) {
577 // Only suggest valid if dereferencing needed.
578 if steps > 0 {
579 // The pointer type implements `Copy` trait so the suggestion is always valid.
580 if let Ok(src) = sm.span_to_snippet(sp) {
581 let derefs = &"*".repeat(steps);
582 if let Some((src, applicability)) = match mutbl_b {
583 hir::Mutability::Mut => {
584 let new_prefix = "&mut ".to_owned() + derefs;
585 match mutbl_a {
586 hir::Mutability::Mut => {
fc512014
XL
587 replace_prefix(&src, "&mut ", &new_prefix)
588 .map(|s| (s, Applicability::MachineApplicable))
f9f354fc
XL
589 }
590 hir::Mutability::Not => {
fc512014
XL
591 replace_prefix(&src, "&", &new_prefix)
592 .map(|s| (s, Applicability::Unspecified))
f9f354fc
XL
593 }
594 }
595 }
596 hir::Mutability::Not => {
597 let new_prefix = "&".to_owned() + derefs;
598 match mutbl_a {
599 hir::Mutability::Mut => {
fc512014
XL
600 replace_prefix(&src, "&mut ", &new_prefix)
601 .map(|s| (s, Applicability::MachineApplicable))
f9f354fc
XL
602 }
603 hir::Mutability::Not => {
fc512014
XL
604 replace_prefix(&src, "&", &new_prefix)
605 .map(|s| (s, Applicability::MachineApplicable))
f9f354fc
XL
606 }
607 }
608 }
609 } {
610 return Some((sp, "consider dereferencing", src, applicability));
611 }
612 }
613 }
9fa01778 614 }
dfeec247 615 }
48663c56 616 _ if sp == expr.span && !is_macro => {
f9f354fc
XL
617 if let Some(steps) = self.deref_steps(checked_ty, expected) {
618 if steps == 1 {
619 // For a suggestion to make sense, the type would need to be `Copy`.
620 if self.infcx.type_is_copy_modulo_regions(self.param_env, expected, sp) {
621 if let Ok(code) = sm.span_to_snippet(sp) {
622 let message = if checked_ty.is_region_ptr() {
623 "consider dereferencing the borrow"
624 } else {
625 "consider dereferencing the type"
626 };
627 let suggestion = if is_struct_pat_shorthand_field {
628 format!("{}: *{}", code, code)
629 } else {
630 format!("*{}", code)
631 };
632 return Some((
633 sp,
634 message,
635 suggestion,
636 Applicability::MachineApplicable,
637 ));
638 }
639 }
0bf4aa26
XL
640 }
641 }
642 }
0bf4aa26
XL
643 _ => {}
644 }
48663c56 645 None
0bf4aa26
XL
646 }
647
9fa01778
XL
648 pub fn check_for_cast(
649 &self,
60c5eb7d 650 err: &mut DiagnosticBuilder<'_>,
dfeec247 651 expr: &hir::Expr<'_>,
9fa01778
XL
652 checked_ty: Ty<'tcx>,
653 expected_ty: Ty<'tcx>,
f035d41b 654 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
9fa01778 655 ) -> bool {
ba9703b0 656 if self.tcx.sess.source_map().is_imported(expr.span) {
e1599b0c
XL
657 // Ignore if span is from within a macro.
658 return false;
659 }
2c00a5a8 660
f035d41b
XL
661 let src = if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
662 src
663 } else {
664 return false;
665 };
666
2c00a5a8
XL
667 // If casting this expression to a given numeric type would be appropriate in case of a type
668 // mismatch.
669 //
670 // We want to minimize the amount of casting operations that are suggested, as it can be a
671 // lossy operation with potentially bad side effects, so we only suggest when encountering
672 // an expression that indicates that the original type couldn't be directly changed.
673 //
674 // For now, don't suggest casting with `as`.
675 let can_cast = false;
676
f9f354fc
XL
677 let prefix = if let Some(hir::Node::Expr(hir::Expr {
678 kind: hir::ExprKind::Struct(_, fields, _),
679 ..
dfeec247
XL
680 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
681 {
9fa01778 682 // `expr` is a literal field for a struct, only suggest if appropriate
f9f354fc
XL
683 match (*fields)
684 .iter()
685 .find(|field| field.expr.hir_id == expr.hir_id && field.is_shorthand)
686 {
687 // This is a field literal
688 Some(field) => format!("{}: ", field.ident),
9fa01778 689 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
f9f354fc 690 None => return false,
9fa01778 691 }
f9f354fc
XL
692 } else {
693 String::new()
694 };
f035d41b 695
e74abb32 696 if let hir::ExprKind::Call(path, args) = &expr.kind {
dfeec247
XL
697 if let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
698 (&path.kind, args.len())
699 {
e1599b0c 700 // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
dfeec247
XL
701 if let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
702 (&base_ty.kind, path_segment.ident.name)
703 {
e1599b0c
XL
704 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
705 match ident.name {
dfeec247
XL
706 sym::i128
707 | sym::i64
708 | sym::i32
709 | sym::i16
710 | sym::i8
711 | sym::u128
712 | sym::u64
713 | sym::u32
714 | sym::u16
715 | sym::u8
716 | sym::isize
717 | sym::usize
718 if base_ty_path.segments.len() == 1 =>
719 {
e1599b0c
XL
720 return false;
721 }
722 _ => {}
723 }
724 }
725 }
726 }
727 }
9fa01778 728
29967ef6
XL
729 let msg = format!(
730 "you can convert {} `{}` to {} `{}`",
731 checked_ty.kind().article(),
732 checked_ty,
733 expected_ty.kind().article(),
734 expected_ty,
735 );
736 let cast_msg = format!(
737 "you can cast {} `{}` to {} `{}`",
738 checked_ty.kind().article(),
739 checked_ty,
740 expected_ty.kind().article(),
741 expected_ty,
742 );
48663c56
XL
743 let lit_msg = format!(
744 "change the type of the numeric literal from `{}` to `{}`",
dfeec247 745 checked_ty, expected_ty,
48663c56
XL
746 );
747
f035d41b
XL
748 let with_opt_paren: fn(&dyn fmt::Display) -> String =
749 if expr.precedence().order() < PREC_POSTFIX {
750 |s| format!("({})", s)
751 } else {
752 |s| s.to_string()
753 };
754
755 let cast_suggestion = format!("{}{} as {}", prefix, with_opt_paren(&src), expected_ty);
756 let into_suggestion = format!("{}{}.into()", prefix, with_opt_paren(&src));
757 let suffix_suggestion = with_opt_paren(&format_args!(
758 "{}{}",
759 if matches!(
1b1a35ee 760 (&expected_ty.kind(), &checked_ty.kind()),
f035d41b
XL
761 (ty::Int(_) | ty::Uint(_), ty::Float(_))
762 ) {
763 // Remove fractional part from literal, for example `42.0f32` into `42`
764 let src = src.trim_end_matches(&checked_ty.to_string());
765 src.split('.').next().unwrap()
766 } else {
767 src.trim_end_matches(&checked_ty.to_string())
768 },
769 expected_ty,
770 ));
771 let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
772 if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
773 };
774 let is_negative_int =
775 |expr: &hir::Expr<'_>| matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::UnNeg, ..));
1b1a35ee 776 let is_uint = |ty: Ty<'_>| matches!(ty.kind(), ty::Uint(..));
f035d41b
XL
777
778 let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
779
780 let suggest_fallible_into_or_lhs_from =
781 |err: &mut DiagnosticBuilder<'_>, exp_to_found_is_fallible: bool| {
782 // If we know the expression the expected type is derived from, we might be able
783 // to suggest a widening conversion rather than a narrowing one (which may
784 // panic). For example, given x: u8 and y: u32, if we know the span of "x",
785 // x > y
786 // can be given the suggestion "u32::from(x) > y" rather than
787 // "x > y.try_into().unwrap()".
788 let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
fc512014
XL
789 self.tcx
790 .sess
791 .source_map()
792 .span_to_snippet(expr.span)
793 .ok()
794 .map(|src| (expr, src))
f035d41b
XL
795 });
796 let (span, msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
797 (lhs_expr_and_src, exp_to_found_is_fallible)
dfeec247 798 {
f035d41b
XL
799 let msg = format!(
800 "you can convert `{}` from `{}` to `{}`, matching the type of `{}`",
801 lhs_src, expected_ty, checked_ty, src
802 );
803 let suggestion = format!("{}::from({})", checked_ty, lhs_src);
804 (lhs_expr.span, msg, suggestion)
48663c56 805 } else {
29967ef6 806 let msg = format!("{} and panic if the converted value doesn't fit", msg);
f035d41b
XL
807 let suggestion =
808 format!("{}{}.try_into().unwrap()", prefix, with_opt_paren(&src));
809 (expr.span, msg, suggestion)
810 };
811 err.span_suggestion(span, &msg, suggestion, Applicability::MachineApplicable);
812 };
813
814 let suggest_to_change_suffix_or_into =
815 |err: &mut DiagnosticBuilder<'_>,
816 found_to_exp_is_fallible: bool,
817 exp_to_found_is_fallible: bool| {
818 let always_fallible = found_to_exp_is_fallible
819 && (exp_to_found_is_fallible || expected_ty_expr.is_none());
820 let msg = if literal_is_ty_suffixed(expr) {
821 &lit_msg
822 } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
823 // We now know that converting either the lhs or rhs is fallible. Before we
824 // suggest a fallible conversion, check if the value can never fit in the
825 // expected type.
826 let msg = format!("`{}` cannot fit into type `{}`", src, expected_ty);
827 err.note(&msg);
828 return;
829 } else if in_const_context {
830 // Do not recommend `into` or `try_into` in const contexts.
831 return;
832 } else if found_to_exp_is_fallible {
833 return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
0bf4aa26 834 } else {
f035d41b
XL
835 &msg
836 };
837 let suggestion = if literal_is_ty_suffixed(expr) {
838 suffix_suggestion.clone()
839 } else {
840 into_suggestion.clone()
841 };
842 err.span_suggestion(expr.span, msg, suggestion, Applicability::MachineApplicable);
0bf4aa26
XL
843 };
844
1b1a35ee 845 match (&expected_ty.kind(), &checked_ty.kind()) {
f035d41b
XL
846 (&ty::Int(ref exp), &ty::Int(ref found)) => {
847 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
848 {
849 (Some(exp), Some(found)) if exp < found => (true, false),
850 (Some(exp), Some(found)) if exp > found => (false, true),
851 (None, Some(8 | 16)) => (false, true),
852 (Some(8 | 16), None) => (true, false),
853 (None, _) | (_, None) => (true, true),
854 _ => (false, false),
855 };
856 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
857 true
858 }
859 (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
860 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
861 {
862 (Some(exp), Some(found)) if exp < found => (true, false),
863 (Some(exp), Some(found)) if exp > found => (false, true),
864 (None, Some(8 | 16)) => (false, true),
865 (Some(8 | 16), None) => (true, false),
866 (None, _) | (_, None) => (true, true),
867 _ => (false, false),
868 };
869 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
870 true
871 }
872 (&ty::Int(exp), &ty::Uint(found)) => {
873 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
874 {
875 (Some(exp), Some(found)) if found < exp => (false, true),
876 (None, Some(8)) => (false, true),
877 _ => (true, true),
878 };
879 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
880 true
881 }
882 (&ty::Uint(exp), &ty::Int(found)) => {
883 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
884 {
885 (Some(exp), Some(found)) if found > exp => (true, false),
886 (Some(8), None) => (true, false),
887 _ => (true, true),
888 };
889 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
890 true
891 }
892 (&ty::Float(ref exp), &ty::Float(ref found)) => {
893 if found.bit_width() < exp.bit_width() {
894 suggest_to_change_suffix_or_into(err, false, true);
895 } else if literal_is_ty_suffixed(expr) {
dfeec247
XL
896 err.span_suggestion(
897 expr.span,
f035d41b
XL
898 &lit_msg,
899 suffix_suggestion,
dfeec247
XL
900 Applicability::MachineApplicable,
901 );
f035d41b
XL
902 } else if can_cast {
903 // Missing try_into implementation for `f64` to `f32`
904 err.span_suggestion(
905 expr.span,
906 &format!("{}, producing the closest possible value", cast_msg),
907 cast_suggestion,
908 Applicability::MaybeIncorrect, // lossy conversion
909 );
2c00a5a8 910 }
f035d41b
XL
911 true
912 }
913 (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
914 if literal_is_ty_suffixed(expr) {
915 err.span_suggestion(
916 expr.span,
917 &lit_msg,
918 suffix_suggestion,
919 Applicability::MachineApplicable,
920 );
921 } else if can_cast {
922 // Missing try_into implementation for `{float}` to `{integer}`
923 err.span_suggestion(
924 expr.span,
925 &format!("{}, rounding the float towards zero", msg),
926 cast_suggestion,
927 Applicability::MaybeIncorrect, // lossy conversion
928 );
2c00a5a8 929 }
f035d41b
XL
930 true
931 }
932 (&ty::Float(ref exp), &ty::Uint(ref found)) => {
933 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
934 if exp.bit_width() > found.bit_width().unwrap_or(256) {
935 err.span_suggestion(
936 expr.span,
937 &format!(
938 "{}, producing the floating point representation of the integer",
939 msg,
940 ),
941 into_suggestion,
942 Applicability::MachineApplicable,
943 );
944 } else if literal_is_ty_suffixed(expr) {
945 err.span_suggestion(
946 expr.span,
947 &lit_msg,
948 suffix_suggestion,
949 Applicability::MachineApplicable,
950 );
951 } else {
952 // Missing try_into implementation for `{integer}` to `{float}`
953 err.span_suggestion(
954 expr.span,
955 &format!(
956 "{}, producing the floating point representation of the integer,
48663c56 957 rounded if necessary",
f035d41b
XL
958 cast_msg,
959 ),
960 cast_suggestion,
961 Applicability::MaybeIncorrect, // lossy conversion
962 );
2c00a5a8 963 }
f035d41b
XL
964 true
965 }
966 (&ty::Float(ref exp), &ty::Int(ref found)) => {
967 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
968 if exp.bit_width() > found.bit_width().unwrap_or(256) {
969 err.span_suggestion(
970 expr.span,
971 &format!(
972 "{}, producing the floating point representation of the integer",
973 &msg,
974 ),
975 into_suggestion,
976 Applicability::MachineApplicable,
977 );
978 } else if literal_is_ty_suffixed(expr) {
979 err.span_suggestion(
980 expr.span,
981 &lit_msg,
982 suffix_suggestion,
983 Applicability::MachineApplicable,
984 );
985 } else {
986 // Missing try_into implementation for `{integer}` to `{float}`
987 err.span_suggestion(
988 expr.span,
989 &format!(
990 "{}, producing the floating point representation of the integer, \
991 rounded if necessary",
992 &msg,
993 ),
994 cast_suggestion,
995 Applicability::MaybeIncorrect, // lossy conversion
996 );
2c00a5a8 997 }
f035d41b 998 true
2c00a5a8 999 }
f035d41b 1000 _ => false,
2c00a5a8
XL
1001 }
1002 }
1a4d82fc 1003}