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