Skip to main content

rustc_hir_typeck/fn_ctxt/
suggestions.rs

1// ignore-tidy-filelength
2use core::cmp::min;
3use core::iter;
4
5use hir::def_id::LocalDefId;
6use rustc_ast::util::parser::ExprPrecedence;
7use rustc_data_structures::packed::Pu128;
8use rustc_errors::{Applicability, Diag, MultiSpan, listify, msg};
9use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
10use rustc_hir::lang_items::LangItem;
11use rustc_hir::{
12    self as hir, Arm, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, ExprKind,
13    GenericBound, HirId, LoopSource, Node, PatExpr, PatExprKind, Path, QPath, Stmt, StmtKind,
14    TyKind, WherePredicateKind, expr_needs_parens, is_range_literal,
15};
16use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
17use rustc_hir_analysis::suggest_impl_trait;
18use rustc_middle::middle::stability::EvalResult;
19use rustc_middle::span_bug;
20use rustc_middle::ty::print::with_no_trimmed_paths;
21use rustc_middle::ty::{
22    self, Article, Binder, IsSuggestable, Ty, TyCtxt, TypeVisitableExt, Upcast,
23    suggest_constraining_type_params,
24};
25use rustc_session::errors::ExprParenthesesNeeded;
26use rustc_span::source_map::Spanned;
27use rustc_span::{ExpnKind, Ident, MacroKind, Span, Symbol, sym};
28use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
29use rustc_trait_selection::error_reporting::traits::DefIdOrName;
30use rustc_trait_selection::infer::InferCtxtExt;
31use rustc_trait_selection::traits;
32use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
33use tracing::{debug, instrument};
34
35use super::FnCtxt;
36use crate::errors;
37use crate::fn_ctxt::rustc_span::BytePos;
38use crate::method::probe;
39use crate::method::probe::{IsSuggestion, Mode, ProbeScope};
40
41impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
42    pub(crate) fn body_fn_sig(&self) -> Option<ty::FnSig<'tcx>> {
43        self.typeck_results
44            .borrow()
45            .liberated_fn_sigs()
46            .get(self.tcx.local_def_id_to_hir_id(self.body_id))
47            .copied()
48    }
49
50    pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diag<'_>) {
51        // This suggestion is incorrect for
52        // fn foo() -> bool { match () { () => true } || match () { () => true } }
53        err.span_suggestion_short(
54            span.shrink_to_hi(),
55            "consider using a semicolon here",
56            ";",
57            Applicability::MaybeIncorrect,
58        );
59    }
60
61    /// On implicit return expressions with mismatched types, provides the following suggestions:
62    ///
63    /// - Points out the method's return type as the reason for the expected type.
64    /// - Possible missing semicolon.
65    /// - Possible missing return type if the return type is the default, and not `fn main()`.
66    pub(crate) fn suggest_mismatched_types_on_tail(
67        &self,
68        err: &mut Diag<'_>,
69        expr: &'tcx hir::Expr<'tcx>,
70        expected: Ty<'tcx>,
71        found: Ty<'tcx>,
72        blk_id: HirId,
73    ) -> bool {
74        let expr = expr.peel_drop_temps();
75        let mut pointing_at_return_type = false;
76        if let hir::ExprKind::Break(..) = expr.kind {
77            // `break` type mismatches provide better context for tail `loop` expressions.
78            return false;
79        }
80        if let Some((fn_id, fn_decl)) = self.get_fn_decl(blk_id) {
81            pointing_at_return_type =
82                self.suggest_missing_return_type(err, fn_decl, expected, found, fn_id);
83            self.suggest_missing_break_or_return_expr(
84                err, expr, fn_decl, expected, found, blk_id, fn_id,
85            );
86        }
87        pointing_at_return_type
88    }
89
90    /// When encountering an fn-like type, try accessing the output of the type
91    /// and suggesting calling it if it satisfies a predicate (i.e. if the
92    /// output has a method or a field):
93    /// ```compile_fail,E0308
94    /// fn foo(x: usize) -> usize { x }
95    /// let x: usize = foo;  // suggest calling the `foo` function: `foo(42)`
96    /// ```
97    pub(crate) fn suggest_fn_call(
98        &self,
99        err: &mut Diag<'_>,
100        expr: &hir::Expr<'_>,
101        found: Ty<'tcx>,
102        can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
103    ) -> bool {
104        let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(found) else {
105            return false;
106        };
107        if can_satisfy(output) {
108            let (sugg_call, mut applicability) = match inputs.len() {
109                0 => ("".to_string(), Applicability::MachineApplicable),
110                1..=4 => (
111                    inputs
112                        .iter()
113                        .map(|ty| {
114                            if ty.is_suggestable(self.tcx, false) {
115                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/* {0} */", ty))
    })format!("/* {ty} */")
116                            } else {
117                                "/* value */".to_string()
118                            }
119                        })
120                        .collect::<Vec<_>>()
121                        .join(", "),
122                    Applicability::HasPlaceholders,
123                ),
124                _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
125            };
126
127            let msg = match def_id_or_name {
128                DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
129                    DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
130                    DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
131                    kind => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("call this {0}",
                self.tcx.def_kind_descr(kind, def_id)))
    })format!("call this {}", self.tcx.def_kind_descr(kind, def_id)),
132                },
133                DefIdOrName::Name(name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("call this {0}", name))
    })format!("call this {name}"),
134            };
135
136            let sugg = match expr.kind {
137                hir::ExprKind::Call(..)
138                | hir::ExprKind::Path(..)
139                | hir::ExprKind::Index(..)
140                | hir::ExprKind::Lit(..) => {
141                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("({0})", sugg_call))
                        }))]))vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
142                }
143                hir::ExprKind::Closure { .. } => {
144                    // Might be `{ expr } || { bool }`
145                    applicability = Applicability::MaybeIncorrect;
146                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_lo(), "(".to_string()),
                (expr.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(")({0})", sugg_call))
                        }))]))vec![
147                        (expr.span.shrink_to_lo(), "(".to_string()),
148                        (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
149                    ]
150                }
151                _ => {
152                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_lo(), "(".to_string()),
                (expr.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(")({0})", sugg_call))
                        }))]))vec![
153                        (expr.span.shrink_to_lo(), "(".to_string()),
154                        (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
155                    ]
156                }
157            };
158
159            err.multipart_suggestion(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use parentheses to {0}", msg))
    })format!("use parentheses to {msg}"), sugg, applicability);
160            return true;
161        }
162        false
163    }
164
165    /// Extracts information about a callable type for diagnostics. This is a
166    /// heuristic -- it doesn't necessarily mean that a type is always callable,
167    /// because the callable type must also be well-formed to be called.
168    pub(in super::super) fn extract_callable_info(
169        &self,
170        ty: Ty<'tcx>,
171    ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
172        self.err_ctxt().extract_callable_info(self.body_id, self.param_env, ty)
173    }
174
175    pub(crate) fn suggest_two_fn_call(
176        &self,
177        err: &mut Diag<'_>,
178        lhs_expr: &'tcx hir::Expr<'tcx>,
179        lhs_ty: Ty<'tcx>,
180        rhs_expr: &'tcx hir::Expr<'tcx>,
181        rhs_ty: Ty<'tcx>,
182        can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
183    ) -> bool {
184        if lhs_expr.span.in_derive_expansion() || rhs_expr.span.in_derive_expansion() {
185            return false;
186        }
187        let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_ty) else {
188            return false;
189        };
190        let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_ty) else {
191            return false;
192        };
193
194        if can_satisfy(lhs_output_ty, rhs_output_ty) {
195            let mut sugg = ::alloc::vec::Vec::new()vec![];
196            let mut applicability = Applicability::MachineApplicable;
197
198            for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
199                let (sugg_call, this_applicability) = match inputs.len() {
200                    0 => ("".to_string(), Applicability::MachineApplicable),
201                    1..=4 => (
202                        inputs
203                            .iter()
204                            .map(|ty| {
205                                if ty.is_suggestable(self.tcx, false) {
206                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/* {0} */", ty))
    })format!("/* {ty} */")
207                                } else {
208                                    "/* value */".to_string()
209                                }
210                            })
211                            .collect::<Vec<_>>()
212                            .join(", "),
213                        Applicability::HasPlaceholders,
214                    ),
215                    _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
216                };
217
218                applicability = applicability.max(this_applicability);
219
220                match expr.kind {
221                    hir::ExprKind::Call(..)
222                    | hir::ExprKind::Path(..)
223                    | hir::ExprKind::Index(..)
224                    | hir::ExprKind::Lit(..) => {
225                        sugg.extend([(expr.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})", sugg_call))
    })format!("({sugg_call})"))]);
226                    }
227                    hir::ExprKind::Closure { .. } => {
228                        // Might be `{ expr } || { bool }`
229                        applicability = Applicability::MaybeIncorrect;
230                        sugg.extend([
231                            (expr.span.shrink_to_lo(), "(".to_string()),
232                            (expr.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(")({0})", sugg_call))
    })format!(")({sugg_call})")),
233                        ]);
234                    }
235                    _ => {
236                        sugg.extend([
237                            (expr.span.shrink_to_lo(), "(".to_string()),
238                            (expr.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(")({0})", sugg_call))
    })format!(")({sugg_call})")),
239                        ]);
240                    }
241                }
242            }
243
244            err.multipart_suggestion("use parentheses to call these", sugg, applicability);
245
246            true
247        } else {
248            false
249        }
250    }
251
252    pub(crate) fn suggest_remove_last_method_call(
253        &self,
254        err: &mut Diag<'_>,
255        expr: &hir::Expr<'tcx>,
256        expected: Ty<'tcx>,
257    ) -> bool {
258        if let hir::ExprKind::MethodCall(hir::PathSegment { ident: method, .. }, recv_expr, &[], _) =
259            expr.kind
260            && let Some(recv_ty) = self.typeck_results.borrow().expr_ty_opt(recv_expr)
261            && self.may_coerce(recv_ty, expected)
262            && let name = method.name.as_str()
263            && (name.starts_with("to_") || name.starts_with("as_") || name == "into")
264        {
265            let span = if let Some(recv_span) = recv_expr.span.find_ancestor_inside(expr.span) {
266                expr.span.with_lo(recv_span.hi())
267            } else {
268                expr.span.with_lo(method.span.lo() - rustc_span::BytePos(1))
269            };
270            err.span_suggestion_verbose(
271                span,
272                "try removing the method call",
273                "",
274                Applicability::MachineApplicable,
275            );
276            return true;
277        }
278        false
279    }
280
281    pub(crate) fn suggest_deref_ref_or_into(
282        &self,
283        err: &mut Diag<'_>,
284        expr: &hir::Expr<'tcx>,
285        expected: Ty<'tcx>,
286        found: Ty<'tcx>,
287        expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
288    ) -> bool {
289        let expr = expr.peel_blocks();
290        let methods =
291            self.get_conversion_methods_for_diagnostic(expr.span, expected, found, expr.hir_id);
292
293        if let Some((suggestion, msg, applicability, verbose, annotation)) =
294            self.suggest_deref_or_ref(expr, found, expected)
295        {
296            if verbose {
297                err.multipart_suggestion(msg, suggestion, applicability);
298            } else {
299                err.multipart_suggestion(msg, suggestion, applicability);
300            }
301            if annotation {
302                let suggest_annotation = match expr.peel_drop_temps().kind {
303                    hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, _) => mutbl.ref_prefix_str(),
304                    _ => return true,
305                };
306                let mut tuple_indexes = Vec::new();
307                let mut expr_id = expr.hir_id;
308                for (parent_id, node) in self.tcx.hir_parent_iter(expr.hir_id) {
309                    match node {
310                        Node::Expr(&Expr { kind: ExprKind::Tup(subs), .. }) => {
311                            tuple_indexes.push(
312                                subs.iter()
313                                    .enumerate()
314                                    .find(|(_, sub_expr)| sub_expr.hir_id == expr_id)
315                                    .unwrap()
316                                    .0,
317                            );
318                            expr_id = parent_id;
319                        }
320                        Node::LetStmt(local) => {
321                            if let Some(mut ty) = local.ty {
322                                while let Some(index) = tuple_indexes.pop() {
323                                    match ty.kind {
324                                        TyKind::Tup(tys) => ty = &tys[index],
325                                        _ => return true,
326                                    }
327                                }
328                                let annotation_span = ty.span;
329                                err.span_suggestion(
330                                    annotation_span.with_hi(annotation_span.lo()),
331                                    "alternatively, consider changing the type annotation",
332                                    suggest_annotation,
333                                    Applicability::MaybeIncorrect,
334                                );
335                            }
336                            break;
337                        }
338                        _ => break,
339                    }
340                }
341            }
342            return true;
343        }
344
345        if self.suggest_else_fn_with_closure(err, expr, found, expected) {
346            return true;
347        }
348
349        if self.suggest_fn_call(err, expr, found, |output| self.may_coerce(output, expected))
350            && let ty::FnDef(def_id, ..) = *found.kind()
351            && let Some(sp) = self.tcx.hir_span_if_local(def_id)
352        {
353            let name = self.tcx.item_name(def_id);
354            let kind = self.tcx.def_kind(def_id);
355            if let DefKind::Ctor(of, CtorKind::Fn) = kind {
356                err.span_label(
357                    sp,
358                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{1}` defines {0} constructor here, which should be called",
                match of {
                    CtorOf::Struct => "a struct",
                    CtorOf::Variant => "an enum variant",
                }, name))
    })format!(
359                        "`{name}` defines {} constructor here, which should be called",
360                        match of {
361                            CtorOf::Struct => "a struct",
362                            CtorOf::Variant => "an enum variant",
363                        }
364                    ),
365                );
366            } else {
367                let descr = self.tcx.def_kind_descr(kind, def_id);
368                err.span_label(sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}` defined here", descr,
                name))
    })format!("{descr} `{name}` defined here"));
369            }
370            return true;
371        }
372
373        if self.suggest_cast(err, expr, found, expected, expected_ty_expr) {
374            return true;
375        }
376
377        if !methods.is_empty() {
378            let mut suggestions = methods
379                .iter()
380                .filter_map(|conversion_method| {
381                    let conversion_method_name = conversion_method.name();
382                    let receiver_method_ident = expr.method_ident();
383                    if let Some(method_ident) = receiver_method_ident
384                        && method_ident.name == conversion_method_name
385                    {
386                        return None; // do not suggest code that is already there (#53348)
387                    }
388
389                    let method_call_list = [sym::to_vec, sym::to_string];
390                    let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
391                        && receiver_method.ident.name == sym::clone
392                        && method_call_list.contains(&conversion_method_name)
393                    // If receiver is `.clone()` and found type has one of those methods,
394                    // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
395                    // to an owned type (`Vec` or `String`). These conversions clone internally,
396                    // so we remove the user's `clone` call.
397                    {
398                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(receiver_method.ident.span, conversion_method_name.to_string())]))vec![(receiver_method.ident.span, conversion_method_name.to_string())]
399                    } else if self.precedence(expr) < ExprPrecedence::Unambiguous {
400                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_lo(), "(".to_string()),
                (expr.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(").{0}()",
                                    conversion_method_name))
                        }))]))vec![
401                            (expr.span.shrink_to_lo(), "(".to_string()),
402                            (expr.span.shrink_to_hi(), format!(").{}()", conversion_method_name)),
403                        ]
404                    } else {
405                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(".{0}()",
                                    conversion_method_name))
                        }))]))vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method_name))]
406                    };
407                    let struct_pat_shorthand_field =
408                        self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr);
409                    if let Some(name) = struct_pat_shorthand_field {
410                        sugg.insert(0, (expr.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", name))
    })format!("{name}: ")));
411                    }
412                    Some(sugg)
413                })
414                .peekable();
415            if suggestions.peek().is_some() {
416                err.multipart_suggestions(
417                    "try using a conversion method",
418                    suggestions,
419                    Applicability::MaybeIncorrect,
420                );
421                return true;
422            }
423        }
424
425        if let Some((found_ty_inner, expected_ty_inner, error_tys)) =
426            self.deconstruct_option_or_result(found, expected)
427            && let ty::Ref(_, peeled, hir::Mutability::Not) = *expected_ty_inner.kind()
428        {
429            // Suggest removing any stray borrows (unless there's macro shenanigans involved).
430            let inner_expr = expr.peel_borrows();
431            if !inner_expr.span.eq_ctxt(expr.span) {
432                return false;
433            }
434            let borrow_removal_span = if inner_expr.hir_id == expr.hir_id {
435                None
436            } else {
437                Some(expr.span.shrink_to_lo().until(inner_expr.span))
438            };
439            // Given `Result<_, E>`, check our expected ty is `Result<_, &E>` for
440            // `as_ref` and `as_deref` compatibility.
441            let error_tys_equate_as_ref = error_tys.is_none_or(|(found, expected)| {
442                self.can_eq(
443                    self.param_env,
444                    Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, found),
445                    expected,
446                )
447            });
448
449            let prefix_wrap = |sugg: &str| {
450                if let Some(name) = self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
451                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}{1}", name, sugg))
    })format!(": {}{}", name, sugg)
452                } else {
453                    sugg.to_string()
454                }
455            };
456
457            // FIXME: This could/should be extended to suggest `as_mut` and `as_deref_mut`,
458            // but those checks need to be a bit more delicate and the benefit is diminishing.
459            if self.can_eq(self.param_env, found_ty_inner, peeled) && error_tys_equate_as_ref {
460                let sugg = prefix_wrap(".as_ref()");
461                err.subdiagnostic(errors::SuggestConvertViaMethod {
462                    span: expr.span.shrink_to_hi(),
463                    sugg,
464                    expected,
465                    found,
466                    borrow_removal_span,
467                });
468                return true;
469            } else if let ty::Ref(_, peeled_found_ty, _) = found_ty_inner.kind()
470                && let ty::Adt(adt, _) = peeled_found_ty.peel_refs().kind()
471                && self.tcx.is_lang_item(adt.did(), LangItem::String)
472                && peeled.is_str()
473                // `Result::map`, conversely, does not take ref of the error type.
474                && error_tys.is_none_or(|(found, expected)| {
475                    self.can_eq(self.param_env, found, expected)
476                })
477            {
478                let sugg = prefix_wrap(".map(|x| x.as_str())");
479                err.span_suggestion_verbose(
480                    expr.span.shrink_to_hi(),
481                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("try converting the passed type into a `&str`"))msg!("try converting the passed type into a `&str`"),
482                    sugg,
483                    Applicability::MachineApplicable,
484                );
485                return true;
486            } else {
487                if !error_tys_equate_as_ref {
488                    return false;
489                }
490                let mut steps = self.autoderef(expr.span, found_ty_inner).silence_errors();
491                if let Some((deref_ty, _)) = steps.nth(1)
492                    && self.can_eq(self.param_env, deref_ty, peeled)
493                {
494                    let sugg = prefix_wrap(".as_deref()");
495                    err.subdiagnostic(errors::SuggestConvertViaMethod {
496                        span: expr.span.shrink_to_hi(),
497                        sugg,
498                        expected,
499                        found,
500                        borrow_removal_span,
501                    });
502                    return true;
503                }
504                for (deref_ty, n_step) in steps {
505                    if self.can_eq(self.param_env, deref_ty, peeled) {
506                        let explicit_deref = "*".repeat(n_step);
507                        let sugg = prefix_wrap(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".map(|v| &{0}v)", explicit_deref))
    })format!(".map(|v| &{explicit_deref}v)"));
