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