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