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