]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/demand.rs
Auto merge of #73210 - wesleywiser:consts_in_debuginfo, r=oli-obk
[rust.git] / compiler / rustc_typeck / src / 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::ObligationCause;
5
6 use rustc_ast::util::parser::PREC_POSTFIX;
7 use rustc_errors::{Applicability, DiagnosticBuilder};
8 use rustc_hir as hir;
9 use rustc_hir::lang_items::LangItem;
10 use rustc_hir::{is_range_literal, Node};
11 use rustc_middle::ty::adjustment::AllowTwoPhase;
12 use rustc_middle::ty::{self, AssocItem, Ty, TypeAndMut};
13 use rustc_span::symbol::sym;
14 use rustc_span::Span;
15
16 use super::method::probe;
17
18 use std::fmt;
19
20 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
21     pub fn emit_coerce_suggestions(
22         &self,
23         err: &mut DiagnosticBuilder<'_>,
24         expr: &hir::Expr<'_>,
25         expr_ty: Ty<'tcx>,
26         expected: Ty<'tcx>,
27         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
28     ) {
29         self.annotate_expected_due_to_let_ty(err, expr);
30         self.suggest_compatible_variants(err, expr, expected, expr_ty);
31         self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr);
32         if self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty) {
33             return;
34         }
35         self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty);
36         self.suggest_missing_parentheses(err, expr);
37         self.note_need_for_fn_pointer(err, expected, expr_ty);
38         self.note_internal_mutation_in_method(err, expr, expected, expr_ty);
39     }
40
41     // Requires that the two types unify, and prints an error message if
42     // they don't.
43     pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
44         if let Some(mut e) = self.demand_suptype_diag(sp, expected, actual) {
45             e.emit();
46         }
47     }
48
49     pub fn demand_suptype_diag(
50         &self,
51         sp: Span,
52         expected: Ty<'tcx>,
53         actual: Ty<'tcx>,
54     ) -> Option<DiagnosticBuilder<'tcx>> {
55         self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
56     }
57
58     pub fn demand_suptype_with_origin(
59         &self,
60         cause: &ObligationCause<'tcx>,
61         expected: Ty<'tcx>,
62         actual: Ty<'tcx>,
63     ) -> Option<DiagnosticBuilder<'tcx>> {
64         match self.at(cause, self.param_env).sup(expected, actual) {
65             Ok(InferOk { obligations, value: () }) => {
66                 self.register_predicates(obligations);
67                 None
68             }
69             Err(e) => Some(self.report_mismatched_types(&cause, expected, actual, e)),
70         }
71     }
72
73     pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
74         if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
75             err.emit();
76         }
77     }
78
79     pub fn demand_eqtype_diag(
80         &self,
81         sp: Span,
82         expected: Ty<'tcx>,
83         actual: Ty<'tcx>,
84     ) -> Option<DiagnosticBuilder<'tcx>> {
85         self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
86     }
87
88     pub fn demand_eqtype_with_origin(
89         &self,
90         cause: &ObligationCause<'tcx>,
91         expected: Ty<'tcx>,
92         actual: Ty<'tcx>,
93     ) -> Option<DiagnosticBuilder<'tcx>> {
94         match self.at(cause, self.param_env).eq(expected, actual) {
95             Ok(InferOk { obligations, value: () }) => {
96                 self.register_predicates(obligations);
97                 None
98             }
99             Err(e) => Some(self.report_mismatched_types(cause, expected, actual, e)),
100         }
101     }
102
103     pub fn demand_coerce(
104         &self,
105         expr: &hir::Expr<'_>,
106         checked_ty: Ty<'tcx>,
107         expected: Ty<'tcx>,
108         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
109         allow_two_phase: AllowTwoPhase,
110     ) -> Ty<'tcx> {
111         let (ty, err) =
112             self.demand_coerce_diag(expr, checked_ty, expected, expected_ty_expr, allow_two_phase);
113         if let Some(mut err) = err {
114             err.emit();
115         }
116         ty
117     }
118
119     /// Checks that the type of `expr` can be coerced to `expected`.
120     ///
121     /// N.B., this code relies on `self.diverges` to be accurate. In particular, assignments to `!`
122     /// will be permitted if the diverges flag is currently "always".
123     pub fn demand_coerce_diag(
124         &self,
125         expr: &hir::Expr<'_>,
126         checked_ty: Ty<'tcx>,
127         expected: Ty<'tcx>,
128         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
129         allow_two_phase: AllowTwoPhase,
130     ) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx>>) {
131         let expected = self.resolve_vars_with_obligations(expected);
132
133         let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase) {
134             Ok(ty) => return (ty, None),
135             Err(e) => e,
136         };
137
138         let expr = expr.peel_drop_temps();
139         let cause = self.misc(expr.span);
140         let expr_ty = self.resolve_vars_with_obligations(checked_ty);
141         let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
142
143         if self.is_assign_to_bool(expr, expected) {
144             // Error reported in `check_assign` so avoid emitting error again.
145             err.delay_as_bug();
146             return (expected, None);
147         }
148
149         self.emit_coerce_suggestions(&mut err, expr, expr_ty, expected, expected_ty_expr);
150
151         (expected, Some(err))
152     }
153
154     fn annotate_expected_due_to_let_ty(
155         &self,
156         err: &mut DiagnosticBuilder<'_>,
157         expr: &hir::Expr<'_>,
158     ) {
159         let parent = self.tcx.hir().get_parent_node(expr.hir_id);
160         if let Some(hir::Node::Local(hir::Local { ty: Some(ty), init: Some(init), .. })) =
161             self.tcx.hir().find(parent)
162         {
163             if init.hir_id == expr.hir_id {
164                 // Point at `let` assignment type.
165                 err.span_label(ty.span, "expected due to this");
166             }
167         }
168     }
169
170     /// Returns whether the expected type is `bool` and the expression is `x = y`.
171     pub fn is_assign_to_bool(&self, expr: &hir::Expr<'_>, expected: Ty<'tcx>) -> bool {
172         if let hir::ExprKind::Assign(..) = expr.kind {
173             return expected == self.tcx.types.bool;
174         }
175         false
176     }
177
178     /// If the expected type is an enum (Issue #55250) with any variants whose
179     /// sole field is of the found type, suggest such variants. (Issue #42764)
180     fn suggest_compatible_variants(
181         &self,
182         err: &mut DiagnosticBuilder<'_>,
183         expr: &hir::Expr<'_>,
184         expected: Ty<'tcx>,
185         expr_ty: Ty<'tcx>,
186     ) {
187         if let ty::Adt(expected_adt, substs) = expected.kind() {
188             if !expected_adt.is_enum() {
189                 return;
190             }
191
192             let mut compatible_variants = expected_adt
193                 .variants
194                 .iter()
195                 .filter(|variant| variant.fields.len() == 1)
196                 .filter_map(|variant| {
197                     let sole_field = &variant.fields[0];
198                     let sole_field_ty = sole_field.ty(self.tcx, substs);
199                     if self.can_coerce(expr_ty, sole_field_ty) {
200                         let variant_path = self.tcx.def_path_str(variant.def_id);
201                         // FIXME #56861: DRYer prelude filtering
202                         Some(variant_path.trim_start_matches("std::prelude::v1::").to_string())
203                     } else {
204                         None
205                     }
206                 })
207                 .peekable();
208
209             if compatible_variants.peek().is_some() {
210                 if let Ok(expr_text) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
211                     let suggestions = compatible_variants.map(|v| format!("{}({})", v, expr_text));
212                     let msg = "try using a variant of the expected enum";
213                     err.span_suggestions(
214                         expr.span,
215                         msg,
216                         suggestions,
217                         Applicability::MaybeIncorrect,
218                     );
219                 }
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         hir_id: hir::HirId,
230     ) -> Vec<AssocItem> {
231         let mut methods =
232             self.probe_for_return_type(span, probe::Mode::MethodCall, expected, checked_ty, hir_id);
233         methods.retain(|m| {
234             self.has_only_self_parameter(m)
235                 && self
236                     .tcx
237                     .get_attrs(m.def_id)
238                     .iter()
239                     // This special internal attribute is used to permit
240                     // "identity-like" conversion methods to be suggested here.
241                     //
242                     // FIXME (#46459 and #46460): ideally
243                     // `std::convert::Into::into` and `std::borrow:ToOwned` would
244                     // also be `#[rustc_conversion_suggestion]`, if not for
245                     // method-probing false-positives and -negatives (respectively).
246                     //
247                     // FIXME? Other potential candidate methods: `as_ref` and
248                     // `as_mut`?
249                     .any(|a| self.sess().check_name(a, sym::rustc_conversion_suggestion))
250         });
251
252         methods
253     }
254
255     /// This function checks whether the method is not static and does not accept other parameters than `self`.
256     fn has_only_self_parameter(&self, method: &AssocItem) -> bool {
257         match method.kind {
258             ty::AssocKind::Fn => {
259                 method.fn_has_self_parameter
260                     && self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
261             }
262             _ => false,
263         }
264     }
265
266     /// Identify some cases where `as_ref()` would be appropriate and suggest it.
267     ///
268     /// Given the following code:
269     /// ```
270     /// struct Foo;
271     /// fn takes_ref(_: &Foo) {}
272     /// let ref opt = Some(Foo);
273     ///
274     /// opt.map(|param| takes_ref(param));
275     /// ```
276     /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
277     ///
278     /// It only checks for `Option` and `Result` and won't work with
279     /// ```
280     /// opt.map(|param| { takes_ref(param) });
281     /// ```
282     fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Span, &'static str, String)> {
283         let path = match expr.kind {
284             hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => path,
285             _ => return None,
286         };
287
288         let local_id = match path.res {
289             hir::def::Res::Local(id) => id,
290             _ => return None,
291         };
292
293         let local_parent = self.tcx.hir().get_parent_node(local_id);
294         let param_hir_id = match self.tcx.hir().find(local_parent) {
295             Some(Node::Param(hir::Param { hir_id, .. })) => hir_id,
296             _ => return None,
297         };
298
299         let param_parent = self.tcx.hir().get_parent_node(*param_hir_id);
300         let (expr_hir_id, closure_fn_decl) = match self.tcx.hir().find(param_parent) {
301             Some(Node::Expr(hir::Expr {
302                 hir_id,
303                 kind: hir::ExprKind::Closure(_, decl, ..),
304                 ..
305             })) => (hir_id, decl),
306             _ => return None,
307         };
308
309         let expr_parent = self.tcx.hir().get_parent_node(*expr_hir_id);
310         let hir = self.tcx.hir().find(expr_parent);
311         let closure_params_len = closure_fn_decl.inputs.len();
312         let (method_path, method_span, method_expr) = match (hir, closure_params_len) {
313             (
314                 Some(Node::Expr(hir::Expr {
315                     kind: hir::ExprKind::MethodCall(path, span, expr, _),
316                     ..
317                 })),
318                 1,
319             ) => (path, span, expr),
320             _ => return None,
321         };
322
323         let self_ty = self.typeck_results.borrow().node_type(method_expr[0].hir_id);
324         let self_ty = format!("{:?}", self_ty);
325         let name = method_path.ident.name;
326         let is_as_ref_able = (self_ty.starts_with("&std::option::Option")
327             || self_ty.starts_with("&std::result::Result")
328             || self_ty.starts_with("std::option::Option")
329             || self_ty.starts_with("std::result::Result"))
330             && (name == sym::map || name == sym::and_then);
331         match (is_as_ref_able, self.sess().source_map().span_to_snippet(*method_span)) {
332             (true, Ok(src)) => {
333                 let suggestion = format!("as_ref().{}", src);
334                 Some((*method_span, "consider using `as_ref` instead", suggestion))
335             }
336             _ => None,
337         }
338     }
339
340     crate fn is_hir_id_from_struct_pattern_shorthand_field(
341         &self,
342         hir_id: hir::HirId,
343         sp: Span,
344     ) -> bool {
345         let sm = self.sess().source_map();
346         let parent_id = self.tcx.hir().get_parent_node(hir_id);
347         if let Some(parent) = self.tcx.hir().find(parent_id) {
348             // Account for fields
349             if let Node::Expr(hir::Expr { kind: hir::ExprKind::Struct(_, fields, ..), .. }) = parent
350             {
351                 if let Ok(src) = sm.span_to_snippet(sp) {
352                     for field in *fields {
353                         if field.ident.as_str() == src && field.is_shorthand {
354                             return true;
355                         }
356                     }
357                 }
358             }
359         }
360         false
361     }
362
363     fn replace_prefix(&self, s: &str, old: &str, new: &str) -> Option<String> {
364         s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
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, Applicability)> {
389         let sm = self.sess().source_map();
390         let sp = expr.span;
391         if sm.is_imported(sp) {
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::Slice(arr)) if arr == self.tcx.types.u8 => {
410                     if let hir::ExprKind::Lit(_) = expr.kind {
411                         if let Ok(src) = sm.span_to_snippet(sp) {
412                             if let Some(src) = self.replace_prefix(&src, "b\"", "\"") {
413                                 return Some((
414                                     sp,
415                                     "consider removing the leading `b`",
416                                     src,
417                                     Applicability::MachineApplicable,
418                                 ));
419                             }
420                         }
421                     }
422                 }
423                 (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
424                     if let hir::ExprKind::Lit(_) = expr.kind {
425                         if let Ok(src) = sm.span_to_snippet(sp) {
426                             if let Some(src) = self.replace_prefix(&src, "\"", "b\"") {
427                                 return Some((
428                                     sp,
429                                     "consider adding a leading `b`",
430                                     src,
431                                     Applicability::MachineApplicable,
432                                 ));
433                             }
434                         }
435                     }
436                 }
437                 _ => {}
438             },
439             (_, &ty::Ref(_, _, mutability), _) => {
440                 // Check if it can work when put into a ref. For example:
441                 //
442                 // ```
443                 // fn bar(x: &mut i32) {}
444                 //
445                 // let x = 0u32;
446                 // bar(&x); // error, expected &mut
447                 // ```
448                 let ref_ty = match mutability {
449                     hir::Mutability::Mut => {
450                         self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
451                     }
452                     hir::Mutability::Not => {
453                         self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
454                     }
455                 };
456                 if self.can_coerce(ref_ty, expected) {
457                     let mut sugg_sp = sp;
458                     if let hir::ExprKind::MethodCall(ref segment, sp, ref args, _) = expr.kind {
459                         let clone_trait = self.tcx.require_lang_item(LangItem::Clone, Some(sp));
460                         if let ([arg], Some(true), sym::clone) = (
461                             &args[..],
462                             self.typeck_results.borrow().type_dependent_def_id(expr.hir_id).map(
463                                 |did| {
464                                     let ai = self.tcx.associated_item(did);
465                                     ai.container == ty::TraitContainer(clone_trait)
466                                 },
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) = sm.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(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((
487                                 sugg.0,
488                                 sugg.1,
489                                 sugg.2,
490                                 Applicability::MachineApplicable,
491                             ));
492                         }
493                         let field_name = if is_struct_pat_shorthand_field {
494                             format!("{}: ", sugg_expr)
495                         } else {
496                             String::new()
497                         };
498                         if let Some(hir::Node::Expr(hir::Expr {
499                             kind: hir::ExprKind::Assign(left_expr, ..),
500                             ..
501                         })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
502                         {
503                             if mutability == hir::Mutability::Mut {
504                                 // Found the following case:
505                                 // fn foo(opt: &mut Option<String>){ opt = None }
506                                 //                                   ---   ^^^^
507                                 //                                   |     |
508                                 //    consider dereferencing here: `*opt`  |
509                                 // expected mutable reference, found enum `Option`
510                                 if let Ok(src) = sm.span_to_snippet(left_expr.span) {
511                                     return Some((
512                                         left_expr.span,
513                                         "consider dereferencing here to assign to the mutable \
514                                          borrowed piece of memory",
515                                         format!("*{}", src),
516                                         Applicability::MachineApplicable,
517                                     ));
518                                 }
519                             }
520                         }
521
522                         return Some(match mutability {
523                             hir::Mutability::Mut => (
524                                 sp,
525                                 "consider mutably borrowing here",
526                                 format!("{}&mut {}", field_name, sugg_expr),
527                                 Applicability::MachineApplicable,
528                             ),
529                             hir::Mutability::Not => (
530                                 sp,
531                                 "consider borrowing here",
532                                 format!("{}&{}", field_name, sugg_expr),
533                                 Applicability::MachineApplicable,
534                             ),
535                         });
536                     }
537                 }
538             }
539             (
540                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
541                 _,
542                 &ty::Ref(_, checked, _),
543             ) if {
544                 self.infcx.can_sub(self.param_env, checked, &expected).is_ok() && !is_macro
545             } =>
546             {
547                 // We have `&T`, check if what was expected was `T`. If so,
548                 // we may want to suggest removing a `&`.
549                 if sm.is_imported(expr.span) {
550                     if let Ok(src) = sm.span_to_snippet(sp) {
551                         if let Some(src) = src.strip_prefix('&') {
552                             return Some((
553                                 sp,
554                                 "consider removing the borrow",
555                                 src.to_string(),
556                                 Applicability::MachineApplicable,
557                             ));
558                         }
559                     }
560                     return None;
561                 }
562                 if let Ok(code) = sm.span_to_snippet(expr.span) {
563                     return Some((
564                         sp,
565                         "consider removing the borrow",
566                         code,
567                         Applicability::MachineApplicable,
568                     ));
569                 }
570             }
571             (
572                 _,
573                 &ty::RawPtr(TypeAndMut { ty: ty_b, mutbl: mutbl_b }),
574                 &ty::Ref(_, ty_a, mutbl_a),
575             ) => {
576                 if let Some(steps) = self.deref_steps(ty_a, ty_b) {
577                     // Only suggest valid if dereferencing needed.
578                     if steps > 0 {
579                         // The pointer type implements `Copy` trait so the suggestion is always valid.
580                         if let Ok(src) = sm.span_to_snippet(sp) {
581                             let derefs = &"*".repeat(steps);
582                             if let Some((src, applicability)) = match mutbl_b {
583                                 hir::Mutability::Mut => {
584                                     let new_prefix = "&mut ".to_owned() + derefs;
585                                     match mutbl_a {
586                                         hir::Mutability::Mut => self
587                                             .replace_prefix(&src, "&mut ", &new_prefix)
588                                             .map(|s| (s, Applicability::MachineApplicable)),
589                                         hir::Mutability::Not => self
590                                             .replace_prefix(&src, "&", &new_prefix)
591                                             .map(|s| (s, Applicability::Unspecified)),
592                                     }
593                                 }
594                                 hir::Mutability::Not => {
595                                     let new_prefix = "&".to_owned() + derefs;
596                                     match mutbl_a {
597                                         hir::Mutability::Mut => self
598                                             .replace_prefix(&src, "&mut ", &new_prefix)
599                                             .map(|s| (s, Applicability::MachineApplicable)),
600                                         hir::Mutability::Not => self
601                                             .replace_prefix(&src, "&", &new_prefix)
602                                             .map(|s| (s, Applicability::MachineApplicable)),
603                                     }
604                                 }
605                             } {
606                                 return Some((sp, "consider dereferencing", src, applicability));
607                             }
608                         }
609                     }
610                 }
611             }
612             _ if sp == expr.span && !is_macro => {
613                 if let Some(steps) = self.deref_steps(checked_ty, expected) {
614                     if steps == 1 {
615                         // For a suggestion to make sense, the type would need to be `Copy`.
616                         if self.infcx.type_is_copy_modulo_regions(self.param_env, expected, sp) {
617                             if let Ok(code) = sm.span_to_snippet(sp) {
618                                 let message = if checked_ty.is_region_ptr() {
619                                     "consider dereferencing the borrow"
620                                 } else {
621                                     "consider dereferencing the type"
622                                 };
623                                 let suggestion = if is_struct_pat_shorthand_field {
624                                     format!("{}: *{}", code, code)
625                                 } else {
626                                     format!("*{}", code)
627                                 };
628                                 return Some((
629                                     sp,
630                                     message,
631                                     suggestion,
632                                     Applicability::MachineApplicable,
633                                 ));
634                             }
635                         }
636                     }
637                 }
638             }
639             _ => {}
640         }
641         None
642     }
643
644     pub fn check_for_cast(
645         &self,
646         err: &mut DiagnosticBuilder<'_>,
647         expr: &hir::Expr<'_>,
648         checked_ty: Ty<'tcx>,
649         expected_ty: Ty<'tcx>,
650         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
651     ) -> bool {
652         if self.tcx.sess.source_map().is_imported(expr.span) {
653             // Ignore if span is from within a macro.
654             return false;
655         }
656
657         let src = if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
658             src
659         } else {
660             return false;
661         };
662
663         // If casting this expression to a given numeric type would be appropriate in case of a type
664         // mismatch.
665         //
666         // We want to minimize the amount of casting operations that are suggested, as it can be a
667         // lossy operation with potentially bad side effects, so we only suggest when encountering
668         // an expression that indicates that the original type couldn't be directly changed.
669         //
670         // For now, don't suggest casting with `as`.
671         let can_cast = false;
672
673         let prefix = if let Some(hir::Node::Expr(hir::Expr {
674             kind: hir::ExprKind::Struct(_, fields, _),
675             ..
676         })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
677         {
678             // `expr` is a literal field for a struct, only suggest if appropriate
679             match (*fields)
680                 .iter()
681                 .find(|field| field.expr.hir_id == expr.hir_id && field.is_shorthand)
682             {
683                 // This is a field literal
684                 Some(field) => format!("{}: ", field.ident),
685                 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
686                 None => return false,
687             }
688         } else {
689             String::new()
690         };
691
692         if let hir::ExprKind::Call(path, args) = &expr.kind {
693             if let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
694                 (&path.kind, args.len())
695             {
696                 // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
697                 if let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
698                     (&base_ty.kind, path_segment.ident.name)
699                 {
700                     if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
701                         match ident.name {
702                             sym::i128
703                             | sym::i64
704                             | sym::i32
705                             | sym::i16
706                             | sym::i8
707                             | sym::u128
708                             | sym::u64
709                             | sym::u32
710                             | sym::u16
711                             | sym::u8
712                             | sym::isize
713                             | sym::usize
714                                 if base_ty_path.segments.len() == 1 =>
715                             {
716                                 return false;
717                             }
718                             _ => {}
719                         }
720                     }
721                 }
722             }
723         }
724
725         let msg = format!(
726             "you can convert {} `{}` to {} `{}`",
727             checked_ty.kind().article(),
728             checked_ty,
729             expected_ty.kind().article(),
730             expected_ty,
731         );
732         let cast_msg = format!(
733             "you can cast {} `{}` to {} `{}`",
734             checked_ty.kind().article(),
735             checked_ty,
736             expected_ty.kind().article(),
737             expected_ty,
738         );
739         let lit_msg = format!(
740             "change the type of the numeric literal from `{}` to `{}`",
741             checked_ty, expected_ty,
742         );
743
744         let with_opt_paren: fn(&dyn fmt::Display) -> String =
745             if expr.precedence().order() < PREC_POSTFIX {
746                 |s| format!("({})", s)
747             } else {
748                 |s| s.to_string()
749             };
750
751         let cast_suggestion = format!("{}{} as {}", prefix, with_opt_paren(&src), expected_ty);
752         let into_suggestion = format!("{}{}.into()", prefix, with_opt_paren(&src));
753         let suffix_suggestion = with_opt_paren(&format_args!(
754             "{}{}",
755             if matches!(
756                 (&expected_ty.kind(), &checked_ty.kind()),
757                 (ty::Int(_) | ty::Uint(_), ty::Float(_))
758             ) {
759                 // Remove fractional part from literal, for example `42.0f32` into `42`
760                 let src = src.trim_end_matches(&checked_ty.to_string());
761                 src.split('.').next().unwrap()
762             } else {
763                 src.trim_end_matches(&checked_ty.to_string())
764             },
765             expected_ty,
766         ));
767         let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
768             if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
769         };
770         let is_negative_int =
771             |expr: &hir::Expr<'_>| matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::UnNeg, ..));
772         let is_uint = |ty: Ty<'_>| matches!(ty.kind(), ty::Uint(..));
773
774         let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
775
776         let suggest_fallible_into_or_lhs_from =
777             |err: &mut DiagnosticBuilder<'_>, exp_to_found_is_fallible: bool| {
778                 // If we know the expression the expected type is derived from, we might be able
779                 // to suggest a widening conversion rather than a narrowing one (which may
780                 // panic). For example, given x: u8 and y: u32, if we know the span of "x",
781                 //   x > y
782                 // can be given the suggestion "u32::from(x) > y" rather than
783                 // "x > y.try_into().unwrap()".
784                 let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
785                     self.tcx
786                         .sess
787                         .source_map()
788                         .span_to_snippet(expr.span)
789                         .ok()
790                         .map(|src| (expr, src))
791                 });
792                 let (span, msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
793                     (lhs_expr_and_src, exp_to_found_is_fallible)
794                 {
795                     let msg = format!(
796                         "you can convert `{}` from `{}` to `{}`, matching the type of `{}`",
797                         lhs_src, expected_ty, checked_ty, src
798                     );
799                     let suggestion = format!("{}::from({})", checked_ty, lhs_src);
800                     (lhs_expr.span, msg, suggestion)
801                 } else {
802                     let msg = format!("{} and panic if the converted value doesn't fit", msg);
803                     let suggestion =
804                         format!("{}{}.try_into().unwrap()", prefix, with_opt_paren(&src));
805                     (expr.span, msg, suggestion)
806                 };
807                 err.span_suggestion(span, &msg, suggestion, Applicability::MachineApplicable);
808             };
809
810         let suggest_to_change_suffix_or_into =
811             |err: &mut DiagnosticBuilder<'_>,
812              found_to_exp_is_fallible: bool,
813              exp_to_found_is_fallible: bool| {
814                 let always_fallible = found_to_exp_is_fallible
815                     && (exp_to_found_is_fallible || expected_ty_expr.is_none());
816                 let msg = if literal_is_ty_suffixed(expr) {
817                     &lit_msg
818                 } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
819                     // We now know that converting either the lhs or rhs is fallible. Before we
820                     // suggest a fallible conversion, check if the value can never fit in the
821                     // expected type.
822                     let msg = format!("`{}` cannot fit into type `{}`", src, expected_ty);
823                     err.note(&msg);
824                     return;
825                 } else if in_const_context {
826                     // Do not recommend `into` or `try_into` in const contexts.
827                     return;
828                 } else if found_to_exp_is_fallible {
829                     return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
830                 } else {
831                     &msg
832                 };
833                 let suggestion = if literal_is_ty_suffixed(expr) {
834                     suffix_suggestion.clone()
835                 } else {
836                     into_suggestion.clone()
837                 };
838                 err.span_suggestion(expr.span, msg, suggestion, Applicability::MachineApplicable);
839             };
840
841         match (&expected_ty.kind(), &checked_ty.kind()) {
842             (&ty::Int(ref exp), &ty::Int(ref found)) => {
843                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
844                 {
845                     (Some(exp), Some(found)) if exp < found => (true, false),
846                     (Some(exp), Some(found)) if exp > found => (false, true),
847                     (None, Some(8 | 16)) => (false, true),
848                     (Some(8 | 16), None) => (true, false),
849                     (None, _) | (_, None) => (true, true),
850                     _ => (false, false),
851                 };
852                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
853                 true
854             }
855             (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
856                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
857                 {
858                     (Some(exp), Some(found)) if exp < found => (true, false),
859                     (Some(exp), Some(found)) if exp > found => (false, true),
860                     (None, Some(8 | 16)) => (false, true),
861                     (Some(8 | 16), None) => (true, false),
862                     (None, _) | (_, None) => (true, true),
863                     _ => (false, false),
864                 };
865                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
866                 true
867             }
868             (&ty::Int(exp), &ty::Uint(found)) => {
869                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
870                 {
871                     (Some(exp), Some(found)) if found < exp => (false, true),
872                     (None, Some(8)) => (false, true),
873                     _ => (true, true),
874                 };
875                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
876                 true
877             }
878             (&ty::Uint(exp), &ty::Int(found)) => {
879                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
880                 {
881                     (Some(exp), Some(found)) if found > exp => (true, false),
882                     (Some(8), None) => (true, false),
883                     _ => (true, true),
884                 };
885                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
886                 true
887             }
888             (&ty::Float(ref exp), &ty::Float(ref found)) => {
889                 if found.bit_width() < exp.bit_width() {
890                     suggest_to_change_suffix_or_into(err, false, true);
891                 } else if literal_is_ty_suffixed(expr) {
892                     err.span_suggestion(
893                         expr.span,
894                         &lit_msg,
895                         suffix_suggestion,
896                         Applicability::MachineApplicable,
897                     );
898                 } else if can_cast {
899                     // Missing try_into implementation for `f64` to `f32`
900                     err.span_suggestion(
901                         expr.span,
902                         &format!("{}, producing the closest possible value", cast_msg),
903                         cast_suggestion,
904                         Applicability::MaybeIncorrect, // lossy conversion
905                     );
906                 }
907                 true
908             }
909             (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
910                 if literal_is_ty_suffixed(expr) {
911                     err.span_suggestion(
912                         expr.span,
913                         &lit_msg,
914                         suffix_suggestion,
915                         Applicability::MachineApplicable,
916                     );
917                 } else if can_cast {
918                     // Missing try_into implementation for `{float}` to `{integer}`
919                     err.span_suggestion(
920                         expr.span,
921                         &format!("{}, rounding the float towards zero", msg),
922                         cast_suggestion,
923                         Applicability::MaybeIncorrect, // lossy conversion
924                     );
925                 }
926                 true
927             }
928             (&ty::Float(ref exp), &ty::Uint(ref found)) => {
929                 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
930                 if exp.bit_width() > found.bit_width().unwrap_or(256) {
931                     err.span_suggestion(
932                         expr.span,
933                         &format!(
934                             "{}, producing the floating point representation of the integer",
935                             msg,
936                         ),
937                         into_suggestion,
938                         Applicability::MachineApplicable,
939                     );
940                 } else if literal_is_ty_suffixed(expr) {
941                     err.span_suggestion(
942                         expr.span,
943                         &lit_msg,
944                         suffix_suggestion,
945                         Applicability::MachineApplicable,
946                     );
947                 } else {
948                     // Missing try_into implementation for `{integer}` to `{float}`
949                     err.span_suggestion(
950                         expr.span,
951                         &format!(
952                             "{}, producing the floating point representation of the integer,
953                                  rounded if necessary",
954                             cast_msg,
955                         ),
956                         cast_suggestion,
957                         Applicability::MaybeIncorrect, // lossy conversion
958                     );
959                 }
960                 true
961             }
962             (&ty::Float(ref exp), &ty::Int(ref found)) => {
963                 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
964                 if exp.bit_width() > found.bit_width().unwrap_or(256) {
965                     err.span_suggestion(
966                         expr.span,
967                         &format!(
968                             "{}, producing the floating point representation of the integer",
969                             &msg,
970                         ),
971                         into_suggestion,
972                         Applicability::MachineApplicable,
973                     );
974                 } else if literal_is_ty_suffixed(expr) {
975                     err.span_suggestion(
976                         expr.span,
977                         &lit_msg,
978                         suffix_suggestion,
979                         Applicability::MachineApplicable,
980                     );
981                 } else {
982                     // Missing try_into implementation for `{integer}` to `{float}`
983                     err.span_suggestion(
984                         expr.span,
985                         &format!(
986                             "{}, producing the floating point representation of the integer, \
987                                 rounded if necessary",
988                             &msg,
989                         ),
990                         cast_suggestion,
991                         Applicability::MaybeIncorrect, // lossy conversion
992                     );
993                 }
994                 true
995             }
996             _ => false,
997         }
998     }
999 }