508                        err.subdiagnostic(errors::SuggestConvertViaMethod {
509                            span: expr.span.shrink_to_hi(),
510                            sugg,
511                            expected,
512                            found,
513                            borrow_removal_span,
514                        });
515                        return true;
516                    }
517                }
518            }
519        }
520
521        false
522    }
523
524    /// If `ty` is `Option<T>`, returns `T, T, None`.
525    /// If `ty` is `Result<T, E>`, returns `T, T, Some(E, E)`.
526    /// Otherwise, returns `None`.
527    fn deconstruct_option_or_result(
528        &self,
529        found_ty: Ty<'tcx>,
530        expected_ty: Ty<'tcx>,
531    ) -> Option<(Ty<'tcx>, Ty<'tcx>, Option<(Ty<'tcx>, Ty<'tcx>)>)> {
532        let ty::Adt(found_adt, found_args) = found_ty.peel_refs().kind() else {
533            return None;
534        };
535        let ty::Adt(expected_adt, expected_args) = expected_ty.kind() else {
536            return None;
537        };
538        if self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
539            && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
540        {
541            Some((found_args.type_at(0), expected_args.type_at(0), None))
542        } else if self.tcx.is_diagnostic_item(sym::Result, found_adt.did())
543            && self.tcx.is_diagnostic_item(sym::Result, expected_adt.did())
544        {
545            Some((
546                found_args.type_at(0),
547                expected_args.type_at(0),
548                Some((found_args.type_at(1), expected_args.type_at(1))),
549            ))
550        } else {
551            None
552        }
553    }
554
555    /// When encountering the expected boxed value allocated in the stack, suggest allocating it
556    /// in the heap by calling `Box::new()`.
557    pub(in super::super) fn suggest_boxing_when_appropriate(
558        &self,
559        err: &mut Diag<'_>,
560        span: Span,
561        hir_id: HirId,
562        expected: Ty<'tcx>,
563        found: Ty<'tcx>,
564    ) -> bool {
565        // Do not suggest `Box::new` in const context.
566        if self.tcx.hir_is_inside_const_context(hir_id) || !expected.is_box() || found.is_box() {
567            return false;
568        }
569        if self.may_coerce(Ty::new_box(self.tcx, found), expected) {
570            let suggest_boxing = match *found.kind() {
571                ty::Tuple(tuple) if tuple.is_empty() => {
572                    errors::SuggestBoxing::Unit { start: span.shrink_to_lo(), end: span }
573                }
574                ty::Coroutine(def_id, ..)
575                    if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.coroutine_kind(def_id)
    {
    Some(CoroutineKind::Desugared(CoroutineDesugaring::Async,
        CoroutineSource::Closure)) => true,
    _ => false,
}matches!(
576                        self.tcx.coroutine_kind(def_id),
577                        Some(CoroutineKind::Desugared(
578                            CoroutineDesugaring::Async,
579                            CoroutineSource::Closure
580                        ))
581                    ) =>
582                {
583                    errors::SuggestBoxing::AsyncBody
584                }
585                _ if let Node::ExprField(expr_field) = self.tcx.parent_hir_node(hir_id)
586                    && expr_field.is_shorthand =>
587                {
588                    errors::SuggestBoxing::ExprFieldShorthand {
589                        start: span.shrink_to_lo(),
590                        end: span.shrink_to_hi(),
591                        ident: expr_field.ident,
592                    }
593                }
594                _ => errors::SuggestBoxing::Other {
595                    start: span.shrink_to_lo(),
596                    end: span.shrink_to_hi(),
597                },
598            };
599            err.subdiagnostic(suggest_boxing);
600
601            true
602        } else {
603            false
604        }
605    }
606
607    /// When encountering a closure that captures variables, where a FnPtr is expected,
608    /// suggest a non-capturing closure
609    pub(in super::super) fn suggest_no_capture_closure(
610        &self,
611        err: &mut Diag<'_>,
612        expected: Ty<'tcx>,
613        found: Ty<'tcx>,
614    ) -> bool {
615        if let (ty::FnPtr(..), ty::Closure(def_id, _)) = (expected.kind(), found.kind())
616            && let Some(upvars) = self.tcx.upvars_mentioned(*def_id)
617        {
618            // Report upto four upvars being captured to reduce the amount error messages
619            // reported back to the user.
620            let spans_and_labels = upvars
621                .iter()
622                .take(4)
623                .map(|(var_hir_id, upvar)| {
624                    let var_name = self.tcx.hir_name(*var_hir_id).to_string();
625                    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` captured here", var_name))
    })format!("`{var_name}` captured here");
626                    (upvar.span, msg)
627                })
628                .collect::<Vec<_>>();
629
630            let mut multi_span: MultiSpan =
631                spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
632            for (sp, label) in spans_and_labels {
633                multi_span.push_span_label(sp, label);
634            }
635            err.span_note(
636                multi_span,
637                "closures can only be coerced to `fn` types if they do not capture any variables",
638            );
639            return true;
640        }
641        false
642    }
643
644    /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
645    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("suggest_calling_boxed_future_when_appropriate",
                                    "rustc_hir_typeck::fn_ctxt::suggestions",
                                    ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(645u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["expr", "expected",
                                                    "found"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&found)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if self.tcx.hir_is_inside_const_context(expr.hir_id) {
                return false;
            }
            let pin_did = self.tcx.lang_items().pin_type();
            if pin_did.is_none() ||
                    self.tcx.lang_items().owned_box().is_none() {
                return false;
            }
            let box_found = Ty::new_box(self.tcx, found);
            let Some(pin_box_found) =
                Ty::new_lang_item(self.tcx, box_found,
                    LangItem::Pin) else { return false; };
            let Some(pin_found) =
                Ty::new_lang_item(self.tcx, found,
                    LangItem::Pin) else { return false; };
            match expected.kind() {
                ty::Adt(def, _) if Some(def.did()) == pin_did => {
                    if self.may_coerce(pin_box_found, expected) {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:674",
                                                "rustc_hir_typeck::fn_ctxt::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(674u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("can coerce {0:?} to {1:?}, suggesting Box::pin",
                                                                            pin_box_found, expected) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        match found.kind() {
                            ty::Adt(def, _) if def.is_box() => {
                                err.help("use `Box::pin`");
                            }
                            _ => {
                                let prefix =
                                    if let Some(name) =
                                            self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr)
                                        {
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("{0}: ", name))
                                            })
                                    } else { String::new() };
                                let suggestion =
                                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                            [(expr.span.shrink_to_lo(),
                                                        ::alloc::__export::must_use({
                                                                ::alloc::fmt::format(format_args!("{0}Box::pin(", prefix))
                                                            })), (expr.span.shrink_to_hi(), ")".to_string())]));
                                err.multipart_suggestion("you need to pin and box this expression",
                                    suggestion, Applicability::MaybeIncorrect);
                            }
                        }
                        true
                    } else if self.may_coerce(pin_found, expected) {
                        match found.kind() {
                            ty::Adt(def, _) if def.is_box() => {
                                err.help("use `Box::pin`");
                                true
                            }
                            _ => false,
                        }
                    } else { false }
                }
                ty::Adt(def, _) if
                    def.is_box() && self.may_coerce(box_found, expected) => {
                    let Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), ..
                            }) =
                        self.tcx.parent_hir_node(expr.hir_id) else {
                            return false;
                        };
                    match fn_name.kind {
                        ExprKind::Path(QPath::TypeRelative(hir::Ty {
                            kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty,
                                .. })), .. }, method)) if
                            recv_ty.opt_def_id() == pin_did &&
                                method.ident.name == sym::new => {
                            err.span_suggestion(fn_name.span,
                                "use `Box::pin` to pin and box this expression", "Box::pin",
                                Applicability::MachineApplicable);
                            true
                        }
                        _ => false,
                    }
                }
                _ => false,
            }
        }
    }
}#[instrument(skip(self, err))]
646    pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
647        &self,
648        err: &mut Diag<'_>,
649        expr: &hir::Expr<'_>,
650        expected: Ty<'tcx>,
651        found: Ty<'tcx>,
652    ) -> bool {
653        // Handle #68197.
654
655        if self.tcx.hir_is_inside_const_context(expr.hir_id) {
656            // Do not suggest `Box::new` in const context.
657            return false;
658        }
659        let pin_did = self.tcx.lang_items().pin_type();
660        // This guards the `new_box` below.
661        if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
662            return false;
663        }
664        let box_found = Ty::new_box(self.tcx, found);
665        let Some(pin_box_found) = Ty::new_lang_item(self.tcx, box_found, LangItem::Pin) else {
666            return false;
667        };
668        let Some(pin_found) = Ty::new_lang_item(self.tcx, found, LangItem::Pin) else {
669            return false;
670        };
671        match expected.kind() {
672            ty::Adt(def, _) if Some(def.did()) == pin_did => {
673                if self.may_coerce(pin_box_found, expected) {
674                    debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
675                    match found.kind() {
676                        ty::Adt(def, _) if def.is_box() => {
677                            err.help("use `Box::pin`");
678                        }
679                        _ => {
680                            let prefix = if let Some(name) =
681                                self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr)
682                            {
683                                format!("{}: ", name)
684                            } else {
685                                String::new()
686                            };
687                            let suggestion = vec![
688                                (expr.span.shrink_to_lo(), format!("{prefix}Box::pin(")),
689                                (expr.span.shrink_to_hi(), ")".to_string()),
690                            ];
691                            err.multipart_suggestion(
692                                "you need to pin and box this expression",
693                                suggestion,
694                                Applicability::MaybeIncorrect,
695                            );
696                        }
697                    }
698                    true
699                } else if self.may_coerce(pin_found, expected) {
700                    match found.kind() {
701                        ty::Adt(def, _) if def.is_box() => {
702                            err.help("use `Box::pin`");
703                            true
704                        }
705                        _ => false,
706                    }
707                } else {
708                    false
709                }
710            }
711            ty::Adt(def, _) if def.is_box() && self.may_coerce(box_found, expected) => {
712                // Check if the parent expression is a call to Pin::new. If it
713                // is and we were expecting a Box, ergo Pin<Box<expected>>, we
714                // can suggest Box::pin.
715                let Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. }) =
716                    self.tcx.parent_hir_node(expr.hir_id)
717                else {
718                    return false;
719                };
720                match fn_name.kind {
721                    ExprKind::Path(QPath::TypeRelative(
722                        hir::Ty {
723                            kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
724                            ..
725                        },
726                        method,
727                    )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
728                        err.span_suggestion(
729                            fn_name.span,
730                            "use `Box::pin` to pin and box this expression",
731                            "Box::pin",
732                            Applicability::MachineApplicable,
733                        );
734                        true
735                    }
736                    _ => false,
737                }
738            }
739            _ => false,
740        }
741    }
742
743    /// A common error is to forget to add a semicolon at the end of a block, e.g.,
744    ///
745    /// ```compile_fail,E0308
746    /// # fn bar_that_returns_u32() -> u32 { 4 }
747    /// fn foo() {
748    ///     bar_that_returns_u32()
749    /// }
750    /// ```
751    ///
752    /// This routine checks if the return expression in a block would make sense on its own as a
753    /// statement and the return type has been left as default or has been specified as `()`. If so,
754    /// it suggests adding a semicolon.
755    ///
756    /// If the expression is the expression of a closure without block (`|| expr`), a
757    /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
758    pub(crate) fn suggest_missing_semicolon(
759        &self,
760        err: &mut Diag<'_>,
761        expression: &'tcx hir::Expr<'tcx>,
762        expected: Ty<'tcx>,
763        needs_block: bool,
764        parent_is_closure: bool,
765    ) {
766        if !expected.is_unit() {
767            return;
768        }
769        // `BlockTailExpression` only relevant if the tail expr would be
770        // useful on its own.
771        match expression.kind {
772            ExprKind::Call(..)
773            | ExprKind::MethodCall(..)
774            | ExprKind::Loop(..)
775            | ExprKind::If(..)
776            | ExprKind::Match(..)
777            | ExprKind::Block(..)
778                if expression.can_have_side_effects()
779                    // If the expression is from an external macro, then do not suggest
780                    // adding a semicolon, because there's nowhere to put it.
781                    // See issue #81943.
782                    && !expression.span.in_external_macro(self.tcx.sess.source_map()) =>
783            {
784                if needs_block {
785                    err.multipart_suggestion(
786                        "consider using a semicolon here",
787                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expression.span.shrink_to_lo(), "{ ".to_owned()),
                (expression.span.shrink_to_hi(), "; }".to_owned())]))vec![
788                            (expression.span.shrink_to_lo(), "{ ".to_owned()),
789                            (expression.span.shrink_to_hi(), "; }".to_owned()),
790                        ],
791                        Applicability::MachineApplicable,
792                    );
793                } else if let hir::Node::Block(block) = self.tcx.parent_hir_node(expression.hir_id)
794                    && let hir::Node::Expr(expr) = self.tcx.parent_hir_node(block.hir_id)
795                    && let hir::Node::Expr(if_expr) = self.tcx.parent_hir_node(expr.hir_id)
796                    && let hir::ExprKind::If(_cond, _then, Some(_else)) = if_expr.kind
797                    && let hir::Node::Stmt(stmt) = self.tcx.parent_hir_node(if_expr.hir_id)
798                    && let hir::StmtKind::Expr(_) = stmt.kind
799                    && self.is_next_stmt_expr_continuation(stmt.hir_id)
800                {
801                    err.multipart_suggestion(
802                        "parentheses are required to parse this as an expression",
803                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(stmt.span.shrink_to_lo(), "(".to_string()),
                (stmt.span.shrink_to_hi(), ")".to_string())]))vec![
804                            (stmt.span.shrink_to_lo(), "(".to_string()),
805                            (stmt.span.shrink_to_hi(), ")".to_string()),
806                        ],
807                        Applicability::MachineApplicable,
808                    );
809                } else {
810                    err.span_suggestion(
811                        expression.span.shrink_to_hi(),
812                        "consider using a semicolon here",
813                        ";",
814                        Applicability::MachineApplicable,
815                    );
816                }
817            }
818            ExprKind::Path(..) | ExprKind::Lit(_)
819                if parent_is_closure
820                    && !expression.span.in_external_macro(self.tcx.sess.source_map()) =>
821            {
822                err.span_suggestion_verbose(
823                    expression.span.shrink_to_lo(),
824                    "consider ignoring the value",
825                    "_ = ",
826                    Applicability::MachineApplicable,
827                );
828            }
829            _ => {
830                if let hir::Node::Block(block) = self.tcx.parent_hir_node(expression.hir_id)
831                    && let hir::Node::Expr(expr) = self.tcx.parent_hir_node(block.hir_id)
832                    && let hir::Node::Expr(if_expr) = self.tcx.parent_hir_node(expr.hir_id)
833                    && let hir::ExprKind::If(_cond, _then, Some(_else)) = if_expr.kind
834                    && let hir::Node::Stmt(stmt) = self.tcx.parent_hir_node(if_expr.hir_id)
835                    && let hir::StmtKind::Expr(_) = stmt.kind
836                    && self.is_next_stmt_expr_continuation(stmt.hir_id)
837                {
838                    // The error is pointing at an arm of an if-expression, and we want to get the
839                    // `Span` of the whole if-expression for the suggestion. This only works for a
840                    // single level of nesting, which is fine.
841                    // We have something like `if true { false } else { true } && true`. Suggest
842                    // wrapping in parentheses. We find the statement or expression following the
843                    // `if` (`&& true`) and see if it is something that can reasonably be
844                    // interpreted as a binop following an expression.
845                    err.multipart_suggestion(
846                        "parentheses are required to parse this as an expression",
847                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(stmt.span.shrink_to_lo(), "(".to_string()),
                (stmt.span.shrink_to_hi(), ")".to_string())]))vec![
848                            (stmt.span.shrink_to_lo(), "(".to_string()),
849                            (stmt.span.shrink_to_hi(), ")".to_string()),
850                        ],
851                        Applicability::MachineApplicable,
852                    );
853                }
854            }
855        }
856    }
857
858    pub(crate) fn is_next_stmt_expr_continuation(&self, hir_id: HirId) -> bool {
859        if let hir::Node::Block(b) = self.tcx.parent_hir_node(hir_id)
860            && let mut stmts = b.stmts.iter().skip_while(|s| s.hir_id != hir_id)
861            && let Some(_) = stmts.next() // The statement the statement that was passed in
862            && let Some(next) = match (stmts.next(), b.expr) { // The following statement
863                (Some(next), _) => match next.kind {
864                    hir::StmtKind::Expr(next) | hir::StmtKind::Semi(next) => Some(next),
865                    _ => None,
866                },
867                (None, Some(next)) => Some(next),
868                _ => None,
869            }
870            && let hir::ExprKind::AddrOf(..) // prev_stmt && next
871                | hir::ExprKind::Unary(..) // prev_stmt * next
872                | hir::ExprKind::Err(_) = next.kind
873        // prev_stmt + next
874        {
875            true
876        } else {
877            false
878        }
879    }
880
881    /// A possible error is to forget to add a return type that is needed:
882    ///
883    /// ```compile_fail,E0308
884    /// # fn bar_that_returns_u32() -> u32 { 4 }
885    /// fn foo() {
886    ///     bar_that_returns_u32()
887    /// }
888    /// ```
889    ///
890    /// This routine checks if the return type is left as default, the method is not part of an
891    /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
892    /// type.
893    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("suggest_missing_return_type",
                                    "rustc_hir_typeck::fn_ctxt::suggestions",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(893u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["fn_decl",
                                                    "expected", "found", "fn_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&found)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(hir::CoroutineKind::Desugared(_,
                    hir::CoroutineSource::Block)) =
                    self.tcx.coroutine_kind(fn_id) {
                return false;
            }
            let found =
                self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
            match &fn_decl.output {
                &hir::FnRetTy::DefaultReturn(_) if
                    self.tcx.is_closure_like(fn_id.to_def_id()) => {}
                &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
                    if !self.can_add_return_type(fn_id) {
                        err.subdiagnostic(errors::ExpectedReturnTypeLabel::Unit {
                                span,
                            });
                    } else if let Some(found) =
                            found.make_suggestable(self.tcx, false, None) {
                        err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
                                span,
                                found: found.to_string(),
                            });
                    } else if let Some(sugg) =
                            suggest_impl_trait(self, self.param_env, found) {
                        err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
                                span,
                                found: sugg,
                            });
                    } else {
                        err.subdiagnostic(errors::AddReturnTypeSuggestion::MissingHere {
                                span,
                            });
                    }
                    return true;
                }
                hir::FnRetTy::Return(hir_ty) => {
                    if let hir::TyKind::OpaqueDef(op_ty, ..) = hir_ty.kind &&
                                        let [hir::GenericBound::Trait(trait_ref)] = op_ty.bounds &&
                                    let Some(hir::PathSegment { args: Some(generic_args), .. })
                                        = trait_ref.trait_ref.path.segments.last() &&
                                let [constraint] = generic_args.constraints &&
                            let Some(ty) = constraint.ty() {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:944",
                                                "rustc_hir_typeck::fn_ctxt::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(944u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&["found"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&found) as
                                                                    &dyn Value))])
                                    });
                            } else { ; }
                        };
                        if found.is_suggestable(self.tcx, false) {
                            if ty.span.is_empty() {
                                err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
                                        span: ty.span,
                                        found: found.to_string(),
                                    });
                                return true;
                            } else {
                                err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
                                        span: ty.span,
                                        expected,
                                    });
                            }
                        }
                    } else {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:962",
                                                "rustc_hir_typeck::fn_ctxt::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(962u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&["message", "hir_ty"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("return type")
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&hir_ty) as
                                                                    &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let ty = self.lowerer().lower_ty(hir_ty);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:964",
                                                "rustc_hir_typeck::fn_ctxt::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(964u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&["message", "ty"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("return type (lowered)")
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&ty) as
                                                                    &dyn Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:965",
                                                "rustc_hir_typeck::fn_ctxt::suggestions",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
                                                ::tracing_core::__macro_support::Option::Some(965u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
                                                ::tracing_core::field::FieldSet::new(&["message",
                                                                "expected"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("expected type")
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&expected)
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let bound_vars =
                            self.tcx.late_bound_vars(self.tcx.local_def_id_to_hir_id(fn_id));
                        let ty = Binder::bind_with_vars(ty, bound_vars);
                        let ty = self.normalize(hir_ty.span, ty);
                        let ty = self.tcx.instantiate_bound_regions_with_erased(ty);
                        if self.may_coerce(expected, ty) {
                            err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
                                    span: hir_ty.span,
                                    expected,
                                });
                            self.try_suggest_return_impl_trait(err, expected, found,
                                fn_id);
                            self.try_note_caller_chooses_ty_for_ty_param(err, expected,
                                found);
                            return true;
                        }
                    }
                }
                _ => {}
            }
            false
        }
    }
}#[instrument(level = "trace", skip(self, err))]
894    pub(in super::super) fn suggest_missing_return_type(
895        &self,
896        err: &mut Diag<'_>,
897        fn_decl: &hir::FnDecl<'tcx>,
898        expected: Ty<'tcx>,
899        found: Ty<'tcx>,
900        fn_id: LocalDefId,
901    ) -> bool {
902        // Can't suggest `->` on a block-like coroutine
903        if let Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Block)) =
904            self.tcx.coroutine_kind(fn_id)
905        {
906            return false;
907        }
908
909        let found =
910            self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
911        // Only suggest changing the return type for methods that
912        // haven't set a return type at all (and aren't `fn main()`, impl or closure).
913        match &fn_decl.output {
914            // For closure with default returns, don't suggest adding return type
915            &hir::FnRetTy::DefaultReturn(_) if self.tcx.is_closure_like(fn_id.to_def_id()) => {}
916            &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
917                if !self.can_add_return_type(fn_id) {
918                    err.subdiagnostic(errors::ExpectedReturnTypeLabel::Unit { span });
919                } else if let Some(found) = found.make_suggestable(self.tcx, false, None) {
920                    err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
921                        span,
922                        found: found.to_string(),
923                    });
924                } else if let Some(sugg) = suggest_impl_trait(self, self.param_env, found) {
925                    err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { span, found: sugg });
926                } else {
927                    // FIXME: if `found` could be `impl Iterator` we should suggest that.
928                    err.subdiagnostic(errors::AddReturnTypeSuggestion::MissingHere { span });
929                }
930
931                return true;
932            }
933            hir::FnRetTy::Return(hir_ty) => {
934                if let hir::TyKind::OpaqueDef(op_ty, ..) = hir_ty.kind
935                    // FIXME: account for RPITIT.
936                    && let [hir::GenericBound::Trait(trait_ref)] = op_ty.bounds
937                    && let Some(hir::PathSegment { args: Some(generic_args), .. }) =
938                        trait_ref.trait_ref.path.segments.last()
939                    && let [constraint] = generic_args.constraints
940                    && let Some(ty) = constraint.ty()
941                {
942                    // Check if async function's return type was omitted.
943                    // Don't emit suggestions if the found type is `impl Future<...>`.
944                    debug!(?found);
945                    if found.is_suggestable(self.tcx, false) {
946                        if ty.span.is_empty() {
947                            err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
948                                span: ty.span,
949                                found: found.to_string(),
950                            });
951                            return true;
952                        } else {
953                            err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
954                                span: ty.span,
955                                expected,
956                            });
957                        }
958                    }
959                } else {
960                    // Only point to return type if the expected type is the return type, as if they
961                    // are not, the expectation must have been caused by something else.
962                    debug!(?hir_ty, "return type");
963                    let ty = self.lowerer().lower_ty(hir_ty);
964                    debug!(?ty, "return type (lowered)");
965                    debug!(?expected, "expected type");
966                    let bound_vars =
967                        self.tcx.late_bound_vars(self.tcx.local_def_id_to_hir_id(fn_id));
968                    let ty = Binder::bind_with_vars(ty, bound_vars);
969                    let ty = self.normalize(hir_ty.span, ty);
970                    let ty = self.tcx.instantiate_bound_regions_with_erased(ty);
971                    if self.may_coerce(expected, ty) {
972                        err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
973                            span: hir_ty.span,
974                            expected,
975                        });
976                        self.try_suggest_return_impl_trait(err, expected, found, fn_id);
977                        self.try_note_caller_chooses_ty_for_ty_param(err, expected, found);
978                        return true;
979                    }
980                }
981            }
982            _ => {}
983        }
984        false
985    }
986
987    /// Checks whether we can add a return type to a function.
988    /// Assumes given function doesn't have a explicit return type.
989    fn can_add_return_type(&self, fn_id: LocalDefId) -> bool {
990        match self.tcx.hir_node_by_def_id(fn_id) {
991            Node::Item(item) => {
992                let (ident, _, _, _) = item.expect_fn();
993                // This is less than ideal, it will not suggest a return type span on any
994                // method called `main`, regardless of whether it is actually the entry point,
995                // but it will still present it as the reason for the expected type.
996                ident.name != sym::main
997            }
998            Node::ImplItem(item) => {
999                // If it doesn't impl a trait, we can add a return type
1000                let Node::Item(&hir::Item {
1001                    kind: hir::ItemKind::Impl(hir::Impl { of_trait, .. }),
1002                    ..
1003                }) = self.tcx.parent_hir_node(item.hir_id())
1004                else {
1005                    ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1006                };
1007
1008                of_trait.is_none()
1009            }
1010            _ => true,
1011        }
1012    }
1013
1014    fn try_note_caller_chooses_ty_for_ty_param(
1015        &self,
1016        diag: &mut Diag<'_>,
1017        expected: Ty<'tcx>,
1018        found: Ty<'tcx>,
1019    ) {
1020        // Only show the note if:
1021        // 1. `expected` ty is a type parameter;
1022        // 2. The `expected` type parameter does *not* occur in the return expression type. This can
1023        //    happen for e.g. `fn foo<T>(t: &T) -> T { t }`, where `expected` is `T` but `found` is
1024        //    `&T`. Saying "the caller chooses a type for `T` which can be different from `&T`" is
1025        //    "well duh" and is only confusing and not helpful.
1026        let ty::Param(expected_ty_as_param) = expected.kind() else {
1027            return;
1028        };
1029
1030        if found.contains(expected) {
1031            return;
1032        }
1033
1034        diag.subdiagnostic(errors::NoteCallerChoosesTyForTyParam {
1035            ty_param_name: expected_ty_as_param.name,
1036            found_ty: found,
1037        });
1038    }
1039
1040    /// check whether the return type is a generic type with a trait bound
1041    /// only suggest this if the generic param is not present in the arguments
1042    /// if this is true, hint them towards changing the return type to `impl Trait`
1043    /// ```compile_fail,E0308
1044    /// fn cant_name_it<T: Fn() -> u32>() -> T {
1045    ///     || 3
1046    /// }
1047    /// ```
1048    fn try_suggest_return_impl_trait(
1049        &self,
1050        err: &mut Diag<'_>,
1051        expected: Ty<'tcx>,
1052        found: Ty<'tcx>,
1053        fn_id: LocalDefId,
1054    ) {
1055        // Only apply the suggestion if:
1056        //  - the return type is a generic parameter
1057        //  - the generic param is not used as a fn param
1058        //  - the generic param has at least one bound
1059        //  - the generic param doesn't appear in any other bounds where it's not the Self type
1060        // Suggest:
1061        //  - Changing the return type to be `impl <all bounds>`
1062
1063        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:1063",
                        "rustc_hir_typeck::fn_ctxt::suggestions",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
                        ::tracing_core::__macro_support::Option::Some(1063u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("try_suggest_return_impl_trait, expected = {0:?}, found = {1:?}",
                                                    expected, found) as &dyn Value))])
            });
    } else { ; }
};debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
1064
1065        let ty::Param(expected_ty_as_param) = expected.kind() else { return };
1066
1067        let fn_node = self.tcx.hir_node_by_def_id(fn_id);
1068
1069        let hir::Node::Item(hir::Item {
1070            kind:
1071                hir::ItemKind::Fn {
1072                    sig:
1073                        hir::FnSig {
1074                            decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. },
1075                            ..
1076                        },
1077                    generics: hir::Generics { params, predicates, .. },
1078                    ..
1079                },
1080            ..
1081        }) = fn_node
1082        else {
1083            return;
1084        };
1085
1086        if params.get(expected_ty_as_param.index as usize).is_none() {
1087            return;
1088        };
1089
1090        // get all where BoundPredicates here, because they are used in two cases below
1091        let where_predicates = predicates
1092            .iter()
1093            .filter_map(|p| match p.kind {
1094                WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1095                    bounds,
1096                    bounded_ty,
1097                    ..
1098                }) => {
1099                    // FIXME: Maybe these calls to `lower_ty` can be removed (and the ones below)
1100                    let ty = self.lowerer().lower_ty(bounded_ty);
1101                    Some((ty, bounds))
1102                }
1103                _ => None,
1104            })
1105            .map(|(ty, bounds)| match ty.kind() {
1106                ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
1107                // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
1108                _ => match ty.contains(expected) {
1109                    true => Err(()),
1110                    false => Ok(None),
1111                },
1112            })
1113            .collect::<Result<Vec<_>, _>>();
1114
1115        let Ok(where_predicates) = where_predicates else { return };
1116
1117        // now get all predicates in the same types as the where bounds, so we can chain them
1118        let predicates_from_where =
1119            where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
1120
1121        // extract all bounds from the source code using their spans
1122        let all_matching_bounds_strs = predicates_from_where
1123            .filter_map(|bound| match bound {
1124                GenericBound::Trait(_) => {
1125                    self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
1126                }
1127                _ => None,
1128            })
1129            .collect::<Vec<String>>();
1130
1131        if all_matching_bounds_strs.is_empty() {
1132            return;
1133        }
1134
1135        let all_bounds_str = all_matching_bounds_strs.join(" + ");
1136
1137        let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
1138                let ty = self.lowerer().lower_ty( param);
1139                #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param
        => true,
    _ => false,
}matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
1140            });
1141
1142        if ty_param_used_in_fn_params {
1143            return;
1144        }
1145
1146        err.span_suggestion(
1147            fn_return.span(),
1148            "consider using an impl return type",
1149            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("impl {0}", all_bounds_str))
    })format!("impl {all_bounds_str}"),
