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