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