1150            Applicability::MaybeIncorrect,
1151        );
1152    }
1153
1154    pub(in super::super) fn suggest_missing_break_or_return_expr(
1155        &self,
1156        err: &mut Diag<'_>,
1157        expr: &'tcx hir::Expr<'tcx>,
1158        fn_decl: &hir::FnDecl<'tcx>,
1159        expected: Ty<'tcx>,
1160        found: Ty<'tcx>,
1161        id: HirId,
1162        fn_id: LocalDefId,
1163    ) {
1164        if !expected.is_unit() {
1165            return;
1166        }
1167        let found = self.resolve_vars_if_possible(found);
1168
1169        let innermost_loop = if self.is_loop(id) {
1170            Some(self.tcx.hir_node(id))
1171        } else {
1172            self.tcx
1173                .hir_parent_iter(id)
1174                .take_while(|(_, node)| {
1175                    // look at parents until we find the first body owner
1176                    node.body_id().is_none()
1177                })
1178                .find_map(|(parent_id, node)| self.is_loop(parent_id).then_some(node))
1179        };
1180        let can_break_with_value = innermost_loop.is_some_and(|node| {
1181            #[allow(non_exhaustive_omitted_patterns)] match node {
    Node::Expr(Expr { kind: ExprKind::Loop(_, _, LoopSource::Loop, ..), .. })
        => true,
    _ => false,
}matches!(
1182                node,
1183                Node::Expr(Expr { kind: ExprKind::Loop(_, _, LoopSource::Loop, ..), .. })
1184            )
1185        });
1186
1187        let in_local_statement = self.is_local_statement(id)
1188            || self
1189                .tcx
1190                .hir_parent_iter(id)
1191                .any(|(parent_id, _)| self.is_local_statement(parent_id));
1192
1193        if can_break_with_value && in_local_statement {
1194            err.multipart_suggestion(
1195                "you might have meant to break the loop with this value",
1196                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_lo(), "break ".to_string()),
                (expr.span.shrink_to_hi(), ";".to_string())]))vec![
1197                    (expr.span.shrink_to_lo(), "break ".to_string()),
1198                    (expr.span.shrink_to_hi(), ";".to_string()),
1199                ],
1200                Applicability::MaybeIncorrect,
1201            );
1202            return;
1203        }
1204
1205        let scope = self.tcx.hir_parent_iter(id).find(|(_, node)| {
1206            #[allow(non_exhaustive_omitted_patterns)] match node {
    Node::Expr(Expr { kind: ExprKind::Closure(..), .. }) | Node::Item(_) |
        Node::TraitItem(_) | Node::ImplItem(_) => true,
    _ => false,
}matches!(
1207                node,
1208                Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
1209                    | Node::Item(_)
1210                    | Node::TraitItem(_)
1211                    | Node::ImplItem(_)
1212            )
1213        });
1214        let in_closure =
1215            #[allow(non_exhaustive_omitted_patterns)] match scope {
    Some((_, Node::Expr(Expr { kind: ExprKind::Closure(..), .. }))) => true,
    _ => false,
}matches!(scope, Some((_, Node::Expr(Expr { kind: ExprKind::Closure(..), .. }))));
1216
1217        let can_return = match fn_decl.output {
1218            hir::FnRetTy::Return(ty) => {
1219                let ty = self.lowerer().lower_ty(ty);
1220                let bound_vars = self.tcx.late_bound_vars(self.tcx.local_def_id_to_hir_id(fn_id));
1221                let ty = self
1222                    .tcx
1223                    .instantiate_bound_regions_with_erased(Binder::bind_with_vars(ty, bound_vars));
1224                let ty = match self.tcx.asyncness(fn_id) {
1225                    ty::Asyncness::Yes => {
1226                        self.err_ctxt().get_impl_future_output_ty(ty).unwrap_or_else(|| {
1227                            ::rustc_middle::util::bug::span_bug_fmt(fn_decl.output.span(),
    format_args!("failed to get output type of async function"))span_bug!(
1228                                fn_decl.output.span(),
1229                                "failed to get output type of async function"
1230                            )
1231                        })
1232                    }
1233                    ty::Asyncness::No => ty,
1234                };
1235                let ty = self.normalize(expr.span, ty);
1236                self.may_coerce(found, ty)
1237            }
1238            hir::FnRetTy::DefaultReturn(_) if in_closure => {
1239                self.ret_coercion.as_ref().is_some_and(|ret| {
1240                    let ret_ty = ret.borrow().expected_ty();
1241                    self.may_coerce(found, ret_ty)
1242                })
1243            }
1244            _ => false,
1245        };
1246        if can_return
1247            && let Some(span) = expr.span.find_ancestor_inside(
1248                self.tcx.hir_span_with_body(self.tcx.local_def_id_to_hir_id(fn_id)),
1249            )
1250        {
1251            // When the expr is in a match arm's body, we shouldn't add semicolon ';' at the end.
1252            // For example:
1253            // fn mismatch_types() -> i32 {
1254            //     match 1 {
1255            //         x => dbg!(x),
1256            //     }
1257            //     todo!()
1258            // }
1259            // -------------^^^^^^^-
1260            // Don't add semicolon `;` at the end of `dbg!(x)` expr
1261            fn is_in_arm<'tcx>(expr: &'tcx hir::Expr<'tcx>, tcx: TyCtxt<'tcx>) -> bool {
1262                for (_, node) in tcx.hir_parent_iter(expr.hir_id) {
1263                    match node {
1264                        hir::Node::Block(block) => {
1265                            if let Some(ret) = block.expr
1266                                && ret.hir_id == expr.hir_id
1267                            {
1268                                continue;
1269                            }
1270                        }
1271                        hir::Node::Arm(arm) => {
1272                            if let hir::ExprKind::Block(block, _) = arm.body.kind
1273                                && let Some(ret) = block.expr
1274                                && ret.hir_id == expr.hir_id
1275                            {
1276                                return true;
1277                            }
1278                        }
1279                        hir::Node::Expr(e) if let hir::ExprKind::Block(block, _) = e.kind => {
1280                            if let Some(ret) = block.expr
1281                                && ret.hir_id == expr.hir_id
1282                            {
1283                                continue;
1284                            }
1285                        }
1286                        _ => {
1287                            return false;
1288                        }
1289                    }
1290                }
1291
1292                false
1293            }
1294            let mut suggs = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), "return ".to_string())]))vec![(span.shrink_to_lo(), "return ".to_string())];
1295            if !is_in_arm(expr, self.tcx) {
1296                suggs.push((span.shrink_to_hi(), ";".to_string()));
1297            }
1298            err.multipart_suggestion(
1299                "you might have meant to return this value",
1300                suggs,
1301                Applicability::MaybeIncorrect,
1302            );
1303        }
1304    }
1305
1306    pub(in super::super) fn suggest_missing_parentheses(
1307        &self,
1308        err: &mut Diag<'_>,
1309        expr: &hir::Expr<'_>,
1310    ) -> bool {
1311        let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None);
1312        if let Some(sp) = self.tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
1313            // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
1314            err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
1315            true
1316        } else {
1317            false
1318        }
1319    }
1320
1321    /// Given an expression type mismatch, peel any `&` expressions until we get to
1322    /// a block expression, and then suggest replacing the braces with square braces
1323    /// if it was possibly mistaken array syntax.
1324    pub(crate) fn suggest_block_to_brackets_peeling_refs(
1325        &self,
1326        diag: &mut Diag<'_>,
1327        mut expr: &hir::Expr<'_>,
1328        mut expr_ty: Ty<'tcx>,
1329        mut expected_ty: Ty<'tcx>,
1330    ) -> bool {
1331        loop {
1332            match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
1333                (
1334                    hir::ExprKind::AddrOf(_, _, inner_expr),
1335                    ty::Ref(_, inner_expr_ty, _),
1336                    ty::Ref(_, inner_expected_ty, _),
1337                ) => {
1338                    expr = *inner_expr;
1339                    expr_ty = *inner_expr_ty;
1340                    expected_ty = *inner_expected_ty;
1341                }
1342                (hir::ExprKind::Block(blk, _), _, _) => {
1343                    self.suggest_block_to_brackets(diag, blk, expr_ty, expected_ty);
1344                    break true;
1345                }
1346                _ => break false,
1347            }
1348        }
1349    }
1350
1351    pub(crate) fn suggest_clone_for_ref(
1352        &self,
1353        diag: &mut Diag<'_>,
1354        expr: &hir::Expr<'_>,
1355        expr_ty: Ty<'tcx>,
1356        expected_ty: Ty<'tcx>,
1357    ) -> bool {
1358        if let ty::Ref(_, inner_ty, hir::Mutability::Not) = expr_ty.kind()
1359            && let Some(clone_trait_def) = self.tcx.lang_items().clone_trait()
1360            && expected_ty == *inner_ty
1361            && self
1362                .infcx
1363                .type_implements_trait(
1364                    clone_trait_def,
1365                    [self.tcx.erase_and_anonymize_regions(expected_ty)],
1366                    self.param_env,
1367                )
1368                .must_apply_modulo_regions()
1369        {
1370            let suggestion = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1371                Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}.clone()", ident))
    })format!(": {ident}.clone()"),
