]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/demand.rs
Correctly parse `{} && false` in tail expression
[rust.git] / src / librustc_typeck / 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::CloneTraitLangItem;
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_boxing_when_appropriate(err, expr, expected, expr_ty);
36         self.suggest_missing_await(err, expr, expected, expr_ty);
37         self.suggest_missing_parentheses(err, expr);
38         self.note_need_for_fn_pointer(err, expected, expr_ty);
39     }
40
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>) {
44         if let Some(mut e) = self.demand_suptype_diag(sp, expected, actual) {
45             e.emit();
46         }
47     }
48
49     pub fn demand_suptype_diag(
50         &self,
51         sp: Span,
52         expected: Ty<'tcx>,
53         actual: Ty<'tcx>,
54     ) -> Option<DiagnosticBuilder<'tcx>> {
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>> {
64         match self.at(cause, self.param_env).sup(expected, actual) {
65             Ok(InferOk { obligations, value: () }) => {
66                 self.register_predicates(obligations);
67                 None
68             }
69             Err(e) => Some(self.report_mismatched_types(&cause, expected, actual, e)),
70         }
71     }
72
73     pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
74         if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
75             err.emit();
76         }
77     }
78
79     pub fn demand_eqtype_diag(
80         &self,
81         sp: Span,
82         expected: Ty<'tcx>,
83         actual: Ty<'tcx>,
84     ) -> Option<DiagnosticBuilder<'tcx>> {
85         self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
86     }
87
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>> {
94         match self.at(cause, self.param_env).eq(expected, actual) {
95             Ok(InferOk { obligations, value: () }) => {
96                 self.register_predicates(obligations);
97                 None
98             }
99             Err(e) => Some(self.report_mismatched_types(cause, expected, actual, e)),
100         }
101     }
102
103     pub fn demand_coerce(
104         &self,
105         expr: &hir::Expr<'_>,
106         checked_ty: Ty<'tcx>,
107         expected: Ty<'tcx>,
108         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
109         allow_two_phase: AllowTwoPhase,
110     ) -> Ty<'tcx> {
111         let (ty, err) =
112             self.demand_coerce_diag(expr, checked_ty, expected, expected_ty_expr, allow_two_phase);
113         if let Some(mut err) = err {
114             err.emit();
115         }
116         ty
117     }
118
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
122     // particular, assignments to `!` will be permitted if the
123     // 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| a.check_name(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<A, B, C>(&self, s: A, old: B, new: C) -> Option<String>
365     where
366         A: AsRef<str>,
367         B: AsRef<str>,
368         C: AsRef<str>,
369     {
370         let s = s.as_ref();
371         let old = old.as_ref();
372         if s.starts_with(old) { Some(new.as_ref().to_owned() + &s[old.len()..]) } else { None }
373     }
374
375     /// This function is used to determine potential "simple" improvements or users' errors and
376     /// provide them useful help. For example:
377     ///
378     /// ```
379     /// fn some_fn(s: &str) {}
380     ///
381     /// let x = "hey!".to_owned();
382     /// some_fn(x); // error
383     /// ```
384     ///
385     /// No need to find every potential function which could make a coercion to transform a
386     /// `String` into a `&str` since a `&` would do the trick!
387     ///
388     /// In addition of this check, it also checks between references mutability state. If the
389     /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
390     /// `&mut`!".
391     pub fn check_ref(
392         &self,
393         expr: &hir::Expr<'_>,
394         checked_ty: Ty<'tcx>,
395         expected: Ty<'tcx>,
396     ) -> Option<(Span, &'static str, String, Applicability)> {
397         let sm = self.sess().source_map();
398         let sp = expr.span;
399         if sm.is_imported(sp) {
400             // Ignore if span is from within a macro #41858, #58298. We previously used the macro
401             // call span, but that breaks down when the type error comes from multiple calls down.
402             return None;
403         }
404
405         let is_struct_pat_shorthand_field =
406             self.is_hir_id_from_struct_pattern_shorthand_field(expr.hir_id, sp);
407
408         // If the span is from a macro, then it's hard to extract the text
409         // and make a good suggestion, so don't bother.
410         let is_macro = sp.from_expansion() && sp.desugaring_kind().is_none();
411
412         // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
413         let expr = expr.peel_drop_temps();
414
415         match (&expr.kind, &expected.kind, &checked_ty.kind) {
416             (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (&exp.kind, &check.kind) {
417                 (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
418                     if let hir::ExprKind::Lit(_) = expr.kind {
419                         if let Ok(src) = sm.span_to_snippet(sp) {
420                             if let Some(src) = self.replace_prefix(src, "b\"", "\"") {
421                                 return Some((
422                                     sp,
423                                     "consider removing the leading `b`",
424                                     src,
425                                     Applicability::MachineApplicable,
426                                 ));
427                             }
428                         }
429                     }
430                 }
431                 (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
432                     if let hir::ExprKind::Lit(_) = expr.kind {
433                         if let Ok(src) = sm.span_to_snippet(sp) {
434                             if let Some(src) = self.replace_prefix(src, "\"", "b\"") {
435                                 return Some((
436                                     sp,
437                                     "consider adding a leading `b`",
438                                     src,
439                                     Applicability::MachineApplicable,
440                                 ));
441                             }
442                         }
443                     }
444                 }
445                 _ => {}
446             },
447             (_, &ty::Ref(_, _, mutability), _) => {
448                 // Check if it can work when put into a ref. For example:
449                 //
450                 // ```
451                 // fn bar(x: &mut i32) {}
452                 //
453                 // let x = 0u32;
454                 // bar(&x); // error, expected &mut
455                 // ```
456                 let ref_ty = match mutability {
457                     hir::Mutability::Mut => {
458                         self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
459                     }
460                     hir::Mutability::Not => {
461                         self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
462                     }
463                 };
464                 if self.can_coerce(ref_ty, expected) {
465                     let mut sugg_sp = sp;
466                     if let hir::ExprKind::MethodCall(ref segment, sp, ref args, _) = expr.kind {
467                         let clone_trait = self.tcx.require_lang_item(CloneTraitLangItem, Some(sp));
468                         if let ([arg], Some(true), sym::clone) = (
469                             &args[..],
470                             self.typeck_results.borrow().type_dependent_def_id(expr.hir_id).map(
471                                 |did| {
472                                     let ai = self.tcx.associated_item(did);
473                                     ai.container == ty::TraitContainer(clone_trait)
474                                 },
475                             ),
476                             segment.ident.name,
477                         ) {
478                             // If this expression had a clone call when suggesting borrowing
479                             // we want to suggest removing it because it'd now be unnecessary.
480                             sugg_sp = arg.span;
481                         }
482                     }
483                     if let Ok(src) = sm.span_to_snippet(sugg_sp) {
484                         let needs_parens = match expr.kind {
485                             // parenthesize if needed (Issue #46756)
486                             hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
487                             // parenthesize borrows of range literals (Issue #54505)
488                             _ if is_range_literal(self.tcx.sess.source_map(), expr) => true,
489                             _ => false,
490                         };
491                         let sugg_expr = if needs_parens { format!("({})", src) } else { src };
492
493                         if let Some(sugg) = self.can_use_as_ref(expr) {
494                             return Some((
495                                 sugg.0,
496                                 sugg.1,
497                                 sugg.2,
498                                 Applicability::MachineApplicable,
499                             ));
500                         }
501                         let field_name = if is_struct_pat_shorthand_field {
502                             format!("{}: ", sugg_expr)
503                         } else {
504                             String::new()
505                         };
506                         if let Some(hir::Node::Expr(hir::Expr {
507                             kind: hir::ExprKind::Assign(left_expr, ..),
508                             ..
509                         })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
510                         {
511                             if mutability == hir::Mutability::Mut {
512                                 // Found the following case:
513                                 // fn foo(opt: &mut Option<String>){ opt = None }
514                                 //                                   ---   ^^^^
515                                 //                                   |     |
516                                 //    consider dereferencing here: `*opt`  |
517                                 // expected mutable reference, found enum `Option`
518                                 if let Ok(src) = sm.span_to_snippet(left_expr.span) {
519                                     return Some((
520                                         left_expr.span,
521                                         "consider dereferencing here to assign to the mutable \
522                                          borrowed piece of memory",
523                                         format!("*{}", src),
524                                         Applicability::MachineApplicable,
525                                     ));
526                                 }
527                             }
528                         }
529
530                         return Some(match mutability {
531                             hir::Mutability::Mut => (
532                                 sp,
533                                 "consider mutably borrowing here",
534                                 format!("{}&mut {}", field_name, sugg_expr),
535                                 Applicability::MachineApplicable,
536                             ),
537                             hir::Mutability::Not => (
538                                 sp,
539                                 "consider borrowing here",
540                                 format!("{}&{}", field_name, sugg_expr),
541                                 Applicability::MachineApplicable,
542                             ),
543                         });
544                     }
545                 }
546             }
547             (
548                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
549                 _,
550                 &ty::Ref(_, checked, _),
551             ) if {
552                 self.infcx.can_sub(self.param_env, checked, &expected).is_ok() && !is_macro
553             } =>
554             {
555                 // We have `&T`, check if what was expected was `T`. If so,
556                 // we may want to suggest removing a `&`.
557                 if sm.is_imported(expr.span) {
558                     if let Ok(src) = sm.span_to_snippet(sp) {
559                         if let Some(src) = self.replace_prefix(src, "&", "") {
560                             return Some((
561                                 sp,
562                                 "consider removing the borrow",
563                                 src,
564                                 Applicability::MachineApplicable,
565                             ));
566                         }
567                     }
568                     return None;
569                 }
570                 if let Ok(code) = sm.span_to_snippet(expr.span) {
571                     return Some((
572                         sp,
573                         "consider removing the borrow",
574                         code,
575                         Applicability::MachineApplicable,
576                     ));
577                 }
578             }
579             (
580                 _,
581                 &ty::RawPtr(TypeAndMut { ty: ty_b, mutbl: mutbl_b }),
582                 &ty::Ref(_, ty_a, mutbl_a),
583             ) => {
584                 if let Some(steps) = self.deref_steps(ty_a, ty_b) {
585                     // Only suggest valid if dereferencing needed.
586                     if steps > 0 {
587                         // The pointer type implements `Copy` trait so the suggestion is always valid.
588                         if let Ok(src) = sm.span_to_snippet(sp) {
589                             let derefs = &"*".repeat(steps);
590                             if let Some((src, applicability)) = match mutbl_b {
591                                 hir::Mutability::Mut => {
592                                     let new_prefix = "&mut ".to_owned() + derefs;
593                                     match mutbl_a {
594                                         hir::Mutability::Mut => {
595                                             if let Some(s) =
596                                                 self.replace_prefix(src, "&mut ", new_prefix)
597                                             {
598                                                 Some((s, Applicability::MachineApplicable))
599                                             } else {
600                                                 None
601                                             }
602                                         }
603                                         hir::Mutability::Not => {
604                                             if let Some(s) =
605                                                 self.replace_prefix(src, "&", new_prefix)
606                                             {
607                                                 Some((s, Applicability::Unspecified))
608                                             } else {
609                                                 None
610                                             }
611                                         }
612                                     }
613                                 }
614                                 hir::Mutability::Not => {
615                                     let new_prefix = "&".to_owned() + derefs;
616                                     match mutbl_a {
617                                         hir::Mutability::Mut => {
618                                             if let Some(s) =
619                                                 self.replace_prefix(src, "&mut ", new_prefix)
620                                             {
621                                                 Some((s, Applicability::MachineApplicable))
622                                             } else {
623                                                 None
624                                             }
625                                         }
626                                         hir::Mutability::Not => {
627                                             if let Some(s) =
628                                                 self.replace_prefix(src, "&", new_prefix)
629                                             {
630                                                 Some((s, Applicability::MachineApplicable))
631                                             } else {
632                                                 None
633                                             }
634                                         }
635                                     }
636                                 }
637                             } {
638                                 return Some((sp, "consider dereferencing", src, applicability));
639                             }
640                         }
641                     }
642                 }
643             }
644             _ if sp == expr.span && !is_macro => {
645                 if let Some(steps) = self.deref_steps(checked_ty, expected) {
646                     if steps == 1 {
647                         // For a suggestion to make sense, the type would need to be `Copy`.
648                         if self.infcx.type_is_copy_modulo_regions(self.param_env, expected, sp) {
649                             if let Ok(code) = sm.span_to_snippet(sp) {
650                                 let message = if checked_ty.is_region_ptr() {
651                                     "consider dereferencing the borrow"
652                                 } else {
653                                     "consider dereferencing the type"
654                                 };
655                                 let suggestion = if is_struct_pat_shorthand_field {
656                                     format!("{}: *{}", code, code)
657                                 } else {
658                                     format!("*{}", code)
659                                 };
660                                 return Some((
661                                     sp,
662                                     message,
663                                     suggestion,
664                                     Applicability::MachineApplicable,
665                                 ));
666                             }
667                         }
668                     }
669                 }
670             }
671             _ => {}
672         }
673         None
674     }
675
676     pub fn check_for_cast(
677         &self,
678         err: &mut DiagnosticBuilder<'_>,
679         expr: &hir::Expr<'_>,
680         checked_ty: Ty<'tcx>,
681         expected_ty: Ty<'tcx>,
682         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
683     ) -> bool {
684         if self.tcx.sess.source_map().is_imported(expr.span) {
685             // Ignore if span is from within a macro.
686             return false;
687         }
688
689         let src = if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
690             src
691         } else {
692             return false;
693         };
694
695         // If casting this expression to a given numeric type would be appropriate in case of a type
696         // mismatch.
697         //
698         // We want to minimize the amount of casting operations that are suggested, as it can be a
699         // lossy operation with potentially bad side effects, so we only suggest when encountering
700         // an expression that indicates that the original type couldn't be directly changed.
701         //
702         // For now, don't suggest casting with `as`.
703         let can_cast = false;
704
705         let prefix = if let Some(hir::Node::Expr(hir::Expr {
706             kind: hir::ExprKind::Struct(_, fields, _),
707             ..
708         })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
709         {
710             // `expr` is a literal field for a struct, only suggest if appropriate
711             match (*fields)
712                 .iter()
713                 .find(|field| field.expr.hir_id == expr.hir_id && field.is_shorthand)
714             {
715                 // This is a field literal
716                 Some(field) => format!("{}: ", field.ident),
717                 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
718                 None => return false,
719             }
720         } else {
721             String::new()
722         };
723
724         if let hir::ExprKind::Call(path, args) = &expr.kind {
725             if let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
726                 (&path.kind, args.len())
727             {
728                 // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
729                 if let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
730                     (&base_ty.kind, path_segment.ident.name)
731                 {
732                     if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
733                         match ident.name {
734                             sym::i128
735                             | sym::i64
736                             | sym::i32
737                             | sym::i16
738                             | sym::i8
739                             | sym::u128
740                             | sym::u64
741                             | sym::u32
742                             | sym::u16
743                             | sym::u8
744                             | sym::isize
745                             | sym::usize
746                                 if base_ty_path.segments.len() == 1 =>
747                             {
748                                 return false;
749                             }
750                             _ => {}
751                         }
752                     }
753                 }
754             }
755         }
756
757         let msg = format!("you can convert an `{}` to `{}`", checked_ty, expected_ty);
758         let cast_msg = format!("you can cast an `{} to `{}`", checked_ty, expected_ty);
759         let lit_msg = format!(
760             "change the type of the numeric literal from `{}` to `{}`",
761             checked_ty, expected_ty,
762         );
763
764         let with_opt_paren: fn(&dyn fmt::Display) -> String =
765             if expr.precedence().order() < PREC_POSTFIX {
766                 |s| format!("({})", s)
767             } else {
768                 |s| s.to_string()
769             };
770
771         let cast_suggestion = format!("{}{} as {}", prefix, with_opt_paren(&src), expected_ty);
772         let into_suggestion = format!("{}{}.into()", prefix, with_opt_paren(&src));
773         let suffix_suggestion = with_opt_paren(&format_args!(
774             "{}{}",
775             if matches!(
776                 (&expected_ty.kind, &checked_ty.kind),
777                 (ty::Int(_) | ty::Uint(_), ty::Float(_))
778             ) {
779                 // Remove fractional part from literal, for example `42.0f32` into `42`
780                 let src = src.trim_end_matches(&checked_ty.to_string());
781                 src.split('.').next().unwrap()
782             } else {
783                 src.trim_end_matches(&checked_ty.to_string())
784             },
785             expected_ty,
786         ));
787         let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
788             if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
789         };
790         let is_negative_int =
791             |expr: &hir::Expr<'_>| matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::UnNeg, ..));
792         let is_uint = |ty: Ty<'_>| matches!(ty.kind, ty::Uint(..));
793
794         let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
795
796         let suggest_fallible_into_or_lhs_from =
797             |err: &mut DiagnosticBuilder<'_>, exp_to_found_is_fallible: bool| {
798                 // If we know the expression the expected type is derived from, we might be able
799                 // to suggest a widening conversion rather than a narrowing one (which may
800                 // panic). For example, given x: u8 and y: u32, if we know the span of "x",
801                 //   x > y
802                 // can be given the suggestion "u32::from(x) > y" rather than
803                 // "x > y.try_into().unwrap()".
804                 let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
805                     match self.tcx.sess.source_map().span_to_snippet(expr.span).ok() {
806                         Some(src) => Some((expr, src)),
807                         None => None,
808                     }
809                 });
810                 let (span, msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
811                     (lhs_expr_and_src, exp_to_found_is_fallible)
812                 {
813                     let msg = format!(
814                         "you can convert `{}` from `{}` to `{}`, matching the type of `{}`",
815                         lhs_src, expected_ty, checked_ty, src
816                     );
817                     let suggestion = format!("{}::from({})", checked_ty, lhs_src);
818                     (lhs_expr.span, msg, suggestion)
819                 } else {
820                     let msg = format!("{} and panic if the converted value wouldn't fit", msg);
821                     let suggestion =
822                         format!("{}{}.try_into().unwrap()", prefix, with_opt_paren(&src));
823                     (expr.span, msg, suggestion)
824                 };
825                 err.span_suggestion(span, &msg, suggestion, Applicability::MachineApplicable);
826             };
827
828         let suggest_to_change_suffix_or_into =
829             |err: &mut DiagnosticBuilder<'_>,
830              found_to_exp_is_fallible: bool,
831              exp_to_found_is_fallible: bool| {
832                 let always_fallible = found_to_exp_is_fallible
833                     && (exp_to_found_is_fallible || expected_ty_expr.is_none());
834                 let msg = if literal_is_ty_suffixed(expr) {
835                     &lit_msg
836                 } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
837                     // We now know that converting either the lhs or rhs is fallible. Before we
838                     // suggest a fallible conversion, check if the value can never fit in the
839                     // expected type.
840                     let msg = format!("`{}` cannot fit into type `{}`", src, expected_ty);
841                     err.note(&msg);
842                     return;
843                 } else if in_const_context {
844                     // Do not recommend `into` or `try_into` in const contexts.
845                     return;
846                 } else if found_to_exp_is_fallible {
847                     return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
848                 } else {
849                     &msg
850                 };
851                 let suggestion = if literal_is_ty_suffixed(expr) {
852                     suffix_suggestion.clone()
853                 } else {
854                     into_suggestion.clone()
855                 };
856                 err.span_suggestion(expr.span, msg, suggestion, Applicability::MachineApplicable);
857             };
858
859         match (&expected_ty.kind, &checked_ty.kind) {
860             (&ty::Int(ref exp), &ty::Int(ref found)) => {
861                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
862                 {
863                     (Some(exp), Some(found)) if exp < found => (true, false),
864                     (Some(exp), Some(found)) if exp > found => (false, true),
865                     (None, Some(8 | 16)) => (false, true),
866                     (Some(8 | 16), None) => (true, false),
867                     (None, _) | (_, None) => (true, true),
868                     _ => (false, false),
869                 };
870                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
871                 true
872             }
873             (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
874                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
875                 {
876                     (Some(exp), Some(found)) if exp < found => (true, false),
877                     (Some(exp), Some(found)) if exp > found => (false, true),
878                     (None, Some(8 | 16)) => (false, true),
879                     (Some(8 | 16), None) => (true, false),
880                     (None, _) | (_, None) => (true, true),
881                     _ => (false, false),
882                 };
883                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
884                 true
885             }
886             (&ty::Int(exp), &ty::Uint(found)) => {
887                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
888                 {
889                     (Some(exp), Some(found)) if found < exp => (false, true),
890                     (None, Some(8)) => (false, true),
891                     _ => (true, true),
892                 };
893                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
894                 true
895             }
896             (&ty::Uint(exp), &ty::Int(found)) => {
897                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
898                 {
899                     (Some(exp), Some(found)) if found > exp => (true, false),
900                     (Some(8), None) => (true, false),
901                     _ => (true, true),
902                 };
903                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
904                 true
905             }
906             (&ty::Float(ref exp), &ty::Float(ref found)) => {
907                 if found.bit_width() < exp.bit_width() {
908                     suggest_to_change_suffix_or_into(err, false, true);
909                 } else if literal_is_ty_suffixed(expr) {
910                     err.span_suggestion(
911                         expr.span,
912                         &lit_msg,
913                         suffix_suggestion,
914                         Applicability::MachineApplicable,
915                     );
916                 } else if can_cast {
917                     // Missing try_into implementation for `f64` to `f32`
918                     err.span_suggestion(
919                         expr.span,
920                         &format!("{}, producing the closest possible value", cast_msg),
921                         cast_suggestion,
922                         Applicability::MaybeIncorrect, // lossy conversion
923                     );
924                 }
925                 true
926             }
927             (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
928                 if literal_is_ty_suffixed(expr) {
929                     err.span_suggestion(
930                         expr.span,
931                         &lit_msg,
932                         suffix_suggestion,
933                         Applicability::MachineApplicable,
934                     );
935                 } else if can_cast {
936                     // Missing try_into implementation for `{float}` to `{integer}`
937                     err.span_suggestion(
938                         expr.span,
939                         &format!("{}, rounding the float towards zero", msg),
940                         cast_suggestion,
941                         Applicability::MaybeIncorrect, // lossy conversion
942                     );
943                 }
944                 true
945             }
946             (&ty::Float(ref exp), &ty::Uint(ref found)) => {
947                 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
948                 if exp.bit_width() > found.bit_width().unwrap_or(256) {
949                     err.span_suggestion(
950                         expr.span,
951                         &format!(
952                             "{}, producing the floating point representation of the integer",
953                             msg,
954                         ),
955                         into_suggestion,
956                         Applicability::MachineApplicable,
957                     );
958                 } else if literal_is_ty_suffixed(expr) {
959                     err.span_suggestion(
960                         expr.span,
961                         &lit_msg,
962                         suffix_suggestion,
963                         Applicability::MachineApplicable,
964                     );
965                 } else {
966                     // Missing try_into implementation for `{integer}` to `{float}`
967                     err.span_suggestion(
968                         expr.span,
969                         &format!(
970                             "{}, producing the floating point representation of the integer,
971                                  rounded if necessary",
972                             cast_msg,
973                         ),
974                         cast_suggestion,
975                         Applicability::MaybeIncorrect, // lossy conversion
976                     );
977                 }
978                 true
979             }
980             (&ty::Float(ref exp), &ty::Int(ref found)) => {
981                 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
982                 if exp.bit_width() > found.bit_width().unwrap_or(256) {
983                     err.span_suggestion(
984                         expr.span,
985                         &format!(
986                             "{}, producing the floating point representation of the integer",
987                             &msg,
988                         ),
989                         into_suggestion,
990                         Applicability::MachineApplicable,
991                     );
992                 } else if literal_is_ty_suffixed(expr) {
993                     err.span_suggestion(
994                         expr.span,
995                         &lit_msg,
996                         suffix_suggestion,
997                         Applicability::MachineApplicable,
998                     );
999                 } else {
1000                     // Missing try_into implementation for `{integer}` to `{float}`
1001                     err.span_suggestion(
1002                         expr.span,
1003                         &format!(
1004                             "{}, producing the floating point representation of the integer, \
1005                                 rounded if necessary",
1006                             &msg,
1007                         ),
1008                         cast_suggestion,
1009                         Applicability::MaybeIncorrect, // lossy conversion
1010                     );
1011                 }
1012                 true
1013             }
1014             _ => false,
1015         }
1016     }
1017 }