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