1372                None => ".clone()".to_string(),
1373            };
1374
1375            let span = expr.span.find_ancestor_not_from_macro().unwrap_or(expr.span).shrink_to_hi();
1376
1377            diag.span_suggestion_verbose(
1378                span,
1379                "consider using clone here",
1380                suggestion,
1381                Applicability::MachineApplicable,
1382            );
1383            return true;
1384        }
1385        false
1386    }
1387
1388    pub(crate) fn suggest_copied_cloned_or_as_ref(
1389        &self,
1390        diag: &mut Diag<'_>,
1391        expr: &hir::Expr<'_>,
1392        expr_ty: Ty<'tcx>,
1393        expected_ty: Ty<'tcx>,
1394    ) -> bool {
1395        let ty::Adt(adt_def, args) = expr_ty.kind() else {
1396            return false;
1397        };
1398        let ty::Adt(expected_adt_def, expected_args) = expected_ty.kind() else {
1399            return false;
1400        };
1401        if adt_def != expected_adt_def {
1402            return false;
1403        }
1404
1405        if Some(adt_def.did()) == self.tcx.get_diagnostic_item(sym::Result)
1406            && self.can_eq(self.param_env, args.type_at(1), expected_args.type_at(1))
1407            || Some(adt_def.did()) == self.tcx.get_diagnostic_item(sym::Option)
1408        {
1409            let expr_inner_ty = args.type_at(0);
1410            let expected_inner_ty = expected_args.type_at(0);
1411            if let &ty::Ref(_, ty, _mutability) = expr_inner_ty.kind()
1412                && self.can_eq(self.param_env, ty, expected_inner_ty)
1413            {
1414                let def_path = self.tcx.def_path_str(adt_def.did());
1415                let span = expr.span.shrink_to_hi();
1416                let subdiag = if self.type_is_copy_modulo_regions(self.param_env, ty) {
1417                    errors::OptionResultRefMismatch::Copied { span, def_path }
1418                } else if self.type_is_clone_modulo_regions(self.param_env, ty) {
1419                    errors::OptionResultRefMismatch::Cloned { span, def_path }
1420                } else {
1421                    return false;
1422                };
1423                diag.subdiagnostic(subdiag);
1424                return true;
1425            }
1426        }
1427
1428        false
1429    }
1430
1431    pub(crate) fn suggest_into(
1432        &self,
1433        diag: &mut Diag<'_>,
1434        expr: &hir::Expr<'_>,
1435        expr_ty: Ty<'tcx>,
1436        expected_ty: Ty<'tcx>,
1437    ) -> bool {
1438        let expr = expr.peel_blocks();
1439
1440        // We have better suggestions for scalar interconversions...
1441        if expr_ty.is_scalar() && expected_ty.is_scalar() {
1442            return false;
1443        }
1444
1445        // Don't suggest turning a block into another type (e.g. `{}.into()`)
1446        if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    hir::ExprKind::Block(..) => true,
    _ => false,
}matches!(expr.kind, hir::ExprKind::Block(..)) {
1447            return false;
1448        }
1449
1450        // We'll later suggest `.as_ref` when noting the type error,
1451        // so skip if we will suggest that instead.
1452        if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1453            return false;
1454        }
1455
1456        if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1457            && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1458                self.tcx,
1459                self.misc(expr.span),
1460                self.param_env,
1461                ty::TraitRef::new(self.tcx, into_def_id, [expr_ty, expected_ty]),
1462            ))
1463            && !expr
1464                .span
1465                .macro_backtrace()
1466                .any(|x| #[allow(non_exhaustive_omitted_patterns)] match x.kind {
    ExpnKind::Macro(MacroKind::Attr | MacroKind::Derive, ..) => true,
    _ => false,
}matches!(x.kind, ExpnKind::Macro(MacroKind::Attr | MacroKind::Derive, ..)))
1467        {
1468            let span = expr
1469                .span
1470                .find_ancestor_not_from_extern_macro(self.tcx.sess.source_map())
1471                .unwrap_or(expr.span);
1472
1473            let mut sugg = if self.precedence(expr) >= ExprPrecedence::Unambiguous {
1474                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_hi(), ".into()".to_owned())]))vec![(span.shrink_to_hi(), ".into()".to_owned())]
1475            } else {
1476                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), "(".to_owned()),
                (span.shrink_to_hi(), ").into()".to_owned())]))vec![
1477                    (span.shrink_to_lo(), "(".to_owned()),
1478                    (span.shrink_to_hi(), ").into()".to_owned()),
1479                ]
1480            };
1481            if let Some(name) = self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1482                sugg.insert(0, (expr.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", name))
    })format!("{}: ", name)));
1483            }
1484            diag.multipart_suggestion(
1485                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("call `Into::into` on this expression to convert `{0}` into `{1}`",
                expr_ty, expected_ty))
    })format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1486                    sugg,
1487                    Applicability::MaybeIncorrect
1488                );
1489            return true;
1490        }
1491
1492        false
1493    }
1494
1495    /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
1496    pub(crate) fn suggest_option_to_bool(
1497        &self,
1498        diag: &mut Diag<'_>,
1499        expr: &hir::Expr<'_>,
1500        expr_ty: Ty<'tcx>,
1501        expected_ty: Ty<'tcx>,
1502    ) -> bool {
1503        if !expected_ty.is_bool() {
1504            return false;
1505        }
1506
1507        let ty::Adt(def, _) = expr_ty.peel_refs().kind() else {
1508            return false;
1509        };
1510        if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1511            return false;
1512        }
1513
1514        let cond_parent = self.tcx.hir_parent_iter(expr.hir_id).find(|(_, node)| {
1515            !#[allow(non_exhaustive_omitted_patterns)] match node {
    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. })
        if op.node == hir::BinOpKind::And => true,
    _ => false,
}matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. }) if op.node == hir::BinOpKind::And)
1516        });
1517        // Don't suggest:
1518        //     `let Some(_) = a.is_some() && b`
1519        //                     ++++++++++
1520        // since the user probably just misunderstood how `let else`
1521        // and `&&` work together.
1522        if let Some((_, hir::Node::LetStmt(local))) = cond_parent
1523            && let hir::PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), .. })
1524            | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1525            && let hir::QPath::Resolved(None, path) = qpath
1526            && let Some(did) = path
1527                .res
1528                .opt_def_id()
1529                .and_then(|did| self.tcx.opt_parent(did))
1530                .and_then(|did| self.tcx.opt_parent(did))
1531            && self.tcx.is_diagnostic_item(sym::Option, did)
1532        {
1533            return false;
1534        }
1535
1536        let suggestion = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1537            Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}.is_some()", ident))
    })format!(": {ident}.is_some()"),
1538            None => ".is_some()".to_string(),
1539        };
1540
1541        diag.span_suggestion_verbose(
1542            expr.span.shrink_to_hi(),
1543            "use `Option::is_some` to test if the `Option` has a value",
1544            suggestion,
1545            Applicability::MachineApplicable,
1546        );
1547        true
1548    }
1549
1550    // Suggest to change `Option<&Vec<T>>::unwrap_or(&[])` to `Option::map_or(&[], |v| v)`.
1551    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("suggest_deref_unwrap_or",
                                    "rustc_hir_typeck::fn_ctxt::suggestions",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1551u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["callee_ty",
                                                    "call_ident", "expected_ty", "provided_ty", "is_method"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&call_ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&provided_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&is_method as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !is_method { return; }
            let Some(callee_ty) = callee_ty else { return; };
            let ty::Adt(callee_adt, _) =
                callee_ty.peel_refs().kind() else { return; };
            let adt_name =
                if self.tcx.is_diagnostic_item(sym::Option, callee_adt.did())
                    {
                    "Option"
                } else if self.tcx.is_diagnostic_item(sym::Result,
                        callee_adt.did()) {
                    "Result"
                } else { return; };
            let Some(call_ident) = call_ident else { return; };
            if call_ident.name != sym::unwrap_or { return; }
            let ty::Ref(_, peeled, _mutability) =
                provided_ty.kind() else { return; };
            let dummy_ty =
                if let ty::Array(elem_ty, size) = peeled.kind() &&
                            let ty::Infer(_) = elem_ty.kind() &&
                        self.try_structurally_resolve_const(provided_expr.span,
                                    *size).try_to_target_usize(self.tcx) == Some(0) {
                    let slice = Ty::new_slice(self.tcx, *elem_ty);
                    Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static,
                        slice)
                } else { provided_ty };
            if !self.may_coerce(expected_ty, dummy_ty) { return; }
            let msg =
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("use `{0}::map_or` to deref inner value of `{0}`",
                                adt_name))
                    });
            err.multipart_suggestion(msg,
                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                        [(call_ident.span, "map_or".to_owned()),
                                (provided_expr.span.shrink_to_hi(),
                                    ", |v| v".to_owned())])), Applicability::MachineApplicable);
        }
    }
}#[instrument(level = "trace", skip(self, err, provided_expr))]
1552    pub(crate) fn suggest_deref_unwrap_or(
1553        &self,
1554        err: &mut Diag<'_>,
1555        callee_ty: Option<Ty<'tcx>>,
1556        call_ident: Option<Ident>,
1557        expected_ty: Ty<'tcx>,
1558        provided_ty: Ty<'tcx>,
1559        provided_expr: &Expr<'tcx>,
1560        is_method: bool,
1561    ) {
1562        if !is_method {
1563            return;
1564        }
1565        let Some(callee_ty) = callee_ty else {
1566            return;
1567        };
1568        let ty::Adt(callee_adt, _) = callee_ty.peel_refs().kind() else {
1569            return;
1570        };
1571        let adt_name = if self.tcx.is_diagnostic_item(sym::Option, callee_adt.did()) {
1572            "Option"
1573        } else if self.tcx.is_diagnostic_item(sym::Result, callee_adt.did()) {
1574            "Result"
1575        } else {
1576            return;
1577        };
1578
1579        let Some(call_ident) = call_ident else {
1580            return;
1581        };
1582        if call_ident.name != sym::unwrap_or {
1583            return;
1584        }
1585
1586        let ty::Ref(_, peeled, _mutability) = provided_ty.kind() else {
1587            return;
1588        };
1589
1590        // NOTE: Can we reuse `suggest_deref_or_ref`?
1591
1592        // Create an dummy type `&[_]` so that both &[] and `&Vec<T>` can coerce to it.
1593        let dummy_ty = if let ty::Array(elem_ty, size) = peeled.kind()
1594            && let ty::Infer(_) = elem_ty.kind()
1595            && self
1596                .try_structurally_resolve_const(provided_expr.span, *size)
1597                .try_to_target_usize(self.tcx)
1598                == Some(0)
1599        {
1600            let slice = Ty::new_slice(self.tcx, *elem_ty);
1601            Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, slice)
1602        } else {
1603            provided_ty
1604        };
1605
1606        if !self.may_coerce(expected_ty, dummy_ty) {
1607            return;
1608        }
1609        let msg = format!("use `{adt_name}::map_or` to deref inner value of `{adt_name}`");
1610        err.multipart_suggestion(
1611            msg,
1612            vec![
1613                (call_ident.span, "map_or".to_owned()),
1614                (provided_expr.span.shrink_to_hi(), ", |v| v".to_owned()),
1615            ],
1616            Applicability::MachineApplicable,
1617        );
1618    }
1619
1620    /// Suggest wrapping the block in square brackets instead of curly braces
1621    /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1622    pub(crate) fn suggest_block_to_brackets(
1623        &self,
1624        diag: &mut Diag<'_>,
1625        blk: &hir::Block<'_>,
1626        blk_ty: Ty<'tcx>,
1627        expected_ty: Ty<'tcx>,
1628    ) {
1629        if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1630            if self.may_coerce(blk_ty, *elem_ty)
1631                && blk.stmts.is_empty()
1632                && blk.rules == hir::BlockCheckMode::DefaultBlock
1633                && let source_map = self.tcx.sess.source_map()
1634                && let Ok(snippet) = source_map.span_to_snippet(blk.span)
1635                && snippet.starts_with('{')
1636                && snippet.ends_with('}')
1637            {
1638                diag.multipart_suggestion(
1639                    "to create an array, use square brackets instead of curly braces",
1640                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(blk.span.shrink_to_lo().with_hi(rustc_span::BytePos(blk.span.lo().0
                                + 1)), "[".to_string()),
                (blk.span.shrink_to_hi().with_lo(rustc_span::BytePos(blk.span.hi().0
                                - 1)), "]".to_string())]))vec![
1641                        (
1642                            blk.span
1643                                .shrink_to_lo()
1644                                .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1645                            "[".to_string(),
1646                        ),
1647                        (
1648                            blk.span
1649                                .shrink_to_hi()
1650                                .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1651                            "]".to_string(),
1652                        ),
1653                    ],
1654                    Applicability::MachineApplicable,
1655                );
1656            }
1657        }
1658    }
1659
1660    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("suggest_floating_point_literal",
                                    "rustc_hir_typeck::fn_ctxt::suggestions",
                                    ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1660u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["expr",
                                                    "expected_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_ty)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !expected_ty.is_floating_point() { return false; }
            match expr.kind {
                ExprKind::Struct(&qpath, [start, end], _) if
                    is_range_literal(expr) &&
                        self.tcx.qpath_is_lang_item(qpath, LangItem::Range) => {
                    err.span_suggestion_verbose(start.expr.span.shrink_to_hi().with_hi(end.expr.span.lo()),
                        "remove the unnecessary `.` operator for a floating point literal",
                        '.', Applicability::MaybeIncorrect);
                    true
                }
                ExprKind::Struct(&qpath, [arg], _) if
                    is_range_literal(expr) &&
                        let Some(qpath @ (LangItem::RangeFrom | LangItem::RangeTo))
                            = self.tcx.qpath_lang_item(qpath) => {
                    let range_span = expr.span.parent_callsite().unwrap();
                    match qpath {
                        LangItem::RangeFrom => {
                            err.span_suggestion_verbose(range_span.with_lo(arg.expr.span.hi()),
                                "remove the unnecessary `.` operator for a floating point literal",
                                '.', Applicability::MaybeIncorrect);
                        }
                        _ => {
                            err.span_suggestion_verbose(range_span.until(arg.expr.span),
                                "remove the unnecessary `.` operator and add an integer part for a floating point literal",
                                "0.", Applicability::MaybeIncorrect);
                        }
                    }
                    true
                }
                ExprKind::Lit(Spanned {
                    node: rustc_ast::LitKind::Int(lit,
                        rustc_ast::LitIntType::Unsuffixed),
                    span }) => {
                    let Ok(snippet) =
                        self.tcx.sess.source_map().span_to_snippet(span) else {
                            return false;
                        };
                    if !(snippet.starts_with("0x") || snippet.starts_with("0X"))
                        {
                        return false;
                    }
                    if snippet.len() <= 5 ||
                            !snippet.is_char_boundary(snippet.len() - 3) {
                        return false;
                    }
                    let (_, suffix) = snippet.split_at(snippet.len() - 3);
                    let value =
                        match suffix {
                            "f32" => (lit.get() - 0xf32) / (16 * 16 * 16),
                            "f64" => (lit.get() - 0xf64) / (16 * 16 * 16),
                            _ => return false,
                        };
                    err.span_suggestions(expr.span,
                        "rewrite this as a decimal floating point literal, or use `as` to turn a hex literal into a float",
                        [::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("0x{0:X} as {1}", value,
                                                suffix))
                                    }),
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("{0}_{1}", value, suffix))
                                    })], Applicability::MaybeIncorrect);
                    true
                }
                _ => false,
            }
        }
    }
}#[instrument(skip(self, err))]
1661    pub(crate) fn suggest_floating_point_literal(
1662        &self,
1663        err: &mut Diag<'_>,
1664        expr: &hir::Expr<'_>,
1665        expected_ty: Ty<'tcx>,
1666    ) -> bool {
1667        if !expected_ty.is_floating_point() {
1668            return false;
1669        }
1670        match expr.kind {
1671            ExprKind::Struct(&qpath, [start, end], _)
1672                if is_range_literal(expr)
1673                    && self.tcx.qpath_is_lang_item(qpath, LangItem::Range) =>
1674            {
1675                err.span_suggestion_verbose(
1676                    start.expr.span.shrink_to_hi().with_hi(end.expr.span.lo()),
1677                    "remove the unnecessary `.` operator for a floating point literal",
1678                    '.',
1679                    Applicability::MaybeIncorrect,
1680                );
1681                true
1682            }
1683            ExprKind::Struct(&qpath, [arg], _)
1684                if is_range_literal(expr)
1685                    && let Some(qpath @ (LangItem::RangeFrom | LangItem::RangeTo)) =
1686                        self.tcx.qpath_lang_item(qpath) =>
1687            {
1688                let range_span = expr.span.parent_callsite().unwrap();
1689                match qpath {
1690                    LangItem::RangeFrom => {
1691                        err.span_suggestion_verbose(
1692                            range_span.with_lo(arg.expr.span.hi()),
1693                            "remove the unnecessary `.` operator for a floating point literal",
1694                            '.',
1695                            Applicability::MaybeIncorrect,
1696                        );
1697                    }
1698                    _ => {
1699                        err.span_suggestion_verbose(
1700                            range_span.until(arg.expr.span),
1701                            "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1702                            "0.",
1703                            Applicability::MaybeIncorrect,
1704                        );
1705                    }
1706                }
1707                true
1708            }
1709            ExprKind::Lit(Spanned {
1710                node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed),
1711                span,
1712            }) => {
1713                let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) else {
1714                    return false;
1715                };
1716                if !(snippet.starts_with("0x") || snippet.starts_with("0X")) {
1717                    return false;
1718                }
1719                if snippet.len() <= 5 || !snippet.is_char_boundary(snippet.len() - 3) {
1720                    return false;
1721                }
1722                let (_, suffix) = snippet.split_at(snippet.len() - 3);
1723                let value = match suffix {
1724                    "f32" => (lit.get() - 0xf32) / (16 * 16 * 16),
1725                    "f64" => (lit.get() - 0xf64) / (16 * 16 * 16),
1726                    _ => return false,
1727                };
1728                err.span_suggestions(
1729                    expr.span,
1730                    "rewrite this as a decimal floating point literal, or use `as` to turn a hex literal into a float",
1731                    [format!("0x{value:X} as {suffix}"), format!("{value}_{suffix}")],
1732                    Applicability::MaybeIncorrect,
1733                );
1734                true
1735            }
1736            _ => false,
1737        }
1738    }
1739
1740    /// Suggest providing `std::ptr::null()` or `std::ptr::null_mut()` if they
1741    /// pass in a literal 0 to an raw pointer.
1742    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("suggest_null_ptr_for_literal_zero_given_to_ptr_arg",
                                    "rustc_hir_typeck::fn_ctxt::suggestions",
                                    ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1742u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
                                    ::tracing_core::field::FieldSet::new(&["expr",
                                                    "expected_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_ty)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty::RawPtr(_, mutbl) =
                expected_ty.kind() else { return false; };
            let ExprKind::Lit(Spanned {
                    node: rustc_ast::LitKind::Int(Pu128(0), _), span }) =
                expr.kind else { return false; };
            let null_sym =
                match mutbl {
                    hir::Mutability::Not => sym::ptr_null,
                    hir::Mutability::Mut => sym::ptr_null_mut,
                };
            let Some(null_did) =
                self.tcx.get_diagnostic_item(null_sym) else { return false; };
            let null_path_str =
                {
                    let _guard = NoTrimmedGuard::new();
                    self.tcx.def_path_str(null_did)
                };
            err.span_suggestion(span,
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("if you meant to create a null pointer, use `{0}()`",
                                null_path_str))
                    }), null_path_str + "()", Applicability::MachineApplicable);
            true
        }
    }
}#[instrument(skip(self, err))]
1743    pub(crate) fn suggest_null_ptr_for_literal_zero_given_to_ptr_arg(
1744        &self,
1745        err: &mut Diag<'_>,
1746        expr: &hir::Expr<'_>,
1747        expected_ty: Ty<'tcx>,
1748    ) -> bool {
1749        // Expected type needs to be a raw pointer.
1750        let ty::RawPtr(_, mutbl) = expected_ty.kind() else {
1751            return false;
1752        };
1753
1754        // Provided expression needs to be a literal `0`.
1755        let ExprKind::Lit(Spanned { node: rustc_ast::LitKind::Int(Pu128(0), _), span }) = expr.kind
1756        else {
1757            return false;
1758        };
1759
1760        // We need to find a null pointer symbol to suggest
1761        let null_sym = match mutbl {
1762            hir::Mutability::Not => sym::ptr_null,
1763            hir::Mutability::Mut => sym::ptr_null_mut,
1764        };
1765        let Some(null_did) = self.tcx.get_diagnostic_item(null_sym) else {
1766            return false;
1767        };
1768        let null_path_str = with_no_trimmed_paths!(self.tcx.def_path_str(null_did));
1769
1770        // We have satisfied all requirements to provide a suggestion. Emit it.
1771        err.span_suggestion(
1772            span,
1773            format!("if you meant to create a null pointer, use `{null_path_str}()`"),
1774            null_path_str + "()",
1775            Applicability::MachineApplicable,
1776        );
1777
1778        true
1779    }
1780
1781    pub(crate) fn suggest_associated_const(
1782        &self,
1783        err: &mut Diag<'_>,
1784        expr: &hir::Expr<'tcx>,
1785        expected_ty: Ty<'tcx>,
1786    ) -> bool {
1787        let Some((DefKind::AssocFn, old_def_id)) =
1788            self.typeck_results.borrow().type_dependent_def(expr.hir_id)
1789        else {
1790            return false;
1791        };
1792        let old_item_name = self.tcx.item_name(old_def_id);
1793        let capitalized_name = Symbol::intern(&old_item_name.as_str().to_uppercase());
1794        if old_item_name == capitalized_name {
1795            return false;
1796        }
1797        let (item, segment) = match expr.kind {
1798            hir::ExprKind::Path(QPath::Resolved(
1799                Some(ty),
1800                hir::Path { segments: [segment], .. },
1801            ))
1802            | hir::ExprKind::Path(QPath::TypeRelative(ty, segment))
1803                if let Some(self_ty) = self.typeck_results.borrow().node_type_opt(ty.hir_id)
1804                    && let Ok(pick) = self.probe_for_name(
1805                        Mode::Path,
1806                        Ident::new(capitalized_name, segment.ident.span),
1807                        Some(expected_ty),
1808                        IsSuggestion(true),
1809                        self_ty,
1810                        expr.hir_id,
1811                        ProbeScope::TraitsInScope,
1812                    ) =>
1813            {
1814                (pick.item, segment)
1815            }
1816            hir::ExprKind::Path(QPath::Resolved(
1817                None,
1818                hir::Path { segments: [.., segment], .. },
1819            )) => {
1820                // we resolved through some path that doesn't end in the item name,
1821                // better not do a bad suggestion by accident.
1822                if old_item_name != segment.ident.name {
1823                    return false;
1824                }
1825                let Some(item) = self
1826                    .tcx
1827                    .associated_items(self.tcx.parent(old_def_id))
1828                    .filter_by_name_unhygienic(capitalized_name)
1829                    .next()
1830                else {
1831                    return false;
1832                };
1833                (*item, segment)
1834            }
1835            _ => return false,
1836        };
1837        if item.def_id == old_def_id
1838            || !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(item.def_id)
    {
    DefKind::AssocConst { .. } => true,
    _ => false,
}matches!(self.tcx.def_kind(item.def_id), DefKind::AssocConst { .. })
1839        {
1840            // Same item
1841            return false;
1842        }
1843        let item_ty = self.tcx.type_of(item.def_id).instantiate_identity();
1844        // FIXME(compiler-errors): This check is *so* rudimentary
1845        if item_ty.has_param() {
1846            return false;
1847        }
1848        if self.may_coerce(item_ty, expected_ty) {
1849            err.span_suggestion_verbose(
1850                segment.ident.span,
1851                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("try referring to the associated const `{0}` instead",
                capitalized_name))
    })format!("try referring to the associated const `{capitalized_name}` instead",),
