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