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