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