1852                capitalized_name,
1853                Applicability::MachineApplicable,
1854            );
1855            true
1856        } else {
1857            false
1858        }
1859    }
1860
1861    fn is_loop(&self, id: HirId) -> bool {
1862        let node = self.tcx.hir_node(id);
1863        #[allow(non_exhaustive_omitted_patterns)] match node {
    Node::Expr(Expr { kind: ExprKind::Loop(..), .. }) => true,
    _ => false,
}matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1864    }
1865
1866    fn is_local_statement(&self, id: HirId) -> bool {
1867        let node = self.tcx.hir_node(id);
1868        #[allow(non_exhaustive_omitted_patterns)] match node {
    Node::Stmt(Stmt { kind: StmtKind::Let(..), .. }) => true,
    _ => false,
}matches!(node, Node::Stmt(Stmt { kind: StmtKind::Let(..), .. }))
1869    }
1870
1871    /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1872    /// which is a side-effect of autoref.
1873    pub(crate) fn note_type_is_not_clone(
1874        &self,
1875        diag: &mut Diag<'_>,
1876        expected_ty: Ty<'tcx>,
1877        found_ty: Ty<'tcx>,
1878        expr: &hir::Expr<'_>,
1879    ) {
1880        // When `expr` is `x` in something like `let x = foo.clone(); x`, need to recurse up to get
1881        // `foo` and `clone`.
1882        let expr = self.note_type_is_not_clone_inner_expr(expr);
1883
1884        // If we've recursed to an `expr` of `foo.clone()`, get `foo` and `clone`.
1885        let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else {
1886            return;
1887        };
1888
1889        let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else {
1890            return;
1891        };
1892        let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1893        let results = self.typeck_results.borrow();
1894        // First, look for a `Clone::clone` call
1895        if segment.ident.name == sym::clone
1896            && results.type_dependent_def_id(expr.hir_id).is_some_and(|did| {
1897                    let assoc_item = self.tcx.associated_item(did);
1898                    assoc_item.container == ty::AssocContainer::Trait
1899                        && assoc_item.container_id(self.tcx) == clone_trait_did
1900                })
1901            // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1902            // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1903            && !results.expr_adjustments(callee_expr).iter().any(|adj| #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
    ty::adjustment::Adjust::Deref(..) => true,
    _ => false,
}matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1904            // Check that we're in fact trying to clone into the expected type
1905            && self.may_coerce(*pointee_ty, expected_ty)
1906            && let trait_ref = ty::TraitRef::new(self.tcx, clone_trait_did, [expected_ty])
1907            // And the expected type doesn't implement `Clone`
1908            && !self.predicate_must_hold_considering_regions(&traits::Obligation::new(
1909                self.tcx,
1910                traits::ObligationCause::dummy(),
1911                self.param_env,
1912                trait_ref,
1913            ))
1914        {
1915            diag.span_note(
1916                callee_expr.span,
1917                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` does not implement `Clone`, so `{1}` was cloned instead",
                expected_ty, found_ty))
    })format!(
1918                    "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1919                ),
1920            );
1921            let owner = self.tcx.hir_enclosing_body_owner(expr.hir_id);
1922            if let ty::Param(param) = expected_ty.kind()
1923                && let Some(generics) = self.tcx.hir_get_generics(owner)
1924            {
1925                suggest_constraining_type_params(
1926                    self.tcx,
1927                    generics,
1928                    diag,
1929                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(param.name.as_str(), "Clone", Some(clone_trait_did))]))vec![(param.name.as_str(), "Clone", Some(clone_trait_did))].into_iter(),
1930                    None,
1931                );
1932            } else {
1933                let mut suggest_derive = true;
1934                if let Some(errors) =
1935                    self.type_implements_trait_shallow(clone_trait_did, expected_ty, self.param_env)
1936                {
1937                    let manually_impl = "consider manually implementing `Clone` to avoid the \
1938                        implicit type parameter bounds";
1939                    match &errors[..] {
1940                        [] => {}
1941                        [error] => {
1942                            let msg = "`Clone` is not implemented because a trait bound is not \
1943                                satisfied";
1944                            if let traits::ObligationCauseCode::ImplDerived(data) =
1945                                error.obligation.cause.code()
1946                            {
1947                                let mut span: MultiSpan = data.span.into();
1948                                if self.tcx.is_automatically_derived(data.impl_or_alias_def_id) {
1949                                    span.push_span_label(
1950                                        data.span,
1951                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("derive introduces an implicit `{0}` bound",
                error.obligation.predicate))
    })format!(
1952                                            "derive introduces an implicit `{}` bound",
1953                                            error.obligation.predicate
1954                                        ),
1955                                    );
1956                                }
1957                                diag.span_help(span, msg);
1958                                if self.tcx.is_automatically_derived(data.impl_or_alias_def_id)
1959                                    && data.impl_or_alias_def_id.is_local()
1960                                {
1961                                    diag.help(manually_impl);
1962                                    suggest_derive = false;
1963                                }
1964                            } else {
1965                                diag.help(msg);
1966                            }
1967                        }
1968                        _ => {
1969                            let unsatisfied_bounds: Vec<_> = errors
1970                                .iter()
1971                                .filter_map(|error| match error.obligation.cause.code() {
1972                                    traits::ObligationCauseCode::ImplDerived(data) => {
1973                                        let pre = if self
1974                                            .tcx
1975                                            .is_automatically_derived(data.impl_or_alias_def_id)
1976                                        {
1977                                            "derive introduces an implicit "
1978                                        } else {
1979                                            ""
1980                                        };
1981                                        Some((
1982                                            data.span,
1983                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}unsatisfied trait bound `{0}`",
                error.obligation.predicate, pre))
    })format!(
1984                                                "{pre}unsatisfied trait bound `{}`",
1985                                                error.obligation.predicate
1986                                            ),
1987                                        ))
1988                                    }
1989                                    _ => None,
1990                                })
1991                                .collect();
1992                            let msg = "`Clone` is not implemented because the some trait bounds \
1993                                could not be satisfied";
1994                            if errors.len() == unsatisfied_bounds.len() {
1995                                let mut unsatisfied_bounds_spans: MultiSpan = unsatisfied_bounds
1996                                    .iter()
1997                                    .map(|(span, _)| *span)
1998                                    .collect::<Vec<Span>>()
1999                                    .into();
2000                                for (span, label) in unsatisfied_bounds {
2001                                    unsatisfied_bounds_spans.push_span_label(span, label);
2002                                }
2003                                diag.span_help(unsatisfied_bounds_spans, msg);
2004                                if errors.iter().all(|error| match error.obligation.cause.code() {
2005                                    traits::ObligationCauseCode::ImplDerived(data) => {
2006                                        self.tcx.is_automatically_derived(data.impl_or_alias_def_id)
2007                                            && data.impl_or_alias_def_id.is_local()
2008                                    }
2009                                    _ => false,
2010                                }) {
2011                                    diag.help(manually_impl);
2012                                    suggest_derive = false;
2013                                }
2014                            } else {
2015                                diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}: {0}",
                listify(&errors,
                        |e|
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("`{0}`",
                                            e.obligation.predicate))
                                })).unwrap(), msg))
    })format!(
2016                                    "{msg}: {}",
2017                                    listify(&errors, |e| format!("`{}`", e.obligation.predicate))
2018                                        .unwrap(),
2019                                ));
2020                            }
2021                        }
2022                    }
2023                    for error in errors {
2024                        if let traits::FulfillmentErrorCode::Select(
2025                            traits::SelectionError::Unimplemented,
2026                        ) = error.code
2027                            && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2028                                error.obligation.predicate.kind().skip_binder()
2029                        {
2030                            self.infcx.err_ctxt().suggest_derive(
2031                                &error.obligation,
2032                                diag,
2033                                error.obligation.predicate.kind().rebind(pred),
2034                            );
2035                        }
2036                    }
2037                }
2038                if suggest_derive {
2039                    self.suggest_derive(diag, &::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(trait_ref.upcast(self.tcx), None, None)]))vec![(trait_ref.upcast(self.tcx), None, None)]);
2040                }
2041            }
2042        }
2043    }
2044
2045    /// Given a type mismatch error caused by `&T` being cloned instead of `T`, and
2046    /// the `expr` as the source of this type mismatch, try to find the method call
2047    /// as the source of this error and return that instead. Otherwise, return the
2048    /// original expression.
2049    fn note_type_is_not_clone_inner_expr<'b>(
2050        &'b self,
2051        expr: &'b hir::Expr<'b>,
2052    ) -> &'b hir::Expr<'b> {
2053        match expr.peel_blocks().kind {
2054            hir::ExprKind::Path(hir::QPath::Resolved(
2055                None,
2056                hir::Path { segments: [_], res: crate::Res::Local(binding), .. },
2057            )) => {
2058                let hir::Node::Pat(hir::Pat { hir_id, .. }) = self.tcx.hir_node(*binding) else {
2059                    return expr;
2060                };
2061
2062                match self.tcx.parent_hir_node(*hir_id) {
2063                    // foo.clone()
2064                    hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) => {
2065                        self.note_type_is_not_clone_inner_expr(init)
2066                    }
2067                    // When `expr` is more complex like a tuple
2068                    hir::Node::Pat(hir::Pat {
2069                        hir_id: pat_hir_id,
2070                        kind: hir::PatKind::Tuple(pats, ..),
2071                        ..
2072                    }) => {
2073                        let hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) =
2074                            self.tcx.parent_hir_node(*pat_hir_id)
2075                        else {
2076                            return expr;
2077                        };
2078
2079                        match init.peel_blocks().kind {
2080                            ExprKind::Tup(init_tup) => {
2081                                if let Some(init) = pats
2082                                    .iter()
2083                                    .enumerate()
2084                                    .filter(|x| x.1.hir_id == *hir_id)
2085                                    .find_map(|(i, _)| init_tup.get(i))
2086                                {
2087                                    self.note_type_is_not_clone_inner_expr(init)
2088                                } else {
2089                                    expr
2090                                }
2091                            }
2092                            _ => expr,
2093                        }
2094                    }
2095                    _ => expr,
2096                }
2097            }
2098            // If we're calling into a closure that may not be typed recurse into that call. no need
2099            // to worry if it's a call to a typed function or closure as this would ne handled
2100            // previously.
2101            hir::ExprKind::Call(Expr { kind: call_expr_kind, .. }, _) => {
2102                if let hir::ExprKind::Path(hir::QPath::Resolved(None, call_expr_path)) =
2103                    call_expr_kind
2104                    && let hir::Path { segments: [_], res: crate::Res::Local(binding), .. } =
2105                        call_expr_path
2106                    && let hir::Node::Pat(hir::Pat { hir_id, .. }) = self.tcx.hir_node(*binding)
2107                    && let hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) =
2108                        self.tcx.parent_hir_node(*hir_id)
2109                    && let Expr {
2110                        kind: hir::ExprKind::Closure(hir::Closure { body: body_id, .. }),
2111                        ..
2112                    } = init
2113                {
2114                    let hir::Body { value: body_expr, .. } = self.tcx.hir_body(*body_id);
2115                    self.note_type_is_not_clone_inner_expr(body_expr)
2116                } else {
2117                    expr
2118                }
2119            }
2120            _ => expr,
2121        }
2122    }
2123
2124    pub(crate) fn is_field_suggestable(
2125        &self,
2126        field: &ty::FieldDef,
2127        hir_id: HirId,
2128        span: Span,
2129    ) -> bool {
2130        // The field must be visible in the containing module.
2131        field.vis.is_accessible_from(self.tcx.parent_module(hir_id), self.tcx)
2132            // The field must not be unstable.
2133            && !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.eval_stability(field.did,
        None, rustc_span::DUMMY_SP, None) {
    rustc_middle::middle::stability::EvalResult::Deny { .. } => true,
    _ => false,
}matches!(
2134                self.tcx.eval_stability(field.did, None, rustc_span::DUMMY_SP, None),
2135                rustc_middle::middle::stability::EvalResult::Deny { .. }
2136            )
2137            // If the field is from an external crate it must not be `doc(hidden)`.
2138            && (field.did.is_local() || !self.tcx.is_doc_hidden(field.did))
2139            // If the field is hygienic it must come from the same syntax context.
2140            && self.tcx.def_ident_span(field.did).unwrap().normalize_to_macros_2_0().eq_ctxt(span)
2141    }
2142
2143    pub(crate) fn suggest_missing_unwrap_expect(
2144        &self,
2145        err: &mut Diag<'_>,
2146        expr: &hir::Expr<'tcx>,
2147        expected: Ty<'tcx>,
2148        found: Ty<'tcx>,
2149    ) -> bool {
2150        let ty::Adt(adt, args) = found.kind() else {
2151            return false;
2152        };
2153        let ret_ty_matches = |diagnostic_item| {
2154            let Some(sig) = self.body_fn_sig() else {
2155                return false;
2156            };
2157            let ty::Adt(kind, _) = sig.output().kind() else {
2158                return false;
2159            };
2160            self.tcx.is_diagnostic_item(diagnostic_item, kind.did())
2161        };
2162
2163        // don't suggest anything like `Ok(ok_val).unwrap()` , `Some(some_val).unwrap()`,
2164        // `None.unwrap()` etc.
2165        let is_ctor = #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    hir::ExprKind::Call(hir::Expr {
        kind: hir::ExprKind::Path(hir::QPath::Resolved(None, hir::Path {
            res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. })), .. }, ..)
        |
        hir::ExprKind::Path(hir::QPath::Resolved(None, hir::Path {
        res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. })) => true,
    _ => false,
}matches!(
2166            expr.kind,
2167            hir::ExprKind::Call(
2168                hir::Expr {
2169                    kind: hir::ExprKind::Path(hir::QPath::Resolved(
2170                        None,
2171                        hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. },
2172                    )),
2173                    ..
2174                },
2175                ..,
2176            ) | hir::ExprKind::Path(hir::QPath::Resolved(
2177                None,
2178                hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. },
2179            )),
2180        );
2181
2182        let (article, kind, variant, sugg_operator) = if self.tcx.is_diagnostic_item(sym::Result, adt.did())
2183            // Do not suggest `.expect()` in const context where it's not available. rust-lang/rust#149316
2184            && !self.tcx.hir_is_inside_const_context(expr.hir_id)
2185        {
2186            ("a", "Result", "Err", ret_ty_matches(sym::Result))
2187        } else if self.tcx.is_diagnostic_item(sym::Option, adt.did()) {
2188            ("an", "Option", "None", ret_ty_matches(sym::Option))
2189        } else {
2190            return false;
2191        };
2192        if is_ctor || !self.may_coerce(args.type_at(0), expected) {
2193            return false;
2194        }
2195
2196        let (msg, sugg) = if sugg_operator {
2197            (
2198                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use the `?` operator to extract the `{0}` value, propagating {1} `{2}::{3}` value to the caller",
                found, article, kind, variant))
    })format!(
2199                    "use the `?` operator to extract the `{found}` value, propagating \
2200                            {article} `{kind}::{variant}` value to the caller"
2201                ),
2202                "?",
2203            )
2204        } else {
2205            (
2206                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider using `{0}::expect` to unwrap the `{1}` value, panicking if the value is {2} `{0}::{3}`",
                kind, found, article, variant))
    })format!(
2207                    "consider using `{kind}::expect` to unwrap the `{found}` value, \
2208                                panicking if the value is {article} `{kind}::{variant}`"
2209                ),
2210                ".expect(\"REASON\")",
2211            )
2212        };
2213
2214        let sugg = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
2215            Some(_) if expr.span.from_expansion() => return false,
2216            Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}{1}", ident, sugg))
    })format!(": {ident}{sugg}"),
2217            None => sugg.to_string(),
2218        };
2219
2220        let span = expr
2221            .span
2222            .find_ancestor_not_from_extern_macro(self.tcx.sess.source_map())
2223            .unwrap_or(expr.span);
2224        err.span_suggestion_verbose(span.shrink_to_hi(), msg, sugg, Applicability::HasPlaceholders);
2225        true
2226    }
2227
2228    pub(crate) fn suggest_coercing_result_via_try_operator(
2229        &self,
2230        err: &mut Diag<'_>,
2231        expr: &hir::Expr<'tcx>,
2232        expected: Ty<'tcx>,
2233        found: Ty<'tcx>,
2234    ) -> bool {
2235        let returned = #[allow(non_exhaustive_omitted_patterns)] match self.tcx.parent_hir_node(expr.hir_id)
    {
    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. }) => true,
    _ => false,
}matches!(
2236            self.tcx.parent_hir_node(expr.hir_id),
2237            hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
2238        ) || self.tcx.hir_get_fn_id_for_return_block(expr.hir_id).is_some();
2239        if returned
2240            && let ty::Adt(e, args_e) = expected.kind()
2241            && let ty::Adt(f, args_f) = found.kind()
2242            && e.did() == f.did()
2243            && Some(e.did()) == self.tcx.get_diagnostic_item(sym::Result)
2244            && let e_ok = args_e.type_at(0)
2245            && let f_ok = args_f.type_at(0)
2246            && self.infcx.can_eq(self.param_env, f_ok, e_ok)
2247            && let e_err = args_e.type_at(1)
2248            && let f_err = args_f.type_at(1)
2249            && self
2250                .infcx
2251                .type_implements_trait(
2252                    self.tcx.get_diagnostic_item(sym::Into).unwrap(),
2253                    [f_err, e_err],
2254                    self.param_env,
2255                )
2256                .must_apply_modulo_regions()
2257        {
2258            err.multipart_suggestion(
2259                "use `?` to coerce and return an appropriate `Err`, and wrap the resulting value \
2260                 in `Ok` so the expression remains of type `Result`",
2261                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_lo(), "Ok(".to_string()),
                (expr.span.shrink_to_hi(), "?)".to_string())]))vec![
2262                    (expr.span.shrink_to_lo(), "Ok(".to_string()),
2263                    (expr.span.shrink_to_hi(), "?)".to_string()),
2264                ],
2265                Applicability::MaybeIncorrect,
2266            );
2267            return true;
2268        }
2269        false
2270    }
2271
2272    // If the expr is a while or for loop and is the tail expr of its
2273    // enclosing body suggest returning a value right after it
2274    pub(crate) fn suggest_returning_value_after_loop(
2275        &self,
2276        err: &mut Diag<'_>,
2277        expr: &hir::Expr<'tcx>,
2278        expected: Ty<'tcx>,
2279    ) -> bool {
2280        let tcx = self.tcx;
2281        let enclosing_scope =
2282            tcx.hir_get_enclosing_scope(expr.hir_id).map(|hir_id| tcx.hir_node(hir_id));
2283
2284        // Get tail expr of the enclosing block or body
2285        let tail_expr = if let Some(Node::Block(hir::Block { expr, .. })) = enclosing_scope
2286            && expr.is_some()
2287        {
2288            *expr
2289        } else {
2290            let body_def_id = tcx.hir_enclosing_body_owner(expr.hir_id);
2291            let body = tcx.hir_body_owned_by(body_def_id);
2292
2293            // Get tail expr of the body
2294            match body.value.kind {
2295                // Regular function body etc.
2296                hir::ExprKind::Block(block, _) => block.expr,
2297                // Anon const body (there's no block in this case)
2298                hir::ExprKind::DropTemps(expr) => Some(expr),
2299                _ => None,
2300            }
2301        };
2302
2303        let Some(tail_expr) = tail_expr else {
2304            return false; // Body doesn't have a tail expr we can compare with
2305        };
2306
2307        // Get the loop expr within the tail expr
2308        let loop_expr_in_tail = match expr.kind {
2309            hir::ExprKind::Loop(_, _, hir::LoopSource::While, _) => tail_expr,
2310            hir::ExprKind::Loop(_, _, hir::LoopSource::ForLoop, _) => {
2311                match tail_expr.peel_drop_temps() {
2312                    Expr { kind: ExprKind::Match(_, [Arm { body, .. }], _), .. } => body,
2313                    _ => return false, // Not really a for loop
2314                }
2315            }
2316            _ => return false, // Not a while or a for loop
2317        };
2318
2319        // If the expr is the loop expr in the tail
2320        // then make the suggestion
2321        if expr.hir_id == loop_expr_in_tail.hir_id {
2322            let span = expr.span;
2323
2324            let (msg, suggestion) = if expected.is_never() {
2325                (
2326                    "consider adding a diverging expression here",
2327                    "`loop {}` or `panic!(\"...\")`".to_string(),
2328                )
2329            } else {
2330                ("consider returning a value here", ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` value", expected))
    })format!("`{expected}` value"))
2331            };
2332
2333            let src_map = tcx.sess.source_map();
2334            let suggestion = if src_map.is_multiline(expr.span) {
2335                let indentation = src_map.indentation_before(span).unwrap_or_default();
2336                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}/* {1} */", indentation,
                suggestion))
    })format!("\n{indentation}/* {suggestion} */")
2337            } else {
2338                // If the entire expr is on a single line
2339                // put the suggestion also on the same line
2340                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" /* {0} */", suggestion))
    })format!(" /* {suggestion} */")
2341            };
2342
2343            err.span_suggestion_verbose(
2344                span.shrink_to_hi(),
2345                msg,
2346                suggestion,
2347                Applicability::MaybeIncorrect,
2348            );
2349
2350            true
2351        } else {
2352            false
2353        }
2354    }
2355
2356    /// Suggest replacing comma with semicolon in incorrect repeat expressions
2357    /// like `["_", 10]` or `vec![String::new(), 10]`.
2358    pub(crate) fn suggest_semicolon_in_repeat_expr(
2359        &self,
2360        err: &mut Diag<'_>,
2361        expr: &hir::Expr<'_>,
2362        expr_ty: Ty<'tcx>,
2363    ) -> bool {
2364        // Check if `expr` is contained in array of two elements
2365        if let hir::Node::Expr(array_expr) = self.tcx.parent_hir_node(expr.hir_id)
2366            && let hir::ExprKind::Array(elements) = array_expr.kind
2367            && let [first, second] = elements
2368            && second.hir_id == expr.hir_id
2369        {
2370            // Span between the two elements of the array
2371            let comma_span = first.span.between(second.span);
2372
2373            // Check if `expr` is a constant value of type `usize`.
2374            // This can only detect const variable declarations and
2375            // calls to const functions.
2376
2377            // Checking this here instead of rustc_hir::hir because
2378            // this check needs access to `self.tcx` but rustc_hir
2379            // has no access to `TyCtxt`.
2380            let expr_is_const_usize = expr_ty.is_usize()
2381                && match expr.kind {
2382                    ExprKind::Path(QPath::Resolved(
2383                        None,
2384                        Path { res: Res::Def(DefKind::Const { .. }, _), .. },
2385                    )) => true,
2386                    ExprKind::Call(
2387                        Expr {
2388                            kind:
2389                                ExprKind::Path(QPath::Resolved(
2390                                    None,
2391                                    Path { res: Res::Def(DefKind::Fn, fn_def_id), .. },
2392                                )),
2393                            ..
2394                        },
2395                        _,
2396                    ) => self.tcx.is_const_fn(*fn_def_id),
2397                    _ => false,
2398                };
2399
2400            // Type of the first element is guaranteed to be checked
2401            // when execution reaches here because `mismatched types`
2402            // error occurs only when type of second element of array
2403            // is not the same as type of first element.
2404            let first_ty = self.typeck_results.borrow().expr_ty(first);
2405
2406            // `array_expr` is from a macro `vec!["a", 10]` if
2407            // 1. array expression's span is imported from a macro
2408            // 2. first element of array implements `Clone` trait
2409            // 3. second element is an integer literal or is an expression of `usize` like type
2410            if self.tcx.sess.source_map().is_imported(array_expr.span)
2411                && self.type_is_clone_modulo_regions(self.param_env, first_ty)
2412                && (expr.is_size_lit() || expr_ty.is_usize_like())
2413            {
2414                err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2415                    comma_span,
2416                    descr: "a vector",
2417                });
2418                return true;
2419            }
2420
2421            // `array_expr` is from an array `["a", 10]` if
2422            // 1. first element of array implements `Copy` trait
2423            // 2. second element is an integer literal or is a const value of type `usize`
2424            if self.type_is_copy_modulo_regions(self.param_env, first_ty)
2425                && (expr.is_size_lit() || expr_is_const_usize)
2426            {
2427                err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2428                    comma_span,
2429                    descr: "an array",
2430                });
2431                return true;
2432            }
2433        }
2434        false
2435    }
2436
2437    /// If the expected type is an enum (Issue #55250) with any variants whose
2438    /// sole field is of the found type, suggest such variants. (Issue #42764)
2439    pub(crate) fn suggest_compatible_variants(
2440        &self,
2441        err: &mut Diag<'_>,
2442        expr: &hir::Expr<'_>,
2443        expected: Ty<'tcx>,
2444        expr_ty: Ty<'tcx>,
2445    ) -> bool {
2446        if expr.span.in_external_macro(self.tcx.sess.source_map()) {
2447            return false;
2448        }
2449        if let ty::Adt(expected_adt, args) = expected.kind() {
2450            if let hir::ExprKind::Field(base, ident) = expr.kind {
2451                let base_ty = self.typeck_results.borrow().expr_ty(base);
2452                if self.can_eq(self.param_env, base_ty, expected)
2453                    && let Some(base_span) = base.span.find_ancestor_inside(expr.span)
2454                {
2455                    err.span_suggestion_verbose(
2456                        expr.span.with_lo(base_span.hi()),
2457                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing the tuple struct field `{0}`",
                ident))
    })format!("consider removing the tuple struct field `{ident}`"),
2458                        "",
2459                        Applicability::MaybeIncorrect,
2460                    );
2461                    return true;
2462                }
2463            }
2464
2465            // If the expression is of type () and it's the return expression of a block,
2466            // we suggest adding a separate return expression instead.
2467            // (To avoid things like suggesting `Ok(while .. { .. })`.)
2468            if expr_ty.is_unit() {
2469                let mut id = expr.hir_id;
2470                let mut parent;
2471
2472                // Unroll desugaring, to make sure this works for `for` loops etc.
2473                loop {
2474                    parent = self.tcx.parent_hir_id(id);
2475                    let parent_span = self.tcx.hir_span(parent);
2476                    if parent_span.find_ancestor_inside(expr.span).is_some() {
2477                        // The parent node is part of the same span, so is the result of the
2478                        // same expansion/desugaring and not the 'real' parent node.
2479                        id = parent;
2480                        continue;
2481                    }
2482                    break;
2483                }
2484
2485                if let hir::Node::Block(&hir::Block { span: block_span, expr: Some(e), .. }) =
2486                    self.tcx.hir_node(parent)
2487                {
2488                    if e.hir_id == id {
2489                        if let Some(span) = expr.span.find_ancestor_inside(block_span) {
2490                            let return_suggestions = if self
2491                                .tcx
2492                                .is_diagnostic_item(sym::Result, expected_adt.did())
2493                            {
2494                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        ["Ok(())"]))vec!["Ok(())"]
2495                            } else if self.tcx.is_diagnostic_item(sym::Option, expected_adt.did()) {
2496                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        ["None", "Some(())"]))vec!["None", "Some(())"]
2497                            } else {
2498                                return false;
2499                            };
2500                            if let Some(indent) =
2501                                self.tcx.sess.source_map().indentation_before(span.shrink_to_lo())
2502                            {
2503                                // Add a semicolon, except after `}`.
2504                                let semicolon =
2505                                    match self.tcx.sess.source_map().span_to_snippet(span) {
2506                                        Ok(s) if s.ends_with('}') => "",
2507                                        _ => ";",
2508                                    };
2509                                err.span_suggestions(
2510                                    span.shrink_to_hi(),
2511                                    "try adding an expression at the end of the block",
2512                                    return_suggestions
2513                                        .into_iter()
2514                                        .map(|r| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\n{1}{2}", semicolon, indent,
                r))
    })format!("{semicolon}\n{indent}{r}")),
2515                                    Applicability::MaybeIncorrect,
2516                                );
2517                            }
2518                            return true;
2519                        }
2520                    }
2521                }
2522            }
2523
2524            let compatible_variants: Vec<(String, _, _, Option<String>)> = expected_adt
2525                .variants()
2526                .iter()
2527                .filter(|variant| {
2528                    variant.fields.len() == 1
2529                })
2530                .filter_map(|variant| {
2531                    let sole_field = &variant.single_field();
2532
2533                    // When expected_ty and expr_ty are the same ADT, we prefer to compare their internal generic params,
2534                    // When the current variant has a sole field whose type is still an unresolved inference variable,
2535                    // suggestions would be often wrong. So suppress the suggestion. See #145294.
2536                    if let (ty::Adt(exp_adt, _), ty::Adt(act_adt, _)) = (expected.kind(), expr_ty.kind())
2537                        && exp_adt.did() == act_adt.did()
2538                        && sole_field.ty(self.tcx, args).is_ty_var() {
2539                            return None;
2540                    }
2541
2542                    let field_is_local = sole_field.did.is_local();
2543                    let field_is_accessible =
2544                        sole_field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
2545                        // Skip suggestions for unstable public fields (for example `Pin::__pointer`)
2546                        && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.eval_stability(sole_field.did,
        None, expr.span, None) {
    EvalResult::Allow | EvalResult::Unmarked => true,
    _ => false,
}matches!(self.tcx.eval_stability(sole_field.did, None, expr.span, None), EvalResult::Allow | EvalResult::Unmarked);
2547
2548                    if !field_is_local && !field_is_accessible {
2549                        return None;
2550                    }
2551
2552                    let note_about_variant_field_privacy = (field_is_local && !field_is_accessible)
2553                        .then(|| " (its field is private, but it's local to this crate and its privacy can be changed)".to_string());
2554
2555                    let sole_field_ty = sole_field.ty(self.tcx, args);
2556                    if self.may_coerce(expr_ty, sole_field_ty) {
2557                        let variant_path =
2558                            { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(variant.def_id) }with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
2559                        // FIXME #56861: DRYer prelude filtering
2560                        if let Some(path) = variant_path.strip_prefix("std::prelude::")
2561                            && let Some((_, path)) = path.split_once("::")
2562                        {
2563                            return Some((path.to_string(), variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy));
2564                        }
2565                        Some((variant_path, variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy))
2566                    } else {
2567                        None
2568                    }
2569                })
2570                .collect();
2571
2572            let suggestions_for = |variant: &_, ctor_kind, field_name| {
2573                let prefix = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
2574                    Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", ident))
    })format!("{ident}: "),
2575                    None => String::new(),
2576                };
2577
2578                let (open, close) = match ctor_kind {
2579                    Some(CtorKind::Fn) => ("(".to_owned(), ")"),
2580                    None => (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{ {0}: ", field_name))
    })format!(" {{ {field_name}: "), " }"),
2581
2582                    Some(CtorKind::Const) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unit variants don\'t have fields")));
}unreachable!("unit variants don't have fields"),
2583                };
2584
2585                // Suggest constructor as deep into the block tree as possible.
2586                // This fixes https://github.com/rust-lang/rust/issues/101065,
2587                // and also just helps make the most minimal suggestions.
2588                let mut expr = expr;
2589                while let hir::ExprKind::Block(block, _) = &expr.kind
2590                    && let Some(expr_) = &block.expr
2591                {
2592                    expr = expr_
2593                }
2594
2595                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}{1}{2}", prefix,
                                    variant, open))
                        })), (expr.span.shrink_to_hi(), close.to_owned())]))vec![
2596                    (expr.span.shrink_to_lo(), format!("{prefix}{variant}{open}")),
2597                    (expr.span.shrink_to_hi(), close.to_owned()),
2598                ]
2599            };
2600
2601            match &compatible_variants[..] {
2602                [] => { /* No variants to format */ }
2603                [(variant, ctor_kind, field_name, note)] => {
2604                    // Just a single matching variant.
2605                    err.multipart_suggestion(
2606                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("try wrapping the expression in `{1}`{0}",
                note.as_deref().unwrap_or(""), variant))
    })format!(
2607                            "try wrapping the expression in `{variant}`{note}",
2608                            note = note.as_deref().unwrap_or("")
2609                        ),
2610                        suggestions_for(&**variant, *ctor_kind, *field_name),
2611                        Applicability::MaybeIncorrect,
2612                    );
2613                    return true;
2614                }
2615                _ => {
2616                    // More than one matching variant.
2617                    err.multipart_suggestions(
2618                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("try wrapping the expression in a variant of `{0}`",
                self.tcx.def_path_str(expected_adt.did())))
    })format!(
2619                            "try wrapping the expression in a variant of `{}`",
2620                            self.tcx.def_path_str(expected_adt.did())
2621                        ),
2622                        compatible_variants.into_iter().map(
2623                            |(variant, ctor_kind, field_name, _)| {
2624                                suggestions_for(&variant, ctor_kind, field_name)
2625                            },
2626                        ),
2627                        Applicability::MaybeIncorrect,
2628                    );
2629                    return true;
2630                }
2631            }
2632        }
2633
2634        false
2635    }
2636
2637    pub(crate) fn suggest_non_zero_new_unwrap(
2638        &self,
2639        err: &mut Diag<'_>,
2640        expr: &hir::Expr<'_>,
2641        expected: Ty<'tcx>,
2642        expr_ty: Ty<'tcx>,
2643    ) -> bool {
2644        let tcx = self.tcx;
2645        let (adt, args, unwrap) = match expected.kind() {
2646            // In case `Option<NonZero<T>>` is wanted, but `T` is provided, suggest calling `new`.
2647            ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Option, adt.did()) => {
2648                let nonzero_type = args.type_at(0); // Unwrap option type.
2649                let ty::Adt(adt, args) = nonzero_type.kind() else {
2650                    return false;
2651                };
2652                (adt, args, "")
2653            }
2654            // In case `NonZero<T>` is wanted but `T` is provided, also add `.unwrap()` to satisfy types.
2655            ty::Adt(adt, args) => (adt, args, ".unwrap()"),
2656            _ => return false,
2657        };
2658
2659        if !self.tcx.is_diagnostic_item(sym::NonZero, adt.did()) {
2660            return false;
2661        }
2662
2663        let int_type = args.type_at(0);
2664        if !self.may_coerce(expr_ty, int_type) {
2665            return false;
2666        }
2667
2668        err.multipart_suggestion(
2669            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider calling `{0}::new`",
                sym::NonZero))
    })format!("consider calling `{}::new`", sym::NonZero),
2670            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}::new(",
                                    sym::NonZero))
                        })),
                (expr.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("){0}", unwrap))
                        }))]))vec![
2671                (expr.span.shrink_to_lo(), format!("{}::new(", sym::NonZero)),
2672                (expr.span.shrink_to_hi(), format!("){unwrap}")),
2673            ],
2674            Applicability::MaybeIncorrect,
2675        );
2676
2677        true
2678    }
2679
2680    /// Identify some cases where `as_ref()` would be appropriate and suggest it.
2681    ///
2682    /// Given the following code:
2683    /// ```compile_fail,E0308
2684    /// struct Foo;
2685    /// fn takes_ref(_: &Foo) {}
2686    /// let ref opt = Some(Foo);
2687    ///
2688    /// opt.map(|param| takes_ref(param));
2689    /// ```
2690    /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
2691    ///
2692    /// It only checks for `Option` and `Result` and won't work with
2693    /// ```ignore (illustrative)
2694    /// opt.map(|param| { takes_ref(param) });
2695    /// ```
2696    fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Vec<(Span, String)>, &'static str)> {
2697        let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind else {
2698            return None;
2699        };
2700
2701        let hir::def::Res::Local(local_id) = path.res else {
2702            return None;
2703        };
2704
2705        let Node::Param(hir::Param { hir_id: param_hir_id, .. }) =
2706            self.tcx.parent_hir_node(local_id)
2707        else {
2708            return None;
2709        };
2710
2711        let Node::Expr(hir::Expr {
2712            hir_id: expr_hir_id,
2713            kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }),
2714            ..
2715        }) = self.tcx.parent_hir_node(*param_hir_id)
2716        else {
2717            return None;
2718        };
2719
2720        let hir = self.tcx.parent_hir_node(*expr_hir_id);
2721        let closure_params_len = closure_fn_decl.inputs.len();
2722        let (
2723            Node::Expr(hir::Expr {
2724                kind: hir::ExprKind::MethodCall(method_path, receiver, ..),
2725                ..
2726            }),
2727            1,
2728        ) = (hir, closure_params_len)
2729        else {
2730            return None;
2731        };
2732
2733        let self_ty = self.typeck_results.borrow().expr_ty(receiver);
2734        let name = method_path.ident.name;
2735        let is_as_ref_able = match self_ty.peel_refs().kind() {
2736            ty::Adt(def, _) => {
2737                (self.tcx.is_diagnostic_item(sym::Option, def.did())
2738                    || self.tcx.is_diagnostic_item(sym::Result, def.did()))
2739                    && (name == sym::map || name == sym::and_then)
2740            }
2741            _ => false,
2742        };
2743        if is_as_ref_able {
2744            Some((
2745                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(method_path.ident.span.shrink_to_lo(), "as_ref().".to_string())]))vec![(method_path.ident.span.shrink_to_lo(), "as_ref().".to_string())],
2746                "consider using `as_ref` instead",
2747            ))
2748        } else {
2749            None
2750        }
2751    }
2752
2753    /// This function is used to determine potential "simple" improvements or users' errors and
2754    /// provide them useful help. For example:
2755    ///
2756    /// ```compile_fail,E0308
2757    /// fn some_fn(s: &str) {}
2758    ///
2759    /// let x = "hey!".to_owned();
2760    /// some_fn(x); // error
2761    /// ```
2762    ///
2763    /// No need to find every potential function which could make a coercion to transform a
2764    /// `String` into a `&str` since a `&` would do the trick!
2765    ///
2766    /// In addition of this check, it also checks between references mutability state. If the
2767    /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
2768    /// `&mut`!".
2769    pub(crate) fn suggest_deref_or_ref(
2770        &self,
2771        expr: &hir::Expr<'tcx>,
2772        checked_ty: Ty<'tcx>,
2773        expected: Ty<'tcx>,
2774    ) -> Option<(
2775        Vec<(Span, String)>,
2776        String,
2777        Applicability,
2778        bool, /* verbose */
2779        bool, /* suggest `&` or `&mut` type annotation */
2780    )> {
2781        let sess = self.sess();
2782        let sp = expr.range_span().unwrap_or(expr.span);
2783        let sm = sess.source_map();
2784
2785        // If the span is from an external macro, there's no suggestion we can make.
2786        if sp.in_external_macro(sm) {
2787            return None;
2788        }
2789
2790        let replace_prefix = |s: &str, old: &str, new: &str| {
2791            s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
2792        };
2793
2794        // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
2795        let expr = expr.peel_drop_temps();
2796
2797        match (&expr.kind, expected.kind(), checked_ty.kind()) {
2798            (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (exp.kind(), check.kind()) {
2799                (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
2800                    if let hir::ExprKind::Lit(_) = expr.kind
2801                        && let Ok(src) = sm.span_to_snippet(sp)
2802                        && replace_prefix(&src, "b\"", "\"").is_some()
2803                    {
2804                        let pos = sp.lo() + BytePos(1);
2805                        return Some((
2806                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(sp.with_hi(pos), String::new())]))vec![(sp.with_hi(pos), String::new())],
2807                            "consider removing the leading `b`".to_string(),
2808                            Applicability::MachineApplicable,
2809                            true,
2810                            false,
2811                        ));
2812                    }
2813                }
2814                (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
2815                    if let hir::ExprKind::Lit(_) = expr.kind
2816                        && let Ok(src) = sm.span_to_snippet(sp)
2817                        && replace_prefix(&src, "\"", "b\"").is_some()
2818                    {
2819                        return Some((
2820                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(sp.shrink_to_lo(), "b".to_string())]))vec![(sp.shrink_to_lo(), "b".to_string())],
2821                            "consider adding a leading `b`".to_string(),
2822                            Applicability::MachineApplicable,
2823                            true,
2824                            false,
2825                        ));
2826                    }
2827                }
2828                _ => {}
2829            },
2830            (_, &ty::Ref(_, _, mutability), _) => {
2831                // Check if it can work when put into a ref. For example:
2832                //
2833                // ```
2834                // fn bar(x: &mut i32) {}
2835                //
2836                // let x = 0u32;
2837                // bar(&x); // error, expected &mut
2838                // ```
2839                let ref_ty = match mutability {
2840                    hir::Mutability::Mut => {
2841                        Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, checked_ty)
2842                    }
2843                    hir::Mutability::Not => {
2844                        Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, checked_ty)
2845                    }
2846                };
2847                if self.may_coerce(ref_ty, expected) {
2848                    let mut sugg_sp = sp;
2849                    if let hir::ExprKind::MethodCall(segment, receiver, args, _) = expr.kind {
2850                        let clone_trait =
2851                            self.tcx.require_lang_item(LangItem::Clone, segment.ident.span);
2852                        if args.is_empty()
2853                            && self
2854                                .typeck_results
2855                                .borrow()
2856                                .type_dependent_def_id(expr.hir_id)
2857                                .is_some_and(|did| {
2858                                    let ai = self.tcx.associated_item(did);
2859                                    ai.trait_container(self.tcx) == Some(clone_trait)
2860                                })
2861                            && segment.ident.name == sym::clone
2862                        {
2863                            // If this expression had a clone call when suggesting borrowing
2864                            // we want to suggest removing it because it'd now be unnecessary.
2865                            sugg_sp = receiver.span;
2866                        }
2867                    }
2868
2869                    if let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
2870                        && let Some(1) = self.deref_steps_for_suggestion(expected, checked_ty)
2871                        && self.typeck_results.borrow().expr_ty(inner).is_ref()
2872                    {
2873                        // We have `*&T`, check if what was expected was `&T`.
2874                        // If so, we may want to suggest removing a `*`.
2875                        sugg_sp = sugg_sp.with_hi(inner.span.lo());
2876                        return Some((
2877                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(sugg_sp, String::new())]))vec![(sugg_sp, String::new())],
2878                            "consider removing deref here".to_string(),
2879                            Applicability::MachineApplicable,
2880                            true,
2881                            false,
2882                        ));
2883                    }
2884
2885                    // Don't try to suggest ref/deref on an `if` expression, because:
2886                    // - The `if` could be part of a desugared `if else` statement,
2887                    //   which would create impossible suggestions such as `if ... { ... } else &if { ... } else { ... }`.
2888                    // - In general the suggestions it creates such as `&if ... { ... } else { ... }` are not very helpful.
2889                    // We try to generate a suggestion such as `if ... { &... } else { &... }` instead.
2890                    if let hir::ExprKind::If(_c, then, els) = expr.kind {
2891                        // The `then` of a `Expr::If` always contains a block, and that block may have a final expression that we can borrow
2892                        // If the block does not have a final expression, it will return () and we do not make a suggestion to borrow that.
2893                        let ExprKind::Block(then, _) = then.kind else { return None };
2894                        let Some(then) = then.expr else { return None };
2895                        let (mut suggs, help, app, verbose, mutref) =
2896                            self.suggest_deref_or_ref(then, checked_ty, expected)?;
2897
2898                        // If there is no `else`, the return type of this `if` will be (), so suggesting to change the `then` block is useless
2899                        let els_expr = match els?.kind {
2900                            ExprKind::Block(block, _) => block.expr?,
2901                            _ => els?,
2902                        };
2903                        let (else_suggs, ..) =
2904                            self.suggest_deref_or_ref(els_expr, checked_ty, expected)?;
2905                        suggs.extend(else_suggs);
2906
2907                        return Some((suggs, help, app, verbose, mutref));
2908                    }
2909
2910                    if let Some((sugg, msg)) = self.can_use_as_ref(expr) {
2911                        return Some((
2912                            sugg,
2913                            msg.to_string(),
2914                            Applicability::MachineApplicable,
2915                            true,
2916                            false,
2917                        ));
2918                    }
2919
2920                    let prefix = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
2921                        Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", ident))
    })format!("{ident}: "),
