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