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