2922                        None => String::new(),
2923                    };
2924
2925                    if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Assign(..), .. }) =
2926                        self.tcx.parent_hir_node(expr.hir_id)
2927                    {
2928                        if mutability.is_mut() {
2929                            // Suppressing this diagnostic, we'll properly print it in `check_expr_assign`
2930                            return None;
2931                        }
2932                    }
2933
2934                    let make_sugg = |expr: &Expr<'_>, span: Span, sugg: &str| {
2935                        if expr_needs_parens(expr) {
2936                            (
2937                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}{1}(", prefix, sugg))
                        })), (span.shrink_to_hi(), ")".to_string())]))vec![
2938                                    (span.shrink_to_lo(), format!("{prefix}{sugg}(")),
2939                                    (span.shrink_to_hi(), ")".to_string()),
2940                                ],
2941                                false,
2942                            )
2943                        } else {
2944                            (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}{1}", prefix, sugg))
                        }))]))vec![(span.shrink_to_lo(), format!("{prefix}{sugg}"))], true)
2945                        }
2946                    };
2947
2948                    // Suggest dereferencing the lhs for expressions such as `&T <= T`
2949                    if let hir::Node::Expr(hir::Expr {
2950                        kind: hir::ExprKind::Binary(_, lhs, ..),
2951                        ..
2952                    }) = self.tcx.parent_hir_node(expr.hir_id)
2953                        && let &ty::Ref(..) = self.check_expr(lhs).kind()
2954                    {
2955                        let (sugg, verbose) = make_sugg(lhs, lhs.span, "*");
2956
2957                        return Some((
2958                            sugg,
2959                            "consider dereferencing the borrow".to_string(),
2960                            Applicability::MachineApplicable,
2961                            verbose,
2962                            false,
2963                        ));
2964                    }
2965
2966                    let sugg = mutability.ref_prefix_str();
2967                    let (sugg, verbose) = make_sugg(expr, sp, sugg);
2968                    return Some((
2969                        sugg,
2970                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider {0}borrowing here",
                mutability.mutably_str()))
    })format!("consider {}borrowing here", mutability.mutably_str()),
