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