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