2971                        Applicability::MachineApplicable,
2972                        verbose,
2973                        false,
2974                    ));
2975                }
2976            }
2977            (hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr), _, &ty::Ref(_, checked, _))
2978                if self.can_eq(self.param_env, checked, expected) =>
2979            {
2980                let make_sugg = |start: Span, end: BytePos| {
2981                    // skip `(` for tuples such as `(c) = (&123)`.
2982                    // make sure we won't suggest like `(c) = 123)` which is incorrect.
2983                    let sp = sm
2984                        .span_extend_while(start.shrink_to_lo(), |c| c == '(' || c.is_whitespace())
2985                        .map_or(start, |s| s.shrink_to_hi());
2986                    Some((
2987                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(sp.with_hi(end), String::new())]))vec![(sp.with_hi(end), String::new())],
2988                        "consider removing the borrow".to_string(),
2989                        Applicability::MachineApplicable,
2990                        true,
2991                        true,
2992                    ))
2993                };
2994
2995                // We have `&T`, check if what was expected was `T`. If so,
2996                // we may want to suggest removing a `&`.
2997                if sm.is_imported(expr.span) {
2998                    // Go through the spans from which this span was expanded,
2999                    // and find the one that's pointing inside `sp`.
3000                    //
3001                    // E.g. for `&format!("")`, where we want the span to the
3002                    // `format!()` invocation instead of its expansion.
3003                    if let Some(call_span) =
3004                        iter::successors(Some(expr.span), |s| s.parent_callsite())
3005                            .find(|&s| sp.contains(s))
3006                        && sm.is_span_accessible(call_span)
3007                    {
3008                        return make_sugg(sp, call_span.lo());
3009                    }
3010                    return None;
3011                }
3012                if sp.contains(expr.span) && sm.is_span_accessible(expr.span) {
3013                    return make_sugg(sp, expr.span.lo());
3014                }
3015            }
3016            (_, &ty::RawPtr(ty_b, mutbl_b), &ty::Ref(_, ty_a, mutbl_a)) => {
3017                if let Some(steps) = self.deref_steps_for_suggestion(ty_a, ty_b)
3018                    // Only suggest valid if dereferencing needed.
3019                    && steps > 0
3020                    // The pointer type implements `Copy` trait so the suggestion is always valid.
3021                    && let Ok(src) = sm.span_to_snippet(sp)
3022                {
3023                    let derefs = "*".repeat(steps);
3024                    let old_prefix = mutbl_a.ref_prefix_str();
3025                    let new_prefix = mutbl_b.ref_prefix_str().to_owned() + &derefs;
3026
3027                    let suggestion = replace_prefix(&src, old_prefix, &new_prefix).map(|_| {
3028                        // skip `&` or `&mut ` if both mutabilities are mutable
3029                        let lo = sp.lo()
3030                            + BytePos(min(old_prefix.len(), mutbl_b.ref_prefix_str().len()) as _);
3031                        // skip `&` or `&mut `
3032                        let hi = sp.lo() + BytePos(old_prefix.len() as _);
3033                        let sp = sp.with_lo(lo).with_hi(hi);
3034
3035                        (
3036                            sp,
3037                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}",
                if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" },
                derefs))
    })format!(
3038                                "{}{derefs}",
3039                                if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" }
3040                            ),
3041                            if mutbl_b <= mutbl_a {
3042                                Applicability::MachineApplicable
3043                            } else {
3044                                Applicability::MaybeIncorrect
3045                            },
3046                        )
3047                    });
3048
3049                    if let Some((span, src, applicability)) = suggestion {
3050                        return Some((
3051                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, src)]))vec![(span, src)],
3052                            "consider dereferencing".to_string(),
3053                            applicability,
3054                            true,
3055                            false,
3056                        ));
3057                    }
3058                }
3059            }
3060            _ if sp == expr.span => {
3061                if let Some(mut steps) = self.deref_steps_for_suggestion(checked_ty, expected) {
3062                    let mut expr = expr.peel_blocks();
3063                    let mut prefix_span = expr.span.shrink_to_lo();
3064                    let mut remove = String::new();
3065
3066                    // Try peeling off any existing `&` and `&mut` to reach our target type
3067                    while steps > 0 {
3068                        if let hir::ExprKind::AddrOf(_, mutbl, inner) = expr.kind {
3069                            // If the expression has `&`, removing it would fix the error
3070                            prefix_span = prefix_span.with_hi(inner.span.lo());
3071                            expr = inner;
3072                            remove.push_str(mutbl.ref_prefix_str());
3073                            steps -= 1;
3074                        } else {
3075                            break;
3076                        }
3077                    }
3078                    // If we've reached our target type with just removing `&`, then just print now.
3079                    if steps == 0 && !remove.trim().is_empty() {
3080                        return Some((
3081                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(prefix_span, String::new())]))vec![(prefix_span, String::new())],
3082                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing the `{0}`",
                remove.trim()))
    })format!("consider removing the `{}`", remove.trim()),
3083                            // Do not remove `&&` to get to bool, because it might be something like
3084                            // { a } && b, which we have a separate fixup suggestion that is more
3085                            // likely correct...
3086                            if remove.trim() == "&&" && expected == self.tcx.types.bool {
3087                                Applicability::MaybeIncorrect
3088                            } else {
3089                                Applicability::MachineApplicable
3090                            },
3091                            true,
3092                            false,
3093                        ));
3094                    }
3095
3096                    // For this suggestion to make sense, the type would need to be `Copy`,
3097                    // or we have to be moving out of a `Box<T>`
3098                    if self.type_is_copy_modulo_regions(self.param_env, expected)
3099                        // FIXME(compiler-errors): We can actually do this if the checked_ty is
3100                        // `steps` layers of boxes, not just one, but this is easier and most likely.
3101                        || (checked_ty.is_box() && steps == 1)
3102                        // We can always deref a binop that takes its arguments by ref.
3103                        || #[allow(non_exhaustive_omitted_patterns)] match self.tcx.parent_hir_node(expr.hir_id)
    {
    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, ..), .. }) if
        !op.node.is_by_value() => true,
    _ => false,
}matches!(
3104                            self.tcx.parent_hir_node(expr.hir_id),
3105                            hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, ..), .. })
3106                                if !op.node.is_by_value()
3107                        )
3108                    {
3109                        let deref_kind = if checked_ty.is_box() {
3110                            // detect Box::new(..)
3111                            // FIXME: use `box_new` diagnostic item instead?
3112                            if let ExprKind::Call(box_new, [_]) = expr.kind
3113                                && let ExprKind::Path(qpath) = &box_new.kind
3114                                && let Res::Def(DefKind::AssocFn, fn_id) =
3115                                    self.typeck_results.borrow().qpath_res(qpath, box_new.hir_id)
3116                                && let Some(impl_id) = self.tcx.inherent_impl_of_assoc(fn_id)
3117                                && self.tcx.type_of(impl_id).skip_binder().is_box()
3118                                && self.tcx.item_name(fn_id) == sym::new
3119                            {
3120                                let l_paren = self.tcx.sess.source_map().next_point(box_new.span);
3121                                let r_paren = self.tcx.sess.source_map().end_point(expr.span);
3122                                return Some((
3123                                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(box_new.span.to(l_paren), String::new()),
                (r_paren, String::new())]))vec![
3124                                        (box_new.span.to(l_paren), String::new()),
3125                                        (r_paren, String::new()),
3126                                    ],
3127                                    "consider removing the Box".to_string(),
3128                                    Applicability::MachineApplicable,
3129                                    false,
3130                                    false,
3131                                ));
3132                            }
3133                            "unboxing the value"
3134                        } else if checked_ty.is_ref() {
3135                            "dereferencing the borrow"
3136                        } else {
3137                            "dereferencing the type"
3138                        };
3139
3140                        // Suggest removing `&` if we have removed any, otherwise suggest just
3141                        // dereferencing the remaining number of steps.
3142                        let message = if remove.is_empty() {
3143                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider {0}", deref_kind))
    })format!("consider {deref_kind}")
3144                        } else {
3145                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing the `{0}` and {1} instead",
                remove.trim(), deref_kind))
    })format!(
3146                                "consider removing the `{}` and {} instead",
3147                                remove.trim(),
3148                                deref_kind
3149                            )
3150                        };
3151
3152                        let prefix =
3153                            match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
3154                                Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", ident))
    })format!("{ident}: "),
3155                                None => String::new(),
3156                            };
3157
3158                        let (span, suggestion) = if self.is_else_if_block(expr) {
3159                            // Don't suggest nonsense like `else *if`
3160                            return None;
3161                        } else if let Some(expr) = self.maybe_get_block_expr(expr) {
3162                            // prefix should be empty here..
3163                            (expr.span.shrink_to_lo(), "*".to_string())
3164                        } else {
3165                            (prefix_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", prefix,
                "*".repeat(steps)))
    })format!("{}{}", prefix, "*".repeat(steps)))
3166                        };
3167                        if suggestion.trim().is_empty() {
3168                            return None;
3169                        }
3170
3171                        if expr_needs_parens(expr) {
3172                            return Some((
3173                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}(", suggestion))
                        })), (expr.span.shrink_to_hi(), ")".to_string())]))vec![
3174                                    (span, format!("{suggestion}(")),
3175                                    (expr.span.shrink_to_hi(), ")".to_string()),
3176                                ],
3177                                message,
3178                                Applicability::MachineApplicable,
3179                                true,
3180                                false,
3181                            ));
3182                        }
3183
3184                        return Some((
3185                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, suggestion)]))vec![(span, suggestion)],
3186                            message,
3187                            Applicability::MachineApplicable,
3188                            true,
3189                            false,
3190                        ));
3191                    }
3192                }
3193            }
3194            _ => {}
3195        }
3196        None
3197    }
3198
3199    /// Returns whether the given expression is an `else if`.
3200    fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool {
3201        if let hir::ExprKind::If(..) = expr.kind
3202            && let Node::Expr(hir::Expr { kind: hir::ExprKind::If(_, _, Some(else_expr)), .. }) =
3203                self.tcx.parent_hir_node(expr.hir_id)
3204        {
3205            return else_expr.hir_id == expr.hir_id;
3206        }
3207        false
3208    }
3209
3210    pub(crate) fn suggest_cast(
3211        &self,
3212        err: &mut Diag<'_>,
3213        expr: &hir::Expr<'_>,
3214        checked_ty: Ty<'tcx>,
3215        expected_ty: Ty<'tcx>,
3216        expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
3217    ) -> bool {
3218        if self.tcx.sess.source_map().is_imported(expr.span) {
3219            // Ignore if span is from within a macro.
3220            return false;
3221        }
3222
3223        let span = if let hir::ExprKind::Lit(lit) = &expr.kind { lit.span } else { expr.span };
3224        let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) else {
3225            return false;
3226        };
3227
3228        // If casting this expression to a given numeric type would be appropriate in case of a type
3229        // mismatch.
3230        //
3231        // We want to minimize the amount of casting operations that are suggested, as it can be a
3232        // lossy operation with potentially bad side effects, so we only suggest when encountering
3233        // an expression that indicates that the original type couldn't be directly changed.
3234        //
3235        // For now, don't suggest casting with `as`.
3236        let can_cast = false;
3237
3238        let mut sugg = ::alloc::vec::Vec::new()vec![];
3239
3240        if let hir::Node::ExprField(field) = self.tcx.parent_hir_node(expr.hir_id) {
3241            // `expr` is a literal field for a struct, only suggest if appropriate
3242            if field.is_shorthand {
3243                // This is a field literal
3244                sugg.push((field.ident.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", field.ident))
    })format!("{}: ", field.ident)));
