]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/demand.rs
Auto merge of #106195 - Nilstrieb:no-more-being-clueless-whether-it-really-is-a-liter...
[rust.git] / compiler / rustc_hir_typeck / src / demand.rs
1 use crate::FnCtxt;
2 use rustc_ast::util::parser::PREC_POSTFIX;
3 use rustc_errors::MultiSpan;
4 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
5 use rustc_hir as hir;
6 use rustc_hir::def::CtorKind;
7 use rustc_hir::lang_items::LangItem;
8 use rustc_hir::{is_range_literal, Node};
9 use rustc_infer::infer::InferOk;
10 use rustc_middle::lint::in_external_macro;
11 use rustc_middle::middle::stability::EvalResult;
12 use rustc_middle::ty::adjustment::AllowTwoPhase;
13 use rustc_middle::ty::error::{ExpectedFound, TypeError};
14 use rustc_middle::ty::print::with_no_trimmed_paths;
15 use rustc_middle::ty::{self, Article, AssocItem, Ty, TypeAndMut};
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_span::{BytePos, Span};
18 use rustc_trait_selection::infer::InferCtxtExt as _;
19 use rustc_trait_selection::traits::ObligationCause;
20
21 use super::method::probe;
22
23 use std::cmp::min;
24 use std::iter;
25
26 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
27     pub fn emit_type_mismatch_suggestions(
28         &self,
29         err: &mut Diagnostic,
30         expr: &hir::Expr<'tcx>,
31         expr_ty: Ty<'tcx>,
32         expected: Ty<'tcx>,
33         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
34         error: Option<TypeError<'tcx>>,
35     ) {
36         if expr_ty == expected {
37             return;
38         }
39
40         self.annotate_alternative_method_deref(err, expr, error);
41
42         // Use `||` to give these suggestions a precedence
43         let _ = self.suggest_missing_parentheses(err, expr)
44             || self.suggest_remove_last_method_call(err, expr, expected)
45             || self.suggest_associated_const(err, expr, expected)
46             || self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr)
47             || self.suggest_option_to_bool(err, expr, expr_ty, expected)
48             || self.suggest_compatible_variants(err, expr, expected, expr_ty)
49             || self.suggest_non_zero_new_unwrap(err, expr, expected, expr_ty)
50             || self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty)
51             || self.suggest_no_capture_closure(err, expected, expr_ty)
52             || self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty)
53             || self.suggest_block_to_brackets_peeling_refs(err, expr, expr_ty, expected)
54             || self.suggest_copied_or_cloned(err, expr, expr_ty, expected)
55             || self.suggest_into(err, expr, expr_ty, expected)
56             || self.suggest_floating_point_literal(err, expr, expected);
57     }
58
59     pub fn emit_coerce_suggestions(
60         &self,
61         err: &mut Diagnostic,
62         expr: &hir::Expr<'tcx>,
63         expr_ty: Ty<'tcx>,
64         expected: Ty<'tcx>,
65         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
66         error: Option<TypeError<'tcx>>,
67     ) {
68         if expr_ty == expected {
69             return;
70         }
71
72         self.annotate_expected_due_to_let_ty(err, expr, error);
73         self.emit_type_mismatch_suggestions(err, expr, expr_ty, expected, expected_ty_expr, error);
74         self.note_type_is_not_clone(err, expected, expr_ty, expr);
75         self.note_need_for_fn_pointer(err, expected, expr_ty);
76         self.note_internal_mutation_in_method(err, expr, expected, expr_ty);
77         self.check_for_range_as_method_call(err, expr, expr_ty, expected);
78     }
79
80     /// Requires that the two types unify, and prints an error message if
81     /// they don't.
82     pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
83         if let Some(mut e) = self.demand_suptype_diag(sp, expected, actual) {
84             e.emit();
85         }
86     }
87
88     pub fn demand_suptype_diag(
89         &self,
90         sp: Span,
91         expected: Ty<'tcx>,
92         actual: Ty<'tcx>,
93     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
94         self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
95     }
96
97     #[instrument(skip(self), level = "debug")]
98     pub fn demand_suptype_with_origin(
99         &self,
100         cause: &ObligationCause<'tcx>,
101         expected: Ty<'tcx>,
102         actual: Ty<'tcx>,
103     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
104         match self.at(cause, self.param_env).sup(expected, actual) {
105             Ok(InferOk { obligations, value: () }) => {
106                 self.register_predicates(obligations);
107                 None
108             }
109             Err(e) => Some(self.err_ctxt().report_mismatched_types(&cause, expected, actual, e)),
110         }
111     }
112
113     pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
114         if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
115             err.emit();
116         }
117     }
118
119     pub fn demand_eqtype_diag(
120         &self,
121         sp: Span,
122         expected: Ty<'tcx>,
123         actual: Ty<'tcx>,
124     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
125         self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
126     }
127
128     pub fn demand_eqtype_with_origin(
129         &self,
130         cause: &ObligationCause<'tcx>,
131         expected: Ty<'tcx>,
132         actual: Ty<'tcx>,
133     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
134         match self.at(cause, self.param_env).eq(expected, actual) {
135             Ok(InferOk { obligations, value: () }) => {
136                 self.register_predicates(obligations);
137                 None
138             }
139             Err(e) => Some(self.err_ctxt().report_mismatched_types(cause, expected, actual, e)),
140         }
141     }
142
143     pub fn demand_coerce(
144         &self,
145         expr: &hir::Expr<'tcx>,
146         checked_ty: Ty<'tcx>,
147         expected: Ty<'tcx>,
148         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
149         allow_two_phase: AllowTwoPhase,
150     ) -> Ty<'tcx> {
151         let (ty, err) =
152             self.demand_coerce_diag(expr, checked_ty, expected, expected_ty_expr, allow_two_phase);
153         if let Some(mut err) = err {
154             err.emit();
155         }
156         ty
157     }
158
159     /// Checks that the type of `expr` can be coerced to `expected`.
160     ///
161     /// N.B., this code relies on `self.diverges` to be accurate. In particular, assignments to `!`
162     /// will be permitted if the diverges flag is currently "always".
163     #[instrument(level = "debug", skip(self, expr, expected_ty_expr, allow_two_phase))]
164     pub fn demand_coerce_diag(
165         &self,
166         expr: &hir::Expr<'tcx>,
167         checked_ty: Ty<'tcx>,
168         expected: Ty<'tcx>,
169         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
170         allow_two_phase: AllowTwoPhase,
171     ) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>) {
172         let expected = self.resolve_vars_with_obligations(expected);
173
174         let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase, None) {
175             Ok(ty) => return (ty, None),
176             Err(e) => e,
177         };
178
179         self.set_tainted_by_errors(self.tcx.sess.delay_span_bug(
180             expr.span,
181             "`TypeError` when attempting coercion but no error emitted",
182         ));
183         let expr = expr.peel_drop_temps();
184         let cause = self.misc(expr.span);
185         let expr_ty = self.resolve_vars_with_obligations(checked_ty);
186         let mut err = self.err_ctxt().report_mismatched_types(&cause, expected, expr_ty, e);
187
188         let is_insufficiently_polymorphic =
189             matches!(e, TypeError::RegionsInsufficientlyPolymorphic(..));
190
191         // FIXME(#73154): For now, we do leak check when coercing function
192         // pointers in typeck, instead of only during borrowck. This can lead
193         // to these `RegionsInsufficientlyPolymorphic` errors that aren't helpful.
194         if !is_insufficiently_polymorphic {
195             self.emit_coerce_suggestions(
196                 &mut err,
197                 expr,
198                 expr_ty,
199                 expected,
200                 expected_ty_expr,
201                 Some(e),
202             );
203         }
204
205         (expected, Some(err))
206     }
207
208     fn annotate_expected_due_to_let_ty(
209         &self,
210         err: &mut Diagnostic,
211         expr: &hir::Expr<'_>,
212         error: Option<TypeError<'tcx>>,
213     ) {
214         let parent = self.tcx.hir().get_parent_node(expr.hir_id);
215         match (self.tcx.hir().find(parent), error) {
216             (Some(hir::Node::Local(hir::Local { ty: Some(ty), init: Some(init), .. })), _)
217                 if init.hir_id == expr.hir_id =>
218             {
219                 // Point at `let` assignment type.
220                 err.span_label(ty.span, "expected due to this");
221             }
222             (
223                 Some(hir::Node::Expr(hir::Expr {
224                     kind: hir::ExprKind::Assign(lhs, rhs, _), ..
225                 })),
226                 Some(TypeError::Sorts(ExpectedFound { expected, .. })),
227             ) if rhs.hir_id == expr.hir_id && !expected.is_closure() => {
228                 // We ignore closures explicitly because we already point at them elsewhere.
229                 // Point at the assigned-to binding.
230                 let mut primary_span = lhs.span;
231                 let mut secondary_span = lhs.span;
232                 let mut post_message = "";
233                 match lhs.kind {
234                     hir::ExprKind::Path(hir::QPath::Resolved(
235                         None,
236                         hir::Path {
237                             res:
238                                 hir::def::Res::Def(
239                                     hir::def::DefKind::Static(_) | hir::def::DefKind::Const,
240                                     def_id,
241                                 ),
242                             ..
243                         },
244                     )) => {
245                         if let Some(hir::Node::Item(hir::Item {
246                             ident,
247                             kind: hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..),
248                             ..
249                         })) = self.tcx.hir().get_if_local(*def_id)
250                         {
251                             primary_span = ty.span;
252                             secondary_span = ident.span;
253                             post_message = " type";
254                         }
255                     }
256                     hir::ExprKind::Path(hir::QPath::Resolved(
257                         None,
258                         hir::Path { res: hir::def::Res::Local(hir_id), .. },
259                     )) => {
260                         if let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(*hir_id) {
261                             let parent = self.tcx.hir().get_parent_node(pat.hir_id);
262                             primary_span = pat.span;
263                             secondary_span = pat.span;
264                             match self.tcx.hir().find(parent) {
265                                 Some(hir::Node::Local(hir::Local { ty: Some(ty), .. })) => {
266                                     primary_span = ty.span;
267                                     post_message = " type";
268                                 }
269                                 Some(hir::Node::Local(hir::Local { init: Some(init), .. })) => {
270                                     primary_span = init.span;
271                                     post_message = " value";
272                                 }
273                                 Some(hir::Node::Param(hir::Param { ty_span, .. })) => {
274                                     primary_span = *ty_span;
275                                     post_message = " parameter type";
276                                 }
277                                 _ => {}
278                             }
279                         }
280                     }
281                     _ => {}
282                 }
283
284                 if primary_span != secondary_span
285                     && self
286                         .tcx
287                         .sess
288                         .source_map()
289                         .is_multiline(secondary_span.shrink_to_hi().until(primary_span))
290                 {
291                     // We are pointing at the binding's type or initializer value, but it's pattern
292                     // is in a different line, so we point at both.
293                     err.span_label(secondary_span, "expected due to the type of this binding");
294                     err.span_label(primary_span, &format!("expected due to this{post_message}"));
295                 } else if post_message == "" {
296                     // We are pointing at either the assignment lhs or the binding def pattern.
297                     err.span_label(primary_span, "expected due to the type of this binding");
298                 } else {
299                     // We are pointing at the binding's type or initializer value.
300                     err.span_label(primary_span, &format!("expected due to this{post_message}"));
301                 }
302
303                 if !lhs.is_syntactic_place_expr() {
304                     // We already emitted E0070 "invalid left-hand side of assignment", so we
305                     // silence this.
306                     err.downgrade_to_delayed_bug();
307                 }
308             }
309             (
310                 Some(hir::Node::Expr(hir::Expr {
311                     kind: hir::ExprKind::Binary(_, lhs, rhs), ..
312                 })),
313                 Some(TypeError::Sorts(ExpectedFound { expected, .. })),
314             ) if rhs.hir_id == expr.hir_id
315                 && self.typeck_results.borrow().expr_ty_adjusted_opt(lhs) == Some(expected) =>
316             {
317                 err.span_label(lhs.span, &format!("expected because this is `{expected}`"));
318             }
319             _ => {}
320         }
321     }
322
323     fn annotate_alternative_method_deref(
324         &self,
325         err: &mut Diagnostic,
326         expr: &hir::Expr<'_>,
327         error: Option<TypeError<'tcx>>,
328     ) {
329         let parent = self.tcx.hir().get_parent_node(expr.hir_id);
330         let Some(TypeError::Sorts(ExpectedFound { expected, .. })) = error else {return;};
331         let Some(hir::Node::Expr(hir::Expr {
332                     kind: hir::ExprKind::Assign(lhs, rhs, _), ..
333                 })) = self.tcx.hir().find(parent) else {return; };
334         if rhs.hir_id != expr.hir_id || expected.is_closure() {
335             return;
336         }
337         let hir::ExprKind::Unary(hir::UnOp::Deref, deref) = lhs.kind else { return; };
338         let hir::ExprKind::MethodCall(path, base, args, _) = deref.kind else { return; };
339         let Some(self_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(base) else { return; };
340
341         let Ok(pick) = self
342             .probe_for_name(
343                 probe::Mode::MethodCall,
344                 path.ident,
345                 probe::IsSuggestion(true),
346                 self_ty,
347                 deref.hir_id,
348                 probe::ProbeScope::TraitsInScope,
349             ) else {
350                 return;
351             };
352         let in_scope_methods = self.probe_for_name_many(
353             probe::Mode::MethodCall,
354             path.ident,
355             probe::IsSuggestion(true),
356             self_ty,
357             deref.hir_id,
358             probe::ProbeScope::TraitsInScope,
359         );
360         let other_methods_in_scope: Vec<_> =
361             in_scope_methods.iter().filter(|c| c.item.def_id != pick.item.def_id).collect();
362
363         let all_methods = self.probe_for_name_many(
364             probe::Mode::MethodCall,
365             path.ident,
366             probe::IsSuggestion(true),
367             self_ty,
368             deref.hir_id,
369             probe::ProbeScope::AllTraits,
370         );
371         let suggestions: Vec<_> = all_methods
372             .into_iter()
373             .filter(|c| c.item.def_id != pick.item.def_id)
374             .map(|c| {
375                 let m = c.item;
376                 let substs = ty::InternalSubsts::for_item(self.tcx, m.def_id, |param, _| {
377                     self.var_for_def(deref.span, param)
378                 });
379                 vec![
380                     (
381                         deref.span.until(base.span),
382                         format!(
383                             "{}({}",
384                             with_no_trimmed_paths!(
385                                 self.tcx.def_path_str_with_substs(m.def_id, substs,)
386                             ),
387                             match self.tcx.fn_sig(m.def_id).input(0).skip_binder().kind() {
388                                 ty::Ref(_, _, hir::Mutability::Mut) => "&mut ",
389                                 ty::Ref(_, _, _) => "&",
390                                 _ => "",
391                             },
392                         ),
393                     ),
394                     match &args[..] {
395                         [] => (base.span.shrink_to_hi().with_hi(deref.span.hi()), ")".to_string()),
396                         [first, ..] => (base.span.between(first.span), ", ".to_string()),
397                     },
398                 ]
399             })
400             .collect();
401         if suggestions.is_empty() {
402             return;
403         }
404         let mut path_span: MultiSpan = path.ident.span.into();
405         path_span.push_span_label(
406             path.ident.span,
407             with_no_trimmed_paths!(format!(
408                 "refers to `{}`",
409                 self.tcx.def_path_str(pick.item.def_id),
410             )),
411         );
412         let container_id = pick.item.container_id(self.tcx);
413         let container = with_no_trimmed_paths!(self.tcx.def_path_str(container_id));
414         for def_id in pick.import_ids {
415             let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
416             path_span.push_span_label(
417                 self.tcx.hir().span(hir_id),
418                 format!("`{container}` imported here"),
419             );
420         }
421         let tail = with_no_trimmed_paths!(match &other_methods_in_scope[..] {
422             [] => return,
423             [candidate] => format!(
424                 "the method of the same name on {} `{}`",
425                 match candidate.kind {
426                     probe::CandidateKind::InherentImplCandidate(..) => "the inherent impl for",
427                     _ => "trait",
428                 },
429                 self.tcx.def_path_str(candidate.item.container_id(self.tcx))
430             ),
431             [.., last] if other_methods_in_scope.len() < 5 => {
432                 format!(
433                     "the methods of the same name on {} and `{}`",
434                     other_methods_in_scope[..other_methods_in_scope.len() - 1]
435                         .iter()
436                         .map(|c| format!(
437                             "`{}`",
438                             self.tcx.def_path_str(c.item.container_id(self.tcx))
439                         ))
440                         .collect::<Vec<String>>()
441                         .join(", "),
442                     self.tcx.def_path_str(last.item.container_id(self.tcx))
443                 )
444             }
445             _ => format!(
446                 "the methods of the same name on {} other traits",
447                 other_methods_in_scope.len()
448             ),
449         });
450         err.span_note(
451             path_span,
452             &format!(
453                 "the `{}` call is resolved to the method in `{container}`, shadowing {tail}",
454                 path.ident,
455             ),
456         );
457         if suggestions.len() > other_methods_in_scope.len() {
458             err.note(&format!(
459                 "additionally, there are {} other available methods that aren't in scope",
460                 suggestions.len() - other_methods_in_scope.len()
461             ));
462         }
463         err.multipart_suggestions(
464             &format!(
465                 "you might have meant to call {}; you can use the fully-qualified path to call {} \
466                  explicitly",
467                 if suggestions.len() == 1 {
468                     "the other method"
469                 } else {
470                     "one of the other methods"
471                 },
472                 if suggestions.len() == 1 { "it" } else { "one of them" },
473             ),
474             suggestions,
475             Applicability::MaybeIncorrect,
476         );
477     }
478
479     /// If the expected type is an enum (Issue #55250) with any variants whose
480     /// sole field is of the found type, suggest such variants. (Issue #42764)
481     fn suggest_compatible_variants(
482         &self,
483         err: &mut Diagnostic,
484         expr: &hir::Expr<'_>,
485         expected: Ty<'tcx>,
486         expr_ty: Ty<'tcx>,
487     ) -> bool {
488         if let ty::Adt(expected_adt, substs) = expected.kind() {
489             if let hir::ExprKind::Field(base, ident) = expr.kind {
490                 let base_ty = self.typeck_results.borrow().expr_ty(base);
491                 if self.can_eq(self.param_env, base_ty, expected).is_ok()
492                     && let Some(base_span) = base.span.find_ancestor_inside(expr.span)
493                 {
494                     err.span_suggestion_verbose(
495                         expr.span.with_lo(base_span.hi()),
496                         format!("consider removing the tuple struct field `{ident}`"),
497                         "",
498                         Applicability::MaybeIncorrect,
499                     );
500                     return true;
501                 }
502             }
503
504             // If the expression is of type () and it's the return expression of a block,
505             // we suggest adding a separate return expression instead.
506             // (To avoid things like suggesting `Ok(while .. { .. })`.)
507             if expr_ty.is_unit() {
508                 let mut id = expr.hir_id;
509                 let mut parent;
510
511                 // Unroll desugaring, to make sure this works for `for` loops etc.
512                 loop {
513                     parent = self.tcx.hir().get_parent_node(id);
514                     if let Some(parent_span) = self.tcx.hir().opt_span(parent) {
515                         if parent_span.find_ancestor_inside(expr.span).is_some() {
516                             // The parent node is part of the same span, so is the result of the
517                             // same expansion/desugaring and not the 'real' parent node.
518                             id = parent;
519                             continue;
520                         }
521                     }
522                     break;
523                 }
524
525                 if let Some(hir::Node::Block(&hir::Block {
526                     span: block_span, expr: Some(e), ..
527                 })) = self.tcx.hir().find(parent)
528                 {
529                     if e.hir_id == id {
530                         if let Some(span) = expr.span.find_ancestor_inside(block_span) {
531                             let return_suggestions = if self
532                                 .tcx
533                                 .is_diagnostic_item(sym::Result, expected_adt.did())
534                             {
535                                 vec!["Ok(())"]
536                             } else if self.tcx.is_diagnostic_item(sym::Option, expected_adt.did()) {
537                                 vec!["None", "Some(())"]
538                             } else {
539                                 return false;
540                             };
541                             if let Some(indent) =
542                                 self.tcx.sess.source_map().indentation_before(span.shrink_to_lo())
543                             {
544                                 // Add a semicolon, except after `}`.
545                                 let semicolon =
546                                     match self.tcx.sess.source_map().span_to_snippet(span) {
547                                         Ok(s) if s.ends_with('}') => "",
548                                         _ => ";",
549                                     };
550                                 err.span_suggestions(
551                                     span.shrink_to_hi(),
552                                     "try adding an expression at the end of the block",
553                                     return_suggestions
554                                         .into_iter()
555                                         .map(|r| format!("{semicolon}\n{indent}{r}")),
556                                     Applicability::MaybeIncorrect,
557                                 );
558                             }
559                             return true;
560                         }
561                     }
562                 }
563             }
564
565             let compatible_variants: Vec<(String, _, _, Option<String>)> = expected_adt
566                 .variants()
567                 .iter()
568                 .filter(|variant| {
569                     variant.fields.len() == 1
570                 })
571                 .filter_map(|variant| {
572                     let sole_field = &variant.fields[0];
573
574                     let field_is_local = sole_field.did.is_local();
575                     let field_is_accessible =
576                         sole_field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
577                         // Skip suggestions for unstable public fields (for example `Pin::pointer`)
578                         && matches!(self.tcx.eval_stability(sole_field.did, None, expr.span, None), EvalResult::Allow | EvalResult::Unmarked);
579
580                     if !field_is_local && !field_is_accessible {
581                         return None;
582                     }
583
584                     let note_about_variant_field_privacy = (field_is_local && !field_is_accessible)
585                         .then(|| " (its field is private, but it's local to this crate and its privacy can be changed)".to_string());
586
587                     let sole_field_ty = sole_field.ty(self.tcx, substs);
588                     if self.can_coerce(expr_ty, sole_field_ty) {
589                         let variant_path =
590                             with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
591                         // FIXME #56861: DRYer prelude filtering
592                         if let Some(path) = variant_path.strip_prefix("std::prelude::")
593                             && let Some((_, path)) = path.split_once("::")
594                         {
595                             return Some((path.to_string(), variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy));
596                         }
597                         Some((variant_path, variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy))
598                     } else {
599                         None
600                     }
601                 })
602                 .collect();
603
604             let suggestions_for = |variant: &_, ctor_kind, field_name| {
605                 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
606                     Some(ident) => format!("{ident}: "),
607                     None => String::new(),
608                 };
609
610                 let (open, close) = match ctor_kind {
611                     Some(CtorKind::Fn) => ("(".to_owned(), ")"),
612                     None => (format!(" {{ {field_name}: "), " }"),
613
614                     // unit variants don't have fields
615                     Some(CtorKind::Const) => unreachable!(),
616                 };
617
618                 // Suggest constructor as deep into the block tree as possible.
619                 // This fixes https://github.com/rust-lang/rust/issues/101065,
620                 // and also just helps make the most minimal suggestions.
621                 let mut expr = expr;
622                 while let hir::ExprKind::Block(block, _) = &expr.kind
623                     && let Some(expr_) = &block.expr
624                 {
625                     expr = expr_
626                 }
627
628                 vec![
629                     (expr.span.shrink_to_lo(), format!("{prefix}{variant}{open}")),
630                     (expr.span.shrink_to_hi(), close.to_owned()),
631                 ]
632             };
633
634             match &compatible_variants[..] {
635                 [] => { /* No variants to format */ }
636                 [(variant, ctor_kind, field_name, note)] => {
637                     // Just a single matching variant.
638                     err.multipart_suggestion_verbose(
639                         &format!(
640                             "try wrapping the expression in `{variant}`{note}",
641                             note = note.as_deref().unwrap_or("")
642                         ),
643                         suggestions_for(&**variant, *ctor_kind, *field_name),
644                         Applicability::MaybeIncorrect,
645                     );
646                     return true;
647                 }
648                 _ => {
649                     // More than one matching variant.
650                     err.multipart_suggestions(
651                         &format!(
652                             "try wrapping the expression in a variant of `{}`",
653                             self.tcx.def_path_str(expected_adt.did())
654                         ),
655                         compatible_variants.into_iter().map(
656                             |(variant, ctor_kind, field_name, _)| {
657                                 suggestions_for(&variant, ctor_kind, field_name)
658                             },
659                         ),
660                         Applicability::MaybeIncorrect,
661                     );
662                     return true;
663                 }
664             }
665         }
666
667         false
668     }
669
670     fn suggest_non_zero_new_unwrap(
671         &self,
672         err: &mut Diagnostic,
673         expr: &hir::Expr<'_>,
674         expected: Ty<'tcx>,
675         expr_ty: Ty<'tcx>,
676     ) -> bool {
677         let tcx = self.tcx;
678         let (adt, unwrap) = match expected.kind() {
679             // In case Option<NonZero*> is wanted, but * is provided, suggest calling new
680             ty::Adt(adt, substs) if tcx.is_diagnostic_item(sym::Option, adt.did()) => {
681                 // Unwrap option
682                 let ty::Adt(adt, _) = substs.type_at(0).kind() else { return false; };
683
684                 (adt, "")
685             }
686             // In case NonZero* is wanted, but * is provided also add `.unwrap()` to satisfy types
687             ty::Adt(adt, _) => (adt, ".unwrap()"),
688             _ => return false,
689         };
690
691         let map = [
692             (sym::NonZeroU8, tcx.types.u8),
693             (sym::NonZeroU16, tcx.types.u16),
694             (sym::NonZeroU32, tcx.types.u32),
695             (sym::NonZeroU64, tcx.types.u64),
696             (sym::NonZeroU128, tcx.types.u128),
697             (sym::NonZeroI8, tcx.types.i8),
698             (sym::NonZeroI16, tcx.types.i16),
699             (sym::NonZeroI32, tcx.types.i32),
700             (sym::NonZeroI64, tcx.types.i64),
701             (sym::NonZeroI128, tcx.types.i128),
702         ];
703
704         let Some((s, _)) = map
705             .iter()
706             .find(|&&(s, t)| self.tcx.is_diagnostic_item(s, adt.did()) && self.can_coerce(expr_ty, t))
707             else { return false; };
708
709         let path = self.tcx.def_path_str(adt.non_enum_variant().def_id);
710
711         err.multipart_suggestion(
712             format!("consider calling `{s}::new`"),
713             vec![
714                 (expr.span.shrink_to_lo(), format!("{path}::new(")),
715                 (expr.span.shrink_to_hi(), format!("){unwrap}")),
716             ],
717             Applicability::MaybeIncorrect,
718         );
719
720         true
721     }
722
723     pub fn get_conversion_methods(
724         &self,
725         span: Span,
726         expected: Ty<'tcx>,
727         checked_ty: Ty<'tcx>,
728         hir_id: hir::HirId,
729     ) -> Vec<AssocItem> {
730         let methods = self.probe_for_return_type(
731             span,
732             probe::Mode::MethodCall,
733             expected,
734             checked_ty,
735             hir_id,
736             |m| {
737                 self.has_only_self_parameter(m)
738                     && self
739                         .tcx
740                         // This special internal attribute is used to permit
741                         // "identity-like" conversion methods to be suggested here.
742                         //
743                         // FIXME (#46459 and #46460): ideally
744                         // `std::convert::Into::into` and `std::borrow:ToOwned` would
745                         // also be `#[rustc_conversion_suggestion]`, if not for
746                         // method-probing false-positives and -negatives (respectively).
747                         //
748                         // FIXME? Other potential candidate methods: `as_ref` and
749                         // `as_mut`?
750                         .has_attr(m.def_id, sym::rustc_conversion_suggestion)
751             },
752         );
753
754         methods
755     }
756
757     /// This function checks whether the method is not static and does not accept other parameters than `self`.
758     fn has_only_self_parameter(&self, method: &AssocItem) -> bool {
759         match method.kind {
760             ty::AssocKind::Fn => {
761                 method.fn_has_self_parameter
762                     && self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
763             }
764             _ => false,
765         }
766     }
767
768     /// Identify some cases where `as_ref()` would be appropriate and suggest it.
769     ///
770     /// Given the following code:
771     /// ```compile_fail,E0308
772     /// struct Foo;
773     /// fn takes_ref(_: &Foo) {}
774     /// let ref opt = Some(Foo);
775     ///
776     /// opt.map(|param| takes_ref(param));
777     /// ```
778     /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
779     ///
780     /// It only checks for `Option` and `Result` and won't work with
781     /// ```ignore (illustrative)
782     /// opt.map(|param| { takes_ref(param) });
783     /// ```
784     fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Span, &'static str, String)> {
785         let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.kind else {
786             return None;
787         };
788
789         let hir::def::Res::Local(local_id) = path.res else {
790             return None;
791         };
792
793         let local_parent = self.tcx.hir().get_parent_node(local_id);
794         let Some(Node::Param(hir::Param { hir_id: param_hir_id, .. })) = self.tcx.hir().find(local_parent) else {
795             return None;
796         };
797
798         let param_parent = self.tcx.hir().get_parent_node(*param_hir_id);
799         let Some(Node::Expr(hir::Expr {
800             hir_id: expr_hir_id,
801             kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }),
802             ..
803         })) = self.tcx.hir().find(param_parent) else {
804             return None;
805         };
806
807         let expr_parent = self.tcx.hir().get_parent_node(*expr_hir_id);
808         let hir = self.tcx.hir().find(expr_parent);
809         let closure_params_len = closure_fn_decl.inputs.len();
810         let (
811             Some(Node::Expr(hir::Expr {
812                 kind: hir::ExprKind::MethodCall(method_path, receiver, ..),
813                 ..
814             })),
815             1,
816         ) = (hir, closure_params_len) else {
817             return None;
818         };
819
820         let self_ty = self.typeck_results.borrow().expr_ty(receiver);
821         let name = method_path.ident.name;
822         let is_as_ref_able = match self_ty.peel_refs().kind() {
823             ty::Adt(def, _) => {
824                 (self.tcx.is_diagnostic_item(sym::Option, def.did())
825                     || self.tcx.is_diagnostic_item(sym::Result, def.did()))
826                     && (name == sym::map || name == sym::and_then)
827             }
828             _ => false,
829         };
830         match (is_as_ref_able, self.sess().source_map().span_to_snippet(method_path.ident.span)) {
831             (true, Ok(src)) => {
832                 let suggestion = format!("as_ref().{}", src);
833                 Some((method_path.ident.span, "consider using `as_ref` instead", suggestion))
834             }
835             _ => None,
836         }
837     }
838
839     pub(crate) fn maybe_get_struct_pattern_shorthand_field(
840         &self,
841         expr: &hir::Expr<'_>,
842     ) -> Option<Symbol> {
843         let hir = self.tcx.hir();
844         let local = match expr {
845             hir::Expr {
846                 kind:
847                     hir::ExprKind::Path(hir::QPath::Resolved(
848                         None,
849                         hir::Path {
850                             res: hir::def::Res::Local(_),
851                             segments: [hir::PathSegment { ident, .. }],
852                             ..
853                         },
854                     )),
855                 ..
856             } => Some(ident),
857             _ => None,
858         }?;
859
860         match hir.find(hir.get_parent_node(expr.hir_id))? {
861             Node::ExprField(field) => {
862                 if field.ident.name == local.name && field.is_shorthand {
863                     return Some(local.name);
864                 }
865             }
866             _ => {}
867         }
868
869         None
870     }
871
872     /// If the given `HirId` corresponds to a block with a trailing expression, return that expression
873     pub(crate) fn maybe_get_block_expr(
874         &self,
875         expr: &hir::Expr<'tcx>,
876     ) -> Option<&'tcx hir::Expr<'tcx>> {
877         match expr {
878             hir::Expr { kind: hir::ExprKind::Block(block, ..), .. } => block.expr,
879             _ => None,
880         }
881     }
882
883     /// Returns whether the given expression is an `else if`.
884     pub(crate) fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool {
885         if let hir::ExprKind::If(..) = expr.kind {
886             let parent_id = self.tcx.hir().get_parent_node(expr.hir_id);
887             if let Some(Node::Expr(hir::Expr {
888                 kind: hir::ExprKind::If(_, _, Some(else_expr)),
889                 ..
890             })) = self.tcx.hir().find(parent_id)
891             {
892                 return else_expr.hir_id == expr.hir_id;
893             }
894         }
895         false
896     }
897
898     /// This function is used to determine potential "simple" improvements or users' errors and
899     /// provide them useful help. For example:
900     ///
901     /// ```compile_fail,E0308
902     /// fn some_fn(s: &str) {}
903     ///
904     /// let x = "hey!".to_owned();
905     /// some_fn(x); // error
906     /// ```
907     ///
908     /// No need to find every potential function which could make a coercion to transform a
909     /// `String` into a `&str` since a `&` would do the trick!
910     ///
911     /// In addition of this check, it also checks between references mutability state. If the
912     /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
913     /// `&mut`!".
914     pub fn check_ref(
915         &self,
916         expr: &hir::Expr<'tcx>,
917         checked_ty: Ty<'tcx>,
918         expected: Ty<'tcx>,
919     ) -> Option<(
920         Span,
921         String,
922         String,
923         Applicability,
924         bool, /* verbose */
925         bool, /* suggest `&` or `&mut` type annotation */
926     )> {
927         let sess = self.sess();
928         let sp = expr.span;
929
930         // If the span is from an external macro, there's no suggestion we can make.
931         if in_external_macro(sess, sp) {
932             return None;
933         }
934
935         let sm = sess.source_map();
936
937         let replace_prefix = |s: &str, old: &str, new: &str| {
938             s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
939         };
940
941         // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
942         let expr = expr.peel_drop_temps();
943
944         match (&expr.kind, expected.kind(), checked_ty.kind()) {
945             (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (exp.kind(), check.kind()) {
946                 (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
947                     if let hir::ExprKind::Lit(_) = expr.kind
948                         && let Ok(src) = sm.span_to_snippet(sp)
949                         && replace_prefix(&src, "b\"", "\"").is_some()
950                     {
951                                 let pos = sp.lo() + BytePos(1);
952                                 return Some((
953                                     sp.with_hi(pos),
954                                     "consider removing the leading `b`".to_string(),
955                                     String::new(),
956                                     Applicability::MachineApplicable,
957                                     true,
958                                     false,
959                                 ));
960                             }
961                         }
962                 (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
963                     if let hir::ExprKind::Lit(_) = expr.kind
964                         && let Ok(src) = sm.span_to_snippet(sp)
965                         && replace_prefix(&src, "\"", "b\"").is_some()
966                     {
967                                 return Some((
968                                     sp.shrink_to_lo(),
969                                     "consider adding a leading `b`".to_string(),
970                                     "b".to_string(),
971                                     Applicability::MachineApplicable,
972                                     true,
973                                     false,
974                                 ));
975                     }
976                 }
977                 _ => {}
978             },
979             (_, &ty::Ref(_, _, mutability), _) => {
980                 // Check if it can work when put into a ref. For example:
981                 //
982                 // ```
983                 // fn bar(x: &mut i32) {}
984                 //
985                 // let x = 0u32;
986                 // bar(&x); // error, expected &mut
987                 // ```
988                 let ref_ty = match mutability {
989                     hir::Mutability::Mut => {
990                         self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
991                     }
992                     hir::Mutability::Not => {
993                         self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
994                     }
995                 };
996                 if self.can_coerce(ref_ty, expected) {
997                     let mut sugg_sp = sp;
998                     if let hir::ExprKind::MethodCall(ref segment, receiver, args, _) = expr.kind {
999                         let clone_trait =
1000                             self.tcx.require_lang_item(LangItem::Clone, Some(segment.ident.span));
1001                         if args.is_empty()
1002                             && self.typeck_results.borrow().type_dependent_def_id(expr.hir_id).map(
1003                                 |did| {
1004                                     let ai = self.tcx.associated_item(did);
1005                                     ai.trait_container(self.tcx) == Some(clone_trait)
1006                                 },
1007                             ) == Some(true)
1008                             && segment.ident.name == sym::clone
1009                         {
1010                             // If this expression had a clone call when suggesting borrowing
1011                             // we want to suggest removing it because it'd now be unnecessary.
1012                             sugg_sp = receiver.span;
1013                         }
1014                     }
1015                     if let Ok(src) = sm.span_to_snippet(sugg_sp) {
1016                         let needs_parens = match expr.kind {
1017                             // parenthesize if needed (Issue #46756)
1018                             hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
1019                             // parenthesize borrows of range literals (Issue #54505)
1020                             _ if is_range_literal(expr) => true,
1021                             _ => false,
1022                         };
1023
1024                         if let Some(sugg) = self.can_use_as_ref(expr) {
1025                             return Some((
1026                                 sugg.0,
1027                                 sugg.1.to_string(),
1028                                 sugg.2,
1029                                 Applicability::MachineApplicable,
1030                                 false,
1031                                 false,
1032                             ));
1033                         }
1034
1035                         let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
1036                             Some(ident) => format!("{ident}: "),
1037                             None => String::new(),
1038                         };
1039
1040                         if let Some(hir::Node::Expr(hir::Expr {
1041                             kind: hir::ExprKind::Assign(..),
1042                             ..
1043                         })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
1044                         {
1045                             if mutability.is_mut() {
1046                                 // Suppressing this diagnostic, we'll properly print it in `check_expr_assign`
1047                                 return None;
1048                             }
1049                         }
1050
1051                         let sugg_expr = if needs_parens { format!("({src})") } else { src };
1052                         return Some((
1053                             sp,
1054                             format!("consider {}borrowing here", mutability.mutably_str()),
1055                             format!("{prefix}{}{sugg_expr}", mutability.ref_prefix_str()),
1056                             Applicability::MachineApplicable,
1057                             false,
1058                             false,
1059                         ));
1060                     }
1061                 }
1062             }
1063             (
1064                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
1065                 _,
1066                 &ty::Ref(_, checked, _),
1067             ) if self.can_sub(self.param_env, checked, expected).is_ok() => {
1068                 // We have `&T`, check if what was expected was `T`. If so,
1069                 // we may want to suggest removing a `&`.
1070                 if sm.is_imported(expr.span) {
1071                     // Go through the spans from which this span was expanded,
1072                     // and find the one that's pointing inside `sp`.
1073                     //
1074                     // E.g. for `&format!("")`, where we want the span to the
1075                     // `format!()` invocation instead of its expansion.
1076                     if let Some(call_span) =
1077                         iter::successors(Some(expr.span), |s| s.parent_callsite())
1078                             .find(|&s| sp.contains(s))
1079                         && sm.is_span_accessible(call_span)
1080                     {
1081                         return Some((
1082                             sp.with_hi(call_span.lo()),
1083                             "consider removing the borrow".to_string(),
1084                             String::new(),
1085                             Applicability::MachineApplicable,
1086                             true,
1087                             true
1088                         ));
1089                     }
1090                     return None;
1091                 }
1092                 if sp.contains(expr.span)
1093                     && sm.is_span_accessible(expr.span)
1094                 {
1095                     return Some((
1096                         sp.with_hi(expr.span.lo()),
1097                         "consider removing the borrow".to_string(),
1098                         String::new(),
1099                         Applicability::MachineApplicable,
1100                         true,
1101                         true,
1102                     ));
1103                 }
1104             }
1105             (
1106                 _,
1107                 &ty::RawPtr(TypeAndMut { ty: ty_b, mutbl: mutbl_b }),
1108                 &ty::Ref(_, ty_a, mutbl_a),
1109             ) => {
1110                 if let Some(steps) = self.deref_steps(ty_a, ty_b)
1111                     // Only suggest valid if dereferencing needed.
1112                     && steps > 0
1113                     // The pointer type implements `Copy` trait so the suggestion is always valid.
1114                     && let Ok(src) = sm.span_to_snippet(sp)
1115                 {
1116                     let derefs = "*".repeat(steps);
1117                     let old_prefix = mutbl_a.ref_prefix_str();
1118                     let new_prefix = mutbl_b.ref_prefix_str().to_owned() + &derefs;
1119
1120                     let suggestion = replace_prefix(&src, old_prefix, &new_prefix).map(|_| {
1121                         // skip `&` or `&mut ` if both mutabilities are mutable
1122                         let lo = sp.lo() + BytePos(min(old_prefix.len(), mutbl_b.ref_prefix_str().len()) as _);
1123                         // skip `&` or `&mut `
1124                         let hi = sp.lo() + BytePos(old_prefix.len() as _);
1125                         let sp = sp.with_lo(lo).with_hi(hi);
1126
1127                         (
1128                             sp,
1129                             format!("{}{derefs}", if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" }),
1130                             if mutbl_b <= mutbl_a { Applicability::MachineApplicable } else { Applicability::MaybeIncorrect }
1131                         )
1132                     });
1133
1134                     if let Some((span, src, applicability)) = suggestion {
1135                         return Some((
1136                             span,
1137                             "consider dereferencing".to_string(),
1138                             src,
1139                             applicability,
1140                             true,
1141                             false,
1142                         ));
1143                     }
1144                 }
1145             }
1146             _ if sp == expr.span => {
1147                 if let Some(mut steps) = self.deref_steps(checked_ty, expected) {
1148                     let mut expr = expr.peel_blocks();
1149                     let mut prefix_span = expr.span.shrink_to_lo();
1150                     let mut remove = String::new();
1151
1152                     // Try peeling off any existing `&` and `&mut` to reach our target type
1153                     while steps > 0 {
1154                         if let hir::ExprKind::AddrOf(_, mutbl, inner) = expr.kind {
1155                             // If the expression has `&`, removing it would fix the error
1156                             prefix_span = prefix_span.with_hi(inner.span.lo());
1157                             expr = inner;
1158                             remove.push_str(mutbl.ref_prefix_str());
1159                             steps -= 1;
1160                         } else {
1161                             break;
1162                         }
1163                     }
1164                     // If we've reached our target type with just removing `&`, then just print now.
1165                     if steps == 0 {
1166                         return Some((
1167                             prefix_span,
1168                             format!("consider removing the `{}`", remove.trim()),
1169                             String::new(),
1170                             // Do not remove `&&` to get to bool, because it might be something like
1171                             // { a } && b, which we have a separate fixup suggestion that is more
1172                             // likely correct...
1173                             if remove.trim() == "&&" && expected == self.tcx.types.bool {
1174                                 Applicability::MaybeIncorrect
1175                             } else {
1176                                 Applicability::MachineApplicable
1177                             },
1178                             true,
1179                             false,
1180                         ));
1181                     }
1182
1183                     // For this suggestion to make sense, the type would need to be `Copy`,
1184                     // or we have to be moving out of a `Box<T>`
1185                     if self.type_is_copy_modulo_regions(self.param_env, expected, sp)
1186                         // FIXME(compiler-errors): We can actually do this if the checked_ty is
1187                         // `steps` layers of boxes, not just one, but this is easier and most likely.
1188                         || (checked_ty.is_box() && steps == 1)
1189                     {
1190                         let deref_kind = if checked_ty.is_box() {
1191                             "unboxing the value"
1192                         } else if checked_ty.is_region_ptr() {
1193                             "dereferencing the borrow"
1194                         } else {
1195                             "dereferencing the type"
1196                         };
1197
1198                         // Suggest removing `&` if we have removed any, otherwise suggest just
1199                         // dereferencing the remaining number of steps.
1200                         let message = if remove.is_empty() {
1201                             format!("consider {deref_kind}")
1202                         } else {
1203                             format!(
1204                                 "consider removing the `{}` and {} instead",
1205                                 remove.trim(),
1206                                 deref_kind
1207                             )
1208                         };
1209
1210                         let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
1211                             Some(ident) => format!("{ident}: "),
1212                             None => String::new(),
1213                         };
1214
1215                         let (span, suggestion) = if self.is_else_if_block(expr) {
1216                             // Don't suggest nonsense like `else *if`
1217                             return None;
1218                         } else if let Some(expr) = self.maybe_get_block_expr(expr) {
1219                             // prefix should be empty here..
1220                             (expr.span.shrink_to_lo(), "*".to_string())
1221                         } else {
1222                             (prefix_span, format!("{}{}", prefix, "*".repeat(steps)))
1223                         };
1224
1225                         return Some((
1226                             span,
1227                             message,
1228                             suggestion,
1229                             Applicability::MachineApplicable,
1230                             true,
1231                             false,
1232                         ));
1233                     }
1234                 }
1235             }
1236             _ => {}
1237         }
1238         None
1239     }
1240
1241     pub fn check_for_cast(
1242         &self,
1243         err: &mut Diagnostic,
1244         expr: &hir::Expr<'_>,
1245         checked_ty: Ty<'tcx>,
1246         expected_ty: Ty<'tcx>,
1247         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
1248     ) -> bool {
1249         if self.tcx.sess.source_map().is_imported(expr.span) {
1250             // Ignore if span is from within a macro.
1251             return false;
1252         }
1253
1254         let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) else {
1255             return false;
1256         };
1257
1258         // If casting this expression to a given numeric type would be appropriate in case of a type
1259         // mismatch.
1260         //
1261         // We want to minimize the amount of casting operations that are suggested, as it can be a
1262         // lossy operation with potentially bad side effects, so we only suggest when encountering
1263         // an expression that indicates that the original type couldn't be directly changed.
1264         //
1265         // For now, don't suggest casting with `as`.
1266         let can_cast = false;
1267
1268         let mut sugg = vec![];
1269
1270         if let Some(hir::Node::ExprField(field)) =
1271             self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
1272         {
1273             // `expr` is a literal field for a struct, only suggest if appropriate
1274             if field.is_shorthand {
1275                 // This is a field literal
1276                 sugg.push((field.ident.span.shrink_to_lo(), format!("{}: ", field.ident)));
1277             } else {
1278                 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
1279                 return false;
1280             }
1281         };
1282
1283         if let hir::ExprKind::Call(path, args) = &expr.kind
1284             && let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
1285                 (&path.kind, args.len())
1286             // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
1287             && let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
1288                 (&base_ty.kind, path_segment.ident.name)
1289         {
1290             if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
1291                 match ident.name {
1292                     sym::i128
1293                     | sym::i64
1294                     | sym::i32
1295                     | sym::i16
1296                     | sym::i8
1297                     | sym::u128
1298                     | sym::u64
1299                     | sym::u32
1300                     | sym::u16
1301                     | sym::u8
1302                     | sym::isize
1303                     | sym::usize
1304                         if base_ty_path.segments.len() == 1 =>
1305                     {
1306                         return false;
1307                     }
1308                     _ => {}
1309                 }
1310             }
1311         }
1312
1313         let msg = format!(
1314             "you can convert {} `{}` to {} `{}`",
1315             checked_ty.kind().article(),
1316             checked_ty,
1317             expected_ty.kind().article(),
1318             expected_ty,
1319         );
1320         let cast_msg = format!(
1321             "you can cast {} `{}` to {} `{}`",
1322             checked_ty.kind().article(),
1323             checked_ty,
1324             expected_ty.kind().article(),
1325             expected_ty,
1326         );
1327         let lit_msg = format!(
1328             "change the type of the numeric literal from `{checked_ty}` to `{expected_ty}`",
1329         );
1330
1331         let close_paren = if expr.precedence().order() < PREC_POSTFIX {
1332             sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1333             ")"
1334         } else {
1335             ""
1336         };
1337
1338         let mut cast_suggestion = sugg.clone();
1339         cast_suggestion.push((expr.span.shrink_to_hi(), format!("{close_paren} as {expected_ty}")));
1340         let mut into_suggestion = sugg.clone();
1341         into_suggestion.push((expr.span.shrink_to_hi(), format!("{close_paren}.into()")));
1342         let mut suffix_suggestion = sugg.clone();
1343         suffix_suggestion.push((
1344             if matches!(
1345                 (&expected_ty.kind(), &checked_ty.kind()),
1346                 (ty::Int(_) | ty::Uint(_), ty::Float(_))
1347             ) {
1348                 // Remove fractional part from literal, for example `42.0f32` into `42`
1349                 let src = src.trim_end_matches(&checked_ty.to_string());
1350                 let len = src.split('.').next().unwrap().len();
1351                 expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
1352             } else {
1353                 let len = src.trim_end_matches(&checked_ty.to_string()).len();
1354                 expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
1355             },
1356             if expr.precedence().order() < PREC_POSTFIX {
1357                 // Readd `)`
1358                 format!("{expected_ty})")
1359             } else {
1360                 expected_ty.to_string()
1361             },
1362         ));
1363         let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
1364             if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
1365         };
1366         let is_negative_int =
1367             |expr: &hir::Expr<'_>| matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::Neg, ..));
1368         let is_uint = |ty: Ty<'_>| matches!(ty.kind(), ty::Uint(..));
1369
1370         let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
1371
1372         let suggest_fallible_into_or_lhs_from =
1373             |err: &mut Diagnostic, exp_to_found_is_fallible: bool| {
1374                 // If we know the expression the expected type is derived from, we might be able
1375                 // to suggest a widening conversion rather than a narrowing one (which may
1376                 // panic). For example, given x: u8 and y: u32, if we know the span of "x",
1377                 //   x > y
1378                 // can be given the suggestion "u32::from(x) > y" rather than
1379                 // "x > y.try_into().unwrap()".
1380                 let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
1381                     self.tcx
1382                         .sess
1383                         .source_map()
1384                         .span_to_snippet(expr.span)
1385                         .ok()
1386                         .map(|src| (expr, src))
1387                 });
1388                 let (msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
1389                     (lhs_expr_and_src, exp_to_found_is_fallible)
1390                 {
1391                     let msg = format!(
1392                         "you can convert `{lhs_src}` from `{expected_ty}` to `{checked_ty}`, matching the type of `{src}`",
1393                     );
1394                     let suggestion = vec![
1395                         (lhs_expr.span.shrink_to_lo(), format!("{checked_ty}::from(")),
1396                         (lhs_expr.span.shrink_to_hi(), ")".to_string()),
1397                     ];
1398                     (msg, suggestion)
1399                 } else {
1400                     let msg = format!("{msg} and panic if the converted value doesn't fit");
1401                     let mut suggestion = sugg.clone();
1402                     suggestion.push((
1403                         expr.span.shrink_to_hi(),
1404                         format!("{close_paren}.try_into().unwrap()"),
1405                     ));
1406                     (msg, suggestion)
1407                 };
1408                 err.multipart_suggestion_verbose(
1409                     &msg,
1410                     suggestion,
1411                     Applicability::MachineApplicable,
1412                 );
1413             };
1414
1415         let suggest_to_change_suffix_or_into =
1416             |err: &mut Diagnostic,
1417              found_to_exp_is_fallible: bool,
1418              exp_to_found_is_fallible: bool| {
1419                 let exp_is_lhs =
1420                     expected_ty_expr.map(|e| self.tcx.hir().is_lhs(e.hir_id)).unwrap_or(false);
1421
1422                 if exp_is_lhs {
1423                     return;
1424                 }
1425
1426                 let always_fallible = found_to_exp_is_fallible
1427                     && (exp_to_found_is_fallible || expected_ty_expr.is_none());
1428                 let msg = if literal_is_ty_suffixed(expr) {
1429                     &lit_msg
1430                 } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
1431                     // We now know that converting either the lhs or rhs is fallible. Before we
1432                     // suggest a fallible conversion, check if the value can never fit in the
1433                     // expected type.
1434                     let msg = format!("`{src}` cannot fit into type `{expected_ty}`");
1435                     err.note(&msg);
1436                     return;
1437                 } else if in_const_context {
1438                     // Do not recommend `into` or `try_into` in const contexts.
1439                     return;
1440                 } else if found_to_exp_is_fallible {
1441                     return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
1442                 } else {
1443                     &msg
1444                 };
1445                 let suggestion = if literal_is_ty_suffixed(expr) {
1446                     suffix_suggestion.clone()
1447                 } else {
1448                     into_suggestion.clone()
1449                 };
1450                 err.multipart_suggestion_verbose(msg, suggestion, Applicability::MachineApplicable);
1451             };
1452
1453         match (&expected_ty.kind(), &checked_ty.kind()) {
1454             (ty::Int(exp), ty::Int(found)) => {
1455                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1456                 {
1457                     (Some(exp), Some(found)) if exp < found => (true, false),
1458                     (Some(exp), Some(found)) if exp > found => (false, true),
1459                     (None, Some(8 | 16)) => (false, true),
1460                     (Some(8 | 16), None) => (true, false),
1461                     (None, _) | (_, None) => (true, true),
1462                     _ => (false, false),
1463                 };
1464                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1465                 true
1466             }
1467             (ty::Uint(exp), ty::Uint(found)) => {
1468                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1469                 {
1470                     (Some(exp), Some(found)) if exp < found => (true, false),
1471                     (Some(exp), Some(found)) if exp > found => (false, true),
1472                     (None, Some(8 | 16)) => (false, true),
1473                     (Some(8 | 16), None) => (true, false),
1474                     (None, _) | (_, None) => (true, true),
1475                     _ => (false, false),
1476                 };
1477                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1478                 true
1479             }
1480             (&ty::Int(exp), &ty::Uint(found)) => {
1481                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1482                 {
1483                     (Some(exp), Some(found)) if found < exp => (false, true),
1484                     (None, Some(8)) => (false, true),
1485                     _ => (true, true),
1486                 };
1487                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1488                 true
1489             }
1490             (&ty::Uint(exp), &ty::Int(found)) => {
1491                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1492                 {
1493                     (Some(exp), Some(found)) if found > exp => (true, false),
1494                     (Some(8), None) => (true, false),
1495                     _ => (true, true),
1496                 };
1497                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1498                 true
1499             }
1500             (ty::Float(exp), ty::Float(found)) => {
1501                 if found.bit_width() < exp.bit_width() {
1502                     suggest_to_change_suffix_or_into(err, false, true);
1503                 } else if literal_is_ty_suffixed(expr) {
1504                     err.multipart_suggestion_verbose(
1505                         &lit_msg,
1506                         suffix_suggestion,
1507                         Applicability::MachineApplicable,
1508                     );
1509                 } else if can_cast {
1510                     // Missing try_into implementation for `f64` to `f32`
1511                     err.multipart_suggestion_verbose(
1512                         &format!("{cast_msg}, producing the closest possible value"),
1513                         cast_suggestion,
1514                         Applicability::MaybeIncorrect, // lossy conversion
1515                     );
1516                 }
1517                 true
1518             }
1519             (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
1520                 if literal_is_ty_suffixed(expr) {
1521                     err.multipart_suggestion_verbose(
1522                         &lit_msg,
1523                         suffix_suggestion,
1524                         Applicability::MachineApplicable,
1525                     );
1526                 } else if can_cast {
1527                     // Missing try_into implementation for `{float}` to `{integer}`
1528                     err.multipart_suggestion_verbose(
1529                         &format!("{msg}, rounding the float towards zero"),
1530                         cast_suggestion,
1531                         Applicability::MaybeIncorrect, // lossy conversion
1532                     );
1533                 }
1534                 true
1535             }
1536             (ty::Float(exp), ty::Uint(found)) => {
1537                 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
1538                 if exp.bit_width() > found.bit_width().unwrap_or(256) {
1539                     err.multipart_suggestion_verbose(
1540                         &format!(
1541                             "{msg}, producing the floating point representation of the integer",
1542                         ),
1543                         into_suggestion,
1544                         Applicability::MachineApplicable,
1545                     );
1546                 } else if literal_is_ty_suffixed(expr) {
1547                     err.multipart_suggestion_verbose(
1548                         &lit_msg,
1549                         suffix_suggestion,
1550                         Applicability::MachineApplicable,
1551                     );
1552                 } else {
1553                     // Missing try_into implementation for `{integer}` to `{float}`
1554                     err.multipart_suggestion_verbose(
1555                         &format!(
1556                             "{cast_msg}, producing the floating point representation of the integer, \
1557                                  rounded if necessary",
1558                         ),
1559                         cast_suggestion,
1560                         Applicability::MaybeIncorrect, // lossy conversion
1561                     );
1562                 }
1563                 true
1564             }
1565             (ty::Float(exp), ty::Int(found)) => {
1566                 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
1567                 if exp.bit_width() > found.bit_width().unwrap_or(256) {
1568                     err.multipart_suggestion_verbose(
1569                         &format!(
1570                             "{}, producing the floating point representation of the integer",
1571                             &msg,
1572                         ),
1573                         into_suggestion,
1574                         Applicability::MachineApplicable,
1575                     );
1576                 } else if literal_is_ty_suffixed(expr) {
1577                     err.multipart_suggestion_verbose(
1578                         &lit_msg,
1579                         suffix_suggestion,
1580                         Applicability::MachineApplicable,
1581                     );
1582                 } else {
1583                     // Missing try_into implementation for `{integer}` to `{float}`
1584                     err.multipart_suggestion_verbose(
1585                         &format!(
1586                             "{}, producing the floating point representation of the integer, \
1587                                 rounded if necessary",
1588                             &msg,
1589                         ),
1590                         cast_suggestion,
1591                         Applicability::MaybeIncorrect, // lossy conversion
1592                     );
1593                 }
1594                 true
1595             }
1596             (
1597                 &ty::Uint(ty::UintTy::U32 | ty::UintTy::U64 | ty::UintTy::U128)
1598                 | &ty::Int(ty::IntTy::I32 | ty::IntTy::I64 | ty::IntTy::I128),
1599                 &ty::Char,
1600             ) => {
1601                 err.multipart_suggestion_verbose(
1602                     &format!("{cast_msg}, since a `char` always occupies 4 bytes"),
1603                     cast_suggestion,
1604                     Applicability::MachineApplicable,
1605                 );
1606                 true
1607             }
1608             _ => false,
1609         }
1610     }
1611
1612     /// Identify when the user has written `foo..bar()` instead of `foo.bar()`.
1613     pub fn check_for_range_as_method_call(
1614         &self,
1615         err: &mut Diagnostic,
1616         expr: &hir::Expr<'_>,
1617         checked_ty: Ty<'tcx>,
1618         expected_ty: Ty<'tcx>,
1619     ) {
1620         if !hir::is_range_literal(expr) {
1621             return;
1622         }
1623         let hir::ExprKind::Struct(
1624             hir::QPath::LangItem(LangItem::Range, ..),
1625             [start, end],
1626             _,
1627         ) = expr.kind else { return; };
1628         let parent = self.tcx.hir().get_parent_node(expr.hir_id);
1629         if let Some(hir::Node::ExprField(_)) = self.tcx.hir().find(parent) {
1630             // Ignore `Foo { field: a..Default::default() }`
1631             return;
1632         }
1633         let mut expr = end.expr;
1634         while let hir::ExprKind::MethodCall(_, rcvr, ..) = expr.kind {
1635             // Getting to the root receiver and asserting it is a fn call let's us ignore cases in
1636             // `src/test/ui/methods/issues/issue-90315.stderr`.
1637             expr = rcvr;
1638         }
1639         let hir::ExprKind::Call(method_name, _) = expr.kind else { return; };
1640         let ty::Adt(adt, _) = checked_ty.kind() else { return; };
1641         if self.tcx.lang_items().range_struct() != Some(adt.did()) {
1642             return;
1643         }
1644         if let ty::Adt(adt, _) = expected_ty.kind()
1645             && self.tcx.lang_items().range_struct() == Some(adt.did())
1646         {
1647             return;
1648         }
1649         // Check if start has method named end.
1650         let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else { return; };
1651         let [hir::PathSegment { ident, .. }] = p.segments else { return; };
1652         let self_ty = self.typeck_results.borrow().expr_ty(start.expr);
1653         let Ok(_pick) = self.probe_for_name(
1654             probe::Mode::MethodCall,
1655             *ident,
1656             probe::IsSuggestion(true),
1657             self_ty,
1658             expr.hir_id,
1659             probe::ProbeScope::AllTraits,
1660         ) else { return; };
1661         let mut sugg = ".";
1662         let mut span = start.expr.span.between(end.expr.span);
1663         if span.lo() + BytePos(2) == span.hi() {
1664             // There's no space between the start, the range op and the end, suggest removal which
1665             // will be more noticeable than the replacement of `..` with `.`.
1666             span = span.with_lo(span.lo() + BytePos(1));
1667             sugg = "";
1668         }
1669         err.span_suggestion_verbose(
1670             span,
1671             "you likely meant to write a method call instead of a range",
1672             sugg,
1673             Applicability::MachineApplicable,
1674         );
1675     }
1676 }