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