3245            } else {
3246                // Likely a field was meant, but this field wasn't found. Do not suggest anything.
3247                return false;
3248            }
3249        };
3250
3251        if let hir::ExprKind::Call(path, args) = &expr.kind
3252            && let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
3253                (&path.kind, args.len())
3254            // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
3255            && let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
3256                (&base_ty.kind, path_segment.ident.name)
3257        {
3258            if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
3259                match ident.name {
3260                    sym::i128
3261                    | sym::i64
3262                    | sym::i32
3263                    | sym::i16
3264                    | sym::i8
3265                    | sym::u128
3266                    | sym::u64
3267                    | sym::u32
3268                    | sym::u16
3269                    | sym::u8
3270                    | sym::isize
3271                    | sym::usize
3272                        if base_ty_path.segments.len() == 1 =>
3273                    {
3274                        return false;
3275                    }
3276                    _ => {}
3277                }
3278            }
3279        }
3280
3281        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you can convert {0} `{1}` to {2} `{3}`",
                checked_ty.kind().article(), checked_ty,
                expected_ty.kind().article(), expected_ty))
    })format!(
3282            "you can convert {} `{}` to {} `{}`",
3283            checked_ty.kind().article(),
3284            checked_ty,
3285            expected_ty.kind().article(),
3286            expected_ty,
3287        );
3288        let cast_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you can cast {0} `{1}` to {2} `{3}`",
                checked_ty.kind().article(), checked_ty,
                expected_ty.kind().article(), expected_ty))
    })format!(
3289            "you can cast {} `{}` to {} `{}`",
3290            checked_ty.kind().article(),
3291            checked_ty,
3292            expected_ty.kind().article(),
3293            expected_ty,
3294        );
3295        let lit_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("change the type of the numeric literal from `{0}` to `{1}`",
                checked_ty, expected_ty))
    })format!(
3296            "change the type of the numeric literal from `{checked_ty}` to `{expected_ty}`",
3297        );
3298
3299        let close_paren = if self.precedence(expr) < ExprPrecedence::Unambiguous {
3300            sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
3301            ")"
3302        } else {
3303            ""
3304        };
3305
3306        let mut cast_suggestion = sugg.clone();
3307        cast_suggestion.push((expr.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} as {1}", close_paren,
                expected_ty))
    })format!("{close_paren} as {expected_ty}")));
3308        let mut into_suggestion = sugg.clone();
3309        into_suggestion.push((expr.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.into()", close_paren))
    })format!("{close_paren}.into()")));
3310        let mut suffix_suggestion = sugg.clone();
3311        suffix_suggestion.push((
3312            if #[allow(non_exhaustive_omitted_patterns)] match (expected_ty.kind(),
        checked_ty.kind()) {
    (ty::Int(_) | ty::Uint(_), ty::Float(_)) => true,
    _ => false,
}matches!(
3313                (expected_ty.kind(), checked_ty.kind()),
3314                (ty::Int(_) | ty::Uint(_), ty::Float(_))
3315            ) {
3316                // Remove fractional part from literal, for example `42.0f32` into `42`
3317                let src = src.trim_end_matches(&checked_ty.to_string());
3318                let len = src.split('.').next().unwrap().len();
3319                span.with_lo(span.lo() + BytePos(len as u32))
3320            } else {
3321                let len = src.trim_end_matches(&checked_ty.to_string()).len();
3322                span.with_lo(span.lo() + BytePos(len as u32))
3323            },
3324            if self.precedence(expr) < ExprPrecedence::Unambiguous {
3325                // Readd `)`
3326                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0})", expected_ty))
    })format!("{expected_ty})")
3327            } else {
3328                expected_ty.to_string()
3329            },
3330        ));
3331        let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
3332            if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
3333        };
3334        let is_negative_int =
3335            |expr: &hir::Expr<'_>| #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    hir::ExprKind::Unary(hir::UnOp::Neg, ..) => true,
    _ => false,
}matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::Neg, ..));
3336        let is_uint = |ty: Ty<'_>| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Uint(..) => true,
    _ => false,
}matches!(ty.kind(), ty::Uint(..));
3337
3338        let in_const_context = self.tcx.hir_is_inside_const_context(expr.hir_id);
3339
3340        let suggest_fallible_into_or_lhs_from =
3341            |err: &mut Diag<'_>, exp_to_found_is_fallible: bool| {
3342                // If we know the expression the expected type is derived from, we might be able
3343                // to suggest a widening conversion rather than a narrowing one (which may
3344                // panic). For example, given x: u8 and y: u32, if we know the span of "x",
3345                //   x > y
3346                // can be given the suggestion "u32::from(x) > y" rather than
3347                // "x > y.try_into().unwrap()".
3348                let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
3349                    self.tcx
3350                        .sess
3351                        .source_map()
3352                        .span_to_snippet(expr.span)
3353                        .ok()
3354                        .map(|src| (expr, src))
3355                });
3356                let (msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
3357                    (lhs_expr_and_src, exp_to_found_is_fallible)
3358                {
3359                    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you can convert `{0}` from `{1}` to `{2}`, matching the type of `{3}`",
                lhs_src, expected_ty, checked_ty, src))
    })format!(
3360                        "you can convert `{lhs_src}` from `{expected_ty}` to `{checked_ty}`, matching the type of `{src}`",
3361                    );
3362                    let suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(lhs_expr.span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}::from(", checked_ty))
                        })), (lhs_expr.span.shrink_to_hi(), ")".to_string())]))vec![
3363                        (lhs_expr.span.shrink_to_lo(), format!("{checked_ty}::from(")),
3364                        (lhs_expr.span.shrink_to_hi(), ")".to_string()),
3365                    ];
3366                    (msg, suggestion)
3367                } else {
3368                    let msg =
3369                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} and panic if the converted value doesn\'t fit",
                msg.clone()))
    })format!("{} and panic if the converted value doesn't fit", msg.clone());
3370                    let mut suggestion = sugg.clone();
3371                    suggestion.push((
3372                        expr.span.shrink_to_hi(),
3373                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.try_into().unwrap()",
                close_paren))
    })format!("{close_paren}.try_into().unwrap()"),
3374                    ));
3375                    (msg, suggestion)
3376                };
3377                err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
3378            };
3379
3380        let suggest_to_change_suffix_or_into =
3381            |err: &mut Diag<'_>, found_to_exp_is_fallible: bool, exp_to_found_is_fallible: bool| {
3382                let exp_is_lhs = expected_ty_expr.is_some_and(|e| self.tcx.hir_is_lhs(e.hir_id));
3383
3384                if exp_is_lhs {
3385                    return;
3386                }
3387
3388                let always_fallible = found_to_exp_is_fallible
3389                    && (exp_to_found_is_fallible || expected_ty_expr.is_none());
3390                let msg = if literal_is_ty_suffixed(expr) {
3391                    lit_msg.clone()
3392                } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
3393                    // We now know that converting either the lhs or rhs is fallible. Before we
3394                    // suggest a fallible conversion, check if the value can never fit in the
3395                    // expected type.
3396                    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` cannot fit into type `{1}`",
                src, expected_ty))
    })format!("`{src}` cannot fit into type `{expected_ty}`");
3397                    err.note(msg);
3398                    return;
3399                } else if in_const_context {
3400                    // Do not recommend `into` or `try_into` in const contexts.
3401                    return;
3402                } else if found_to_exp_is_fallible {
3403                    return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
3404                } else {
3405                    msg.clone()
3406                };
3407                let suggestion = if literal_is_ty_suffixed(expr) {
3408                    suffix_suggestion.clone()
3409                } else {
3410                    into_suggestion.clone()
3411                };
3412                err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
3413            };
3414
3415        match (expected_ty.kind(), checked_ty.kind()) {
3416            (ty::Int(exp), ty::Int(found)) => {
3417                let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3418                {
3419                    (Some(exp), Some(found)) if exp < found => (true, false),
3420                    (Some(exp), Some(found)) if exp > found => (false, true),
3421                    (None, Some(8 | 16)) => (false, true),
3422                    (Some(8 | 16), None) => (true, false),
3423                    (None, _) | (_, None) => (true, true),
3424                    _ => (false, false),
3425                };
3426                suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3427                true
3428            }
3429            (ty::Uint(exp), ty::Uint(found)) => {
3430                let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3431                {
3432                    (Some(exp), Some(found)) if exp < found => (true, false),
3433                    (Some(exp), Some(found)) if exp > found => (false, true),
3434                    (None, Some(8 | 16)) => (false, true),
3435                    (Some(8 | 16), None) => (true, false),
3436                    (None, _) | (_, None) => (true, true),
3437                    _ => (false, false),
3438                };
3439                suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3440                true
3441            }
3442            (&ty::Int(exp), &ty::Uint(found)) => {
3443                let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3444                {
3445                    (Some(exp), Some(found)) if found < exp => (false, true),
3446                    (None, Some(8)) => (false, true),
3447                    _ => (true, true),
3448                };
3449                suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3450                true
3451            }
3452            (&ty::Uint(exp), &ty::Int(found)) => {
3453                let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3454                {
3455                    (Some(exp), Some(found)) if found > exp => (true, false),
3456                    (Some(8), None) => (true, false),
3457                    _ => (true, true),
3458                };
3459                suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3460                true
3461            }
3462            (ty::Float(exp), ty::Float(found)) => {
3463                if found.bit_width() < exp.bit_width() {
3464                    suggest_to_change_suffix_or_into(err, false, true);
3465                } else if literal_is_ty_suffixed(expr) {
3466                    err.multipart_suggestion(
3467                        lit_msg,
3468                        suffix_suggestion,
3469                        Applicability::MachineApplicable,
3470                    );
3471                } else if can_cast {
3472                    // Missing try_into implementation for `f64` to `f32`
3473                    err.multipart_suggestion(
3474                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, producing the closest possible value",
                cast_msg))
    })format!("{cast_msg}, producing the closest possible value"),
3475                        cast_suggestion,
3476                        Applicability::MaybeIncorrect, // lossy conversion
3477                    );
3478                }
3479                true
3480            }
3481            (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
3482                if literal_is_ty_suffixed(expr) {
3483                    err.multipart_suggestion(
3484                        lit_msg,
3485                        suffix_suggestion,
3486                        Applicability::MachineApplicable,
3487                    );
3488                } else if can_cast {
3489                    // Missing try_into implementation for `{float}` to `{integer}`
3490                    err.multipart_suggestion(
3491                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, rounding the float towards zero",
                msg))
    })format!("{msg}, rounding the float towards zero"),
3492                        cast_suggestion,
3493                        Applicability::MaybeIncorrect, // lossy conversion
3494                    );
3495                }
3496                true
3497            }
3498            (ty::Float(exp), ty::Uint(found)) => {
3499                // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
3500                if exp.bit_width() > found.bit_width().unwrap_or(256) {
3501                    err.multipart_suggestion(
3502                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer",
                msg))
    })format!(
3503                            "{msg}, producing the floating point representation of the integer",
3504                        ),
3505                        into_suggestion,
3506                        Applicability::MachineApplicable,
3507                    );
3508                } else if literal_is_ty_suffixed(expr) {
3509                    err.multipart_suggestion(
3510                        lit_msg,
3511                        suffix_suggestion,
3512                        Applicability::MachineApplicable,
3513                    );
3514                } else {
3515                    // Missing try_into implementation for `{integer}` to `{float}`
3516                    err.multipart_suggestion(
3517                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer, rounded if necessary",
                cast_msg))
    })format!(
3518                            "{cast_msg}, producing the floating point representation of the integer, \
3519                                 rounded if necessary",
3520                        ),
3521                        cast_suggestion,
3522                        Applicability::MaybeIncorrect, // lossy conversion
3523                    );
3524                }
3525                true
3526            }
3527            (ty::Float(exp), ty::Int(found)) => {
3528                // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
3529                if exp.bit_width() > found.bit_width().unwrap_or(256) {
3530                    err.multipart_suggestion(
3531                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer",
                msg.clone()))
    })format!(
3532                            "{}, producing the floating point representation of the integer",
3533                            msg.clone(),
3534                        ),
3535                        into_suggestion,
3536                        Applicability::MachineApplicable,
3537                    );
3538                } else if literal_is_ty_suffixed(expr) {
3539                    err.multipart_suggestion(
3540                        lit_msg,
3541                        suffix_suggestion,
3542                        Applicability::MachineApplicable,
3543                    );
3544                } else {
3545                    // Missing try_into implementation for `{integer}` to `{float}`
3546                    err.multipart_suggestion(
3547                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer, rounded if necessary",
                &msg))
    })format!(
3548                            "{}, producing the floating point representation of the integer, \
3549                                rounded if necessary",
3550                            &msg,
3551                        ),
3552                        cast_suggestion,
3553                        Applicability::MaybeIncorrect, // lossy conversion
3554                    );
3555                }
3556                true
3557            }
3558            (
3559                &ty::Uint(ty::UintTy::U32 | ty::UintTy::U64 | ty::UintTy::U128)
3560                | &ty::Int(ty::IntTy::I32 | ty::IntTy::I64 | ty::IntTy::I128),
3561                &ty::Char,
3562            ) => {
3563                err.multipart_suggestion(
3564                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, since a `char` always occupies 4 bytes",
                cast_msg))
    })format!("{cast_msg}, since a `char` always occupies 4 bytes"),
3565                    cast_suggestion,
3566                    Applicability::MachineApplicable,
3567                );
3568                true
3569            }
3570            _ => false,
3571        }
3572    }
3573
3574    /// Identify when the user has written `foo..bar()` instead of `foo.bar()`.
3575    pub(crate) fn suggest_method_call_on_range_literal(
3576        &self,
3577        err: &mut Diag<'_>,
3578        expr: &hir::Expr<'tcx>,
3579        checked_ty: Ty<'tcx>,
3580        expected_ty: Ty<'tcx>,
3581    ) {
3582        if !hir::is_range_literal(expr) {
3583            return;
3584        }
3585        let hir::ExprKind::Struct(&qpath, [start, end], _) = expr.kind else {
3586            return;
3587        };
3588        if !self.tcx.qpath_is_lang_item(qpath, LangItem::Range) {
3589            return;
3590        }
3591        if let hir::Node::ExprField(_) = self.tcx.parent_hir_node(expr.hir_id) {
3592            // Ignore `Foo { field: a..Default::default() }`
3593            return;
3594        }
3595        let mut expr = end.expr;
3596        let mut expectation = Some(expected_ty);
3597        while let hir::ExprKind::MethodCall(_, rcvr, ..) = expr.kind {
3598            // Getting to the root receiver and asserting it is a fn call let's us ignore cases in
3599            // `tests/ui/methods/issues/issue-90315.stderr`.
3600            expr = rcvr;
3601            // If we have more than one layer of calls, then the expected ty
3602            // cannot guide the method probe.
3603            expectation = None;
3604        }
3605        let hir::ExprKind::Call(method_name, _) = expr.kind else {
3606            return;
3607        };
3608        let ty::Adt(adt, _) = checked_ty.kind() else {
3609            return;
3610        };
3611        if self.tcx.lang_items().range_struct() != Some(adt.did()) {
3612            return;
3613        }
3614        if let ty::Adt(adt, _) = expected_ty.kind()
3615            && self.tcx.is_lang_item(adt.did(), LangItem::Range)
3616        {
3617            return;
3618        }
3619        // Check if start has method named end.
3620        let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else {
3621            return;
3622        };
3623        let [hir::PathSegment { ident, .. }] = p.segments else {
3624            return;
3625        };
3626        let self_ty = self.typeck_results.borrow().expr_ty(start.expr);
3627        let Ok(_pick) = self.lookup_probe_for_diagnostic(
3628            *ident,
3629            self_ty,
3630            expr,
3631            probe::ProbeScope::AllTraits,
3632            expectation,
3633        ) else {
3634            return;
3635        };
3636        let mut sugg = ".";
3637        let mut span = start.expr.span.between(end.expr.span);
3638        if span.lo() + BytePos(2) == span.hi() {
3639            // There's no space between the start, the range op and the end, suggest removal which
3640            // will be more noticeable than the replacement of `..` with `.`.
3641            span = span.with_lo(span.lo() + BytePos(1));
3642            sugg = "";
3643        }
3644        err.span_suggestion_verbose(
3645            span,
3646            "you likely meant to write a method call instead of a range",
3647            sugg,
3648            Applicability::MachineApplicable,
3649        );
3650    }
3651
3652    /// Identify when the type error is because `()` is found in a binding that was assigned a
3653    /// block without a tail expression.
3654    pub(crate) fn suggest_return_binding_for_missing_tail_expr(
3655        &self,
3656        err: &mut Diag<'_>,
3657        expr: &hir::Expr<'_>,
3658        checked_ty: Ty<'tcx>,
3659        expected_ty: Ty<'tcx>,
3660    ) {
3661        if !checked_ty.is_unit() {
3662            return;
3663        }
3664        let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
3665            return;
3666        };
3667        let hir::def::Res::Local(hir_id) = path.res else {
3668            return;
3669        };
3670        let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
3671            return;
3672        };
3673        let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
3674            self.tcx.parent_hir_node(pat.hir_id)
3675        else {
3676            return;
3677        };
3678        let hir::ExprKind::Block(block, None) = init.kind else {
3679            return;
3680        };
3681        if block.expr.is_some() {
3682            return;
3683        }
3684        let [.., stmt] = block.stmts else {
3685            err.span_label(block.span, "this empty block is missing a tail expression");
3686            return;
3687        };
3688        let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
3689            return;
3690        };
3691        let Some(ty) = self.node_ty_opt(tail_expr.hir_id) else {
3692            return;
3693        };
3694        if self.can_eq(self.param_env, expected_ty, ty)
3695            // FIXME: this happens with macro calls. Need to figure out why the stmt
3696            // `println!();` doesn't include the `;` in its `Span`. (#133845)
3697            // We filter these out to avoid ICEs with debug assertions on caused by
3698            // empty suggestions.
3699            && stmt.span.hi() != tail_expr.span.hi()
3700        {
3701            err.span_suggestion_short(
3702                stmt.span.with_lo(tail_expr.span.hi()),
3703                "remove this semicolon",
3704                "",
3705                Applicability::MachineApplicable,
3706            );
3707        } else {
3708            err.span_label(block.span, "this block is missing a tail expression");
3709        }
3710    }
3711
3712    pub(crate) fn suggest_swapping_lhs_and_rhs(
3713        &self,
3714        err: &mut Diag<'_>,
3715        rhs_ty: Ty<'tcx>,
3716        lhs_ty: Ty<'tcx>,
3717        rhs_expr: &'tcx hir::Expr<'tcx>,
3718        lhs_expr: &'tcx hir::Expr<'tcx>,
3719    ) {
3720        if let Some(partial_eq_def_id) = self.infcx.tcx.lang_items().eq_trait()
3721            && self
3722                .infcx
3723                .type_implements_trait(partial_eq_def_id, [rhs_ty, lhs_ty], self.param_env)
3724                .must_apply_modulo_regions()
3725        {
3726            let sm = self.tcx.sess.source_map();
3727            // If the span of rhs_expr or lhs_expr is in an external macro,
3728            // we just suppress the suggestion. See issue #139050
3729            if !rhs_expr.span.in_external_macro(sm)
3730                && !lhs_expr.span.in_external_macro(sm)
3731                && let Ok(rhs_snippet) = sm.span_to_snippet(rhs_expr.span)
3732                && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_expr.span)
3733            {
3734                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` implements `PartialEq<{1}>`",
                rhs_ty, lhs_ty))
    })format!("`{rhs_ty}` implements `PartialEq<{lhs_ty}>`"));
3735                err.multipart_suggestion(
3736                    "consider swapping the equality",
3737                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(lhs_expr.span, rhs_snippet), (rhs_expr.span, lhs_snippet)]))vec![(lhs_expr.span, rhs_snippet), (rhs_expr.span, lhs_snippet)],
3738                    Applicability::MaybeIncorrect,
3739                );
3740            }
3741        }
3742    }
3743}