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