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::intravisit::Visitor;
11use rustc_hir::lang_items::LangItem;
12use rustc_hir::{
13    self as hir, Arm, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, ExprKind,
14    GenericBound, HirId, LoopSource, Node, PatExpr, PatExprKind, Path, QPath, Stmt, StmtKind,
15    TyKind, WherePredicateKind, expr_needs_parens, is_range_literal,
16};
17use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
18use rustc_hir_analysis::suggest_impl_trait;
19use rustc_middle::middle::stability::EvalResult;
20use rustc_middle::span_bug;
21use rustc_middle::ty::print::with_no_trimmed_paths;
22use rustc_middle::ty::{
23    self, Article, Binder, IsSuggestable, Ty, TyCtxt, TypeVisitableExt, Unnormalized, Upcast,
24    suggest_constraining_type_params,
25};
26use rustc_session::errors::ExprParenthesesNeeded;
27use rustc_span::{ExpnKind, Ident, MacroKind, Span, Spanned, Symbol, sym};
28use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
29use rustc_trait_selection::error_reporting::traits::DefIdOrName;
30use rustc_trait_selection::error_reporting::traits::suggestions::ReturnsVisitor;
31use rustc_trait_selection::infer::InferCtxtExt;
32use rustc_trait_selection::traits;
33use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
34use tracing::{debug, instrument};
35
36use super::FnCtxt;
37use crate::errors::{self, SuggestBoxingForReturnImplTrait};
38use crate::fn_ctxt::rustc_span::BytePos;
39use crate::method::probe;
40use crate::method::probe::{IsSuggestion, Mode, ProbeScope};
41
42impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43    pub(crate) fn body_fn_sig(&self) -> Option<ty::FnSig<'tcx>> {
44        self.typeck_results
45            .borrow()
46            .liberated_fn_sigs()
47            .get(self.tcx.local_def_id_to_hir_id(self.body_id))
48            .copied()
49    }
50
51    pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diag<'_>) {
52        // This suggestion is incorrect for
53        // fn foo() -> bool { match () { () => true } || match () { () => true } }
54        err.span_suggestion_short(
55            span.shrink_to_hi(),
56            "consider using a semicolon here",
57            ";",
58            Applicability::MaybeIncorrect,
59        );
60    }
61
62    /// On implicit return expressions with mismatched types, provides the following suggestions:
63    ///
64    /// - Points out the method's return type as the reason for the expected type.
65    /// - Possible missing semicolon.
66    /// - Possible missing return type if the return type is the default, and not `fn main()`.
67    pub(crate) fn suggest_mismatched_types_on_tail(
68        &self,
69        err: &mut Diag<'_>,
70        expr: &'tcx hir::Expr<'tcx>,
71        expected: Ty<'tcx>,
72        found: Ty<'tcx>,
73        blk_id: HirId,
74    ) -> bool {
75        let expr = expr.peel_drop_temps();
76        let mut pointing_at_return_type = false;
77        if let hir::ExprKind::Break(..) = expr.kind {
78            // `break` type mismatches provide better context for tail `loop` expressions.
79            return false;
80        }
81        if let Some((fn_id, fn_decl)) = self.get_fn_decl(blk_id) {
82            pointing_at_return_type =
83                self.suggest_missing_return_type(err, fn_decl, expected, found, fn_id);
84            self.suggest_missing_break_or_return_expr(
85                err, expr, fn_decl, expected, found, blk_id, fn_id,
86            );
87        }
88        pointing_at_return_type
89    }
90
91    /// When encountering an fn-like type, try accessing the output of the type
92    /// and suggesting calling it if it satisfies a predicate (i.e. if the
93    /// output has a method or a field):
94    /// ```compile_fail,E0308
95    /// fn foo(x: usize) -> usize { x }
96    /// let x: usize = foo;  // suggest calling the `foo` function: `foo(42)`
97    /// ```
98    pub(crate) fn suggest_fn_call(
99        &self,
100        err: &mut Diag<'_>,
101        expr: &hir::Expr<'_>,
102        found: Ty<'tcx>,
103        can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
104    ) -> bool {
105        let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(found) else {
106            return false;
107        };
108        if can_satisfy(output) {
109            let (sugg_call, mut applicability) = match inputs.len() {
110                0 => ("".to_string(), Applicability::MachineApplicable),
111                1..=4 => (
112                    inputs
113                        .iter()
114                        .map(|ty| {
115                            if ty.is_suggestable(self.tcx, false) {
116                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/* {0} */", ty))
    })format!("/* {ty} */")
117                            } else {
118                                "/* value */".to_string()
119                            }
120                        })
121                        .collect::<Vec<_>>()
122                        .join(", "),
123                    Applicability::HasPlaceholders,
124                ),
125                _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
126            };
127
128            let msg = match def_id_or_name {
129                DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
130                    DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
131                    DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
132                    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)),
133                },
134                DefIdOrName::Name(name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("call this {0}", name))
    })format!("call this {name}"),
135            };
136
137            let sugg = match expr.kind {
138                hir::ExprKind::Call(..)
139                | hir::ExprKind::Path(..)
140                | hir::ExprKind::Index(..)
141                | hir::ExprKind::Lit(..) => {
142                    ::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})"))]
143                }
144                hir::ExprKind::Closure { .. } => {
145                    // Might be `{ expr } || { bool }`
146                    applicability = Applicability::MaybeIncorrect;
147                    ::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![
148                        (expr.span.shrink_to_lo(), "(".to_string()),
149                        (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
150                    ]
151                }
152                _ => {
153                    ::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![
154                        (expr.span.shrink_to_lo(), "(".to_string()),
155                        (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
156                    ]
157                }
158            };
159
160            err.multipart_suggestion(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use parentheses to {0}", msg))
    })format!("use parentheses to {msg}"), sugg, applicability);
161            return true;
162        }
163        false
164    }
165
166    /// Extracts information about a callable type for diagnostics. This is a
167    /// heuristic -- it doesn't necessarily mean that a type is always callable,
168    /// because the callable type must also be well-formed to be called.
169    pub(in super::super) fn extract_callable_info(
170        &self,
171        ty: Ty<'tcx>,
172    ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
173        self.err_ctxt().extract_callable_info(self.body_id, self.param_env, ty)
174    }
175
176    pub(crate) fn suggest_two_fn_call(
177        &self,
178        err: &mut Diag<'_>,
179        lhs_expr: &'tcx hir::Expr<'tcx>,
180        lhs_ty: Ty<'tcx>,
181        rhs_expr: &'tcx hir::Expr<'tcx>,
182        rhs_ty: Ty<'tcx>,
183        can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
184    ) -> bool {
185        if lhs_expr.span.in_derive_expansion() || rhs_expr.span.in_derive_expansion() {
186            return false;
187        }
188        let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_ty) else {
189            return false;
190        };
191        let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_ty) else {
192            return false;
193        };
194
195        if can_satisfy(lhs_output_ty, rhs_output_ty) {
196            let mut sugg = ::alloc::vec::Vec::new()vec![];
197            let mut applicability = Applicability::MachineApplicable;
198
199            for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
200                let (sugg_call, this_applicability) = match inputs.len() {
201                    0 => ("".to_string(), Applicability::MachineApplicable),
202                    1..=4 => (
203                        inputs
204                            .iter()
205                            .map(|ty| {
206                                if ty.is_suggestable(self.tcx, false) {
207                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/* {0} */", ty))
    })format!("/* {ty} */")
208                                } else {
209                                    "/* value */".to_string()
210                                }
211                            })
212                            .collect::<Vec<_>>()
213                            .join(", "),
214                        Applicability::HasPlaceholders,
215                    ),
216                    _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
217                };
218
219                applicability = applicability.max(this_applicability);
220
221                match expr.kind {
222                    hir::ExprKind::Call(..)
223                    | hir::ExprKind::Path(..)
224                    | hir::ExprKind::Index(..)
225                    | hir::ExprKind::Lit(..) => {
226                        sugg.extend([(expr.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})", sugg_call))
    })format!("({sugg_call})"))]);
227                    }
228                    hir::ExprKind::Closure { .. } => {
229                        // Might be `{ expr } || { bool }`
230                        applicability = Applicability::MaybeIncorrect;
231                        sugg.extend([
232                            (expr.span.shrink_to_lo(), "(".to_string()),
233                            (expr.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(")({0})", sugg_call))
    })format!(")({sugg_call})")),
234                        ]);
235                    }
236                    _ => {
237                        sugg.extend([
238                            (expr.span.shrink_to_lo(), "(".to_string()),
239                            (expr.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(")({0})", sugg_call))
    })format!(")({sugg_call})")),
240                        ]);
241                    }
242                }
243            }
244
245            err.multipart_suggestion("use parentheses to call these", sugg, applicability);
246
247            true
248        } else {
249            false
250        }
251    }
252
253    pub(crate) fn suggest_remove_last_method_call(
254        &self,
255        err: &mut Diag<'_>,
256        expr: &hir::Expr<'tcx>,
257        expected: Ty<'tcx>,
258    ) -> bool {
259        if let hir::ExprKind::MethodCall(hir::PathSegment { ident: method, .. }, recv_expr, &[], _) =
260            expr.kind
261            && let Some(recv_ty) = self.typeck_results.borrow().expr_ty_opt(recv_expr)
262            && self.may_coerce(recv_ty, expected)
263            && let name = method.name.as_str()
264            && (name.starts_with("to_") || name.starts_with("as_") || name == "into")
265        {
266            let span = if let Some(recv_span) = recv_expr.span.find_ancestor_inside(expr.span) {
267                expr.span.with_lo(recv_span.hi())
268            } else {
269                expr.span.with_lo(method.span.lo() - rustc_span::BytePos(1))
270            };
271            err.span_suggestion_verbose(
272                span,
273                "try removing the method call",
274                "",
275                Applicability::MachineApplicable,
276            );
277            return true;
278        }
279        false
280    }
281
282    pub(crate) fn suggest_deref_ref_or_into(
283        &self,
284        err: &mut Diag<'_>,
285        expr: &hir::Expr<'tcx>,
286        expected: Ty<'tcx>,
287        found: Ty<'tcx>,
288        expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
289    ) -> bool {
290        let expr = expr.peel_blocks();
291        let methods =
292            self.get_conversion_methods_for_diagnostic(expr.span, expected, found, expr.hir_id);
293
294        if let Some((suggestion, msg, applicability, verbose, annotation)) =
295            self.suggest_deref_or_ref(expr, found, expected)
296        {
297            if verbose {
298                err.multipart_suggestion(msg, suggestion, applicability);
299            } else {
300                err.multipart_suggestion(msg, suggestion, applicability);
301            }
302            if annotation {
303                let suggest_annotation = match expr.peel_drop_temps().kind {
304                    hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, _) => mutbl.ref_prefix_str(),
305                    _ => return true,
306                };
307                let mut tuple_indexes = Vec::new();
308                let mut expr_id = expr.hir_id;
309                for (parent_id, node) in self.tcx.hir_parent_iter(expr.hir_id) {
310                    match node {
311                        Node::Expr(&Expr { kind: ExprKind::Tup(subs), .. }) => {
312                            tuple_indexes.push(
313                                subs.iter()
314                                    .enumerate()
315                                    .find(|(_, sub_expr)| sub_expr.hir_id == expr_id)
316                                    .unwrap()
317                                    .0,
318                            );
319                            expr_id = parent_id;
320                        }
321                        Node::LetStmt(local) => {
322                            if let Some(mut ty) = local.ty {
323                                while let Some(index) = tuple_indexes.pop() {
324                                    match ty.kind {
325                                        TyKind::Tup(tys) => ty = &tys[index],
326                                        _ => return true,
327                                    }
328                                }
329                                let annotation_span = ty.span;
330                                err.span_suggestion(
331                                    annotation_span.with_hi(annotation_span.lo()),
332                                    "alternatively, consider changing the type annotation",
333                                    suggest_annotation,
334                                    Applicability::MaybeIncorrect,
335                                );
336                            }
337                            break;
338                        }
339                        _ => break,
340                    }
341                }
342            }
343            return true;
344        }
345
346        if self.suggest_else_fn_with_closure(err, expr, found, expected) {
347            return true;
348        }
349
350        if self.suggest_fn_call(err, expr, found, |output| self.may_coerce(output, expected))
351            && let ty::FnDef(def_id, ..) = *found.kind()
352            && let Some(sp) = self.tcx.hir_span_if_local(def_id)
353        {
354            let name = self.tcx.item_name(def_id);
355            let kind = self.tcx.def_kind(def_id);
356            if let DefKind::Ctor(of, CtorKind::Fn) = kind {
357                err.span_label(
358                    sp,
359                    ::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!(
360                        "`{name}` defines {} constructor here, which should be called",
361                        match of {
362                            CtorOf::Struct => "a struct",
363                            CtorOf::Variant => "an enum variant",
364                        }
365                    ),
366                );
367            } else {
368                let descr = self.tcx.def_kind_descr(kind, def_id);
369                err.span_label(sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}` defined here", descr,
                name))
    })format!("{descr} `{name}` defined here"));
370            }
371            return true;
372        }
373
374        if self.suggest_cast(err, expr, found, expected, expected_ty_expr) {
375            return true;
376        }
377
378        if !methods.is_empty() {
379            let mut suggestions = methods
380                .iter()
381                .filter_map(|conversion_method| {
382                    let conversion_method_name = conversion_method.name();
383                    let receiver_method_ident = expr.method_ident();
384                    if let Some(method_ident) = receiver_method_ident
385                        && method_ident.name == conversion_method_name
386                    {
387                        return None; // do not suggest code that is already there (#53348)
388                    }
389
390                    let method_call_list = [sym::to_vec, sym::to_string];
391                    let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
392                        && receiver_method.ident.name == sym::clone
393                        && method_call_list.contains(&conversion_method_name)
394                    // If receiver is `.clone()` and found type has one of those methods,
395                    // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
396                    // to an owned type (`Vec` or `String`). These conversions clone internally,
397                    // so we remove the user's `clone` call.
398                    {
399                        ::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())]
400                    } else if self.precedence(expr) < ExprPrecedence::Unambiguous {
401                        ::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![
402                            (expr.span.shrink_to_lo(), "(".to_string()),
403                            (expr.span.shrink_to_hi(), format!(").{}()", conversion_method_name)),
404                        ]
405                    } else {
406                        ::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))]
407                    };
408                    let struct_pat_shorthand_field =
409                        self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr);
410                    if let Some(name) = struct_pat_shorthand_field {
411                        sugg.insert(0, (expr.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", name))
    })format!("{name}: ")));
412                    }
413                    Some(sugg)
414                })
415                .peekable();
416            if suggestions.peek().is_some() {
417                err.multipart_suggestions(
418                    "try using a conversion method",
419                    suggestions,
420                    Applicability::MaybeIncorrect,
421                );
422                return true;
423            }
424        }
425
426        if let Some((found_ty_inner, expected_ty_inner, error_tys)) =
427            self.deconstruct_option_or_result(found, expected)
428            && let ty::Ref(_, peeled, hir::Mutability::Not) = *expected_ty_inner.kind()
429        {
430            // Suggest removing any stray borrows (unless there's macro shenanigans involved).
431            let inner_expr = expr.peel_borrows();
432            if !inner_expr.span.eq_ctxt(expr.span) {
433                return false;
434            }
435            let borrow_removal_span = if inner_expr.hir_id == expr.hir_id {
436                None
437            } else {
438                Some(expr.span.shrink_to_lo().until(inner_expr.span))
439            };
440            // Given `Result<_, E>`, check our expected ty is `Result<_, &E>` for
441            // `as_ref` and `as_deref` compatibility.
442            let error_tys_equate_as_ref = error_tys.is_none_or(|(found, expected)| {
443                self.can_eq(
444                    self.param_env,
445                    Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, found),
446                    expected,
447                )
448            });
449
450            let prefix_wrap = |sugg: &str| {
451                if let Some(name) = self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
452                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}{1}", name, sugg))
    })format!(": {}{}", name, sugg)
453                } else {
454                    sugg.to_string()
455                }
456            };
457
458            // FIXME: This could/should be extended to suggest `as_mut` and `as_deref_mut`,
459            // but those checks need to be a bit more delicate and the benefit is diminishing.
460            if self.can_eq(self.param_env, found_ty_inner, peeled) && error_tys_equate_as_ref {
461                let sugg = prefix_wrap(".as_ref()");
462                err.subdiagnostic(errors::SuggestConvertViaMethod {
463                    span: expr.span.shrink_to_hi(),
464                    sugg,
465                    expected,
466                    found,
467                    borrow_removal_span,
468                });
469                return true;
470            } else if let ty::Ref(_, peeled_found_ty, _) = found_ty_inner.kind()
471                && let ty::Adt(adt, _) = peeled_found_ty.peel_refs().kind()
472                && self.tcx.is_lang_item(adt.did(), LangItem::String)
473                && peeled.is_str()
474                // `Result::map`, conversely, does not take ref of the error type.
475                && error_tys.is_none_or(|(found, expected)| {
476                    self.can_eq(self.param_env, found, expected)
477                })
478            {
479                let sugg = prefix_wrap(".map(|x| x.as_str())");
480                err.span_suggestion_verbose(
481                    expr.span.shrink_to_hi(),
482                    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`"),
483                    sugg,
484                    Applicability::MachineApplicable,
485                );
486                return true;
487            } else {
488                if !error_tys_equate_as_ref {
489                    return false;
490                }
491                let mut steps = self.autoderef(expr.span, found_ty_inner).silence_errors();
492                if let Some((deref_ty, _)) = steps.nth(1)
493                    && self.can_eq(self.param_env, deref_ty, peeled)
494                {
495                    let sugg = prefix_wrap(".as_deref()");
496                    err.subdiagnostic(errors::SuggestConvertViaMethod {
497                        span: expr.span.shrink_to_hi(),
498                        sugg,
499                        expected,
500                        found,
501                        borrow_removal_span,
502                    });
503                    return true;
504                }
505                for (deref_ty, n_step) in steps {
506                    if self.can_eq(self.param_env, deref_ty, peeled) {
507                        let explicit_deref = "*".repeat(n_step);
508                        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)"));
509                        err.subdiagnostic(errors::SuggestConvertViaMethod {
510                            span: expr.span.shrink_to_hi(),
511                            sugg,
512                            expected,
513                            found,
514                            borrow_removal_span,
515                        });
516                        return true;
517                    }
518                }
519            }
520        }
521
522        false
523    }
524
525    /// If `ty` is `Option<T>`, returns `T, T, None`.
526    /// If `ty` is `Result<T, E>`, returns `T, T, Some(E, E)`.
527    /// Otherwise, returns `None`.
528    fn deconstruct_option_or_result(
529        &self,
530        found_ty: Ty<'tcx>,
531        expected_ty: Ty<'tcx>,
532    ) -> Option<(Ty<'tcx>, Ty<'tcx>, Option<(Ty<'tcx>, Ty<'tcx>)>)> {
533        let ty::Adt(found_adt, found_args) = found_ty.peel_refs().kind() else {
534            return None;
535        };
536        let ty::Adt(expected_adt, expected_args) = expected_ty.kind() else {
537            return None;
538        };
539        if self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
540            && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
541        {
542            Some((found_args.type_at(0), expected_args.type_at(0), None))
543        } else if self.tcx.is_diagnostic_item(sym::Result, found_adt.did())
544            && self.tcx.is_diagnostic_item(sym::Result, expected_adt.did())
545        {
546            Some((
547                found_args.type_at(0),
548                expected_args.type_at(0),
549                Some((found_args.type_at(1), expected_args.type_at(1))),
550            ))
551        } else {
552            None
553        }
554    }
555
556    /// When encountering the expected boxed value allocated in the stack, suggest allocating it
557    /// in the heap by calling `Box::new()`.
558    pub(in super::super) fn suggest_boxing_when_appropriate(
559        &self,
560        err: &mut Diag<'_>,
561        span: Span,
562        hir_id: HirId,
563        expected: Ty<'tcx>,
564        found: Ty<'tcx>,
565    ) -> bool {
566        // Do not suggest `Box::new` in const context.
567        if self.tcx.hir_is_inside_const_context(hir_id) || !expected.is_box() || found.is_box() {
568            return false;
569        }
570        if self.may_coerce(Ty::new_box(self.tcx, found), expected) {
571            let suggest_boxing = match *found.kind() {
572                ty::Tuple(tuple) if tuple.is_empty() => {
573                    errors::SuggestBoxing::Unit { start: span.shrink_to_lo(), end: span }
574                }
575                ty::Coroutine(def_id, ..)
576                    if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.coroutine_kind(def_id)
    {
    Some(CoroutineKind::Desugared(CoroutineDesugaring::Async,
        CoroutineSource::Closure)) => true,
    _ => false,
}matches!(
577                        self.tcx.coroutine_kind(def_id),
578                        Some(CoroutineKind::Desugared(
579                            CoroutineDesugaring::Async,
580                            CoroutineSource::Closure
581                        ))
582                    ) =>
583                {
584                    errors::SuggestBoxing::AsyncBody
585                }
586                _ if let Node::ExprField(expr_field) = self.tcx.parent_hir_node(hir_id)
587                    && expr_field.is_shorthand =>
588                {
589                    errors::SuggestBoxing::ExprFieldShorthand {
590                        start: span.shrink_to_lo(),
591                        end: span.shrink_to_hi(),
592                        ident: expr_field.ident,
593                    }
594                }
595                _ => errors::SuggestBoxing::Other {
596                    start: span.shrink_to_lo(),
597                    end: span.shrink_to_hi(),
598                },
599            };
600            err.subdiagnostic(suggest_boxing);
601
602            true
603        } else {
604            false
605        }
606    }
607
608    /// When encountering a closure that captures variables, where a FnPtr is expected,
609    /// suggest a non-capturing closure
610    pub(in super::super) fn suggest_no_capture_closure(
611        &self,
612        err: &mut Diag<'_>,
613        expected: Ty<'tcx>,
614        found: Ty<'tcx>,
615    ) -> bool {
616        if let (ty::FnPtr(..), ty::Closure(def_id, _)) = (expected.kind(), found.kind())
617            && let Some(upvars) = self.tcx.upvars_mentioned(*def_id)
618        {
619            // Report upto four upvars being captured to reduce the amount error messages
620            // reported back to the user.
621            let spans_and_labels = upvars
622                .iter()
623                .take(4)
624                .map(|(var_hir_id, upvar)| {
625                    let var_name = self.tcx.hir_name(*var_hir_id).to_string();
626                    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` captured here", var_name))
    })format!("`{var_name}` captured here");
627                    (upvar.span, msg)
628                })
629                .collect::<Vec<_>>();
630
631            let mut multi_span: MultiSpan =
632                spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
633            for (sp, label) in spans_and_labels {
634                multi_span.push_span_label(sp, label);
635            }
636            err.span_note(
637                multi_span,
638                "closures can only be coerced to `fn` types if they do not capture any variables",
639            );
640            return true;
641        }
642        false
643    }
644
645    /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
646    #[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(646u32),
                                    ::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:675",
                                                "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(675u32),
                                                ::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))]
647    pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
648        &self,
649        err: &mut Diag<'_>,
650        expr: &hir::Expr<'_>,
651        expected: Ty<'tcx>,
652        found: Ty<'tcx>,
653    ) -> bool {
654        // Handle #68197.
655
656        if self.tcx.hir_is_inside_const_context(expr.hir_id) {
657            // Do not suggest `Box::new` in const context.
658            return false;
659        }
660        let pin_did = self.tcx.lang_items().pin_type();
661        // This guards the `new_box` below.
662        if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
663            return false;
664        }
665        let box_found = Ty::new_box(self.tcx, found);
666        let Some(pin_box_found) = Ty::new_lang_item(self.tcx, box_found, LangItem::Pin) else {
667            return false;
668        };
669        let Some(pin_found) = Ty::new_lang_item(self.tcx, found, LangItem::Pin) else {
670            return false;
671        };
672        match expected.kind() {
673            ty::Adt(def, _) if Some(def.did()) == pin_did => {
674                if self.may_coerce(pin_box_found, expected) {
675                    debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
676                    match found.kind() {
677                        ty::Adt(def, _) if def.is_box() => {
678                            err.help("use `Box::pin`");
679                        }
680                        _ => {
681                            let prefix = if let Some(name) =
682                                self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr)
683                            {
684                                format!("{}: ", name)
685                            } else {
686                                String::new()
687                            };
688                            let suggestion = vec![
689                                (expr.span.shrink_to_lo(), format!("{prefix}Box::pin(")),
690                                (expr.span.shrink_to_hi(), ")".to_string()),
691                            ];
692                            err.multipart_suggestion(
693                                "you need to pin and box this expression",
694                                suggestion,
695                                Applicability::MaybeIncorrect,
696                            );
697                        }
698                    }
699                    true
700                } else if self.may_coerce(pin_found, expected) {
701                    match found.kind() {
702                        ty::Adt(def, _) if def.is_box() => {
703                            err.help("use `Box::pin`");
704                            true
705                        }
706                        _ => false,
707                    }
708                } else {
709                    false
710                }
711            }
712            ty::Adt(def, _) if def.is_box() && self.may_coerce(box_found, expected) => {
713                // Check if the parent expression is a call to Pin::new. If it
714                // is and we were expecting a Box, ergo Pin<Box<expected>>, we
715                // can suggest Box::pin.
716                let Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. }) =
717                    self.tcx.parent_hir_node(expr.hir_id)
718                else {
719                    return false;
720                };
721                match fn_name.kind {
722                    ExprKind::Path(QPath::TypeRelative(
723                        hir::Ty {
724                            kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
725                            ..
726                        },
727                        method,
728                    )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
729                        err.span_suggestion(
730                            fn_name.span,
731                            "use `Box::pin` to pin and box this expression",
732                            "Box::pin",
733                            Applicability::MachineApplicable,
734                        );
735                        true
736                    }
737                    _ => false,
738                }
739            }
740            _ => false,
741        }
742    }
743
744    /// A common error is to forget to add a semicolon at the end of a block, e.g.,
745    ///
746    /// ```compile_fail,E0308
747    /// # fn bar_that_returns_u32() -> u32 { 4 }
748    /// fn foo() {
749    ///     bar_that_returns_u32()
750    /// }
751    /// ```
752    ///
753    /// This routine checks if the return expression in a block would make sense on its own as a
754    /// statement and the return type has been left as default or has been specified as `()`. If so,
755    /// it suggests adding a semicolon.
756    ///
757    /// If the expression is the expression of a closure without block (`|| expr`), a
758    /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
759    pub(crate) fn suggest_missing_semicolon(
760        &self,
761        err: &mut Diag<'_>,
762        expression: &'tcx hir::Expr<'tcx>,
763        expected: Ty<'tcx>,
764        needs_block: bool,
765        parent_is_closure: bool,
766    ) {
767        if !expected.is_unit() {
768            return;
769        }
770        // `BlockTailExpression` only relevant if the tail expr would be
771        // useful on its own.
772        match expression.kind {
773            ExprKind::Call(..)
774            | ExprKind::MethodCall(..)
775            | ExprKind::Loop(..)
776            | ExprKind::If(..)
777            | ExprKind::Match(..)
778            | ExprKind::Block(..)
779                if expression.can_have_side_effects()
780                    // If the expression is from an external macro, then do not suggest
781                    // adding a semicolon, because there's nowhere to put it.
782                    // See issue #81943.
783                    && !expression.span.in_external_macro(self.tcx.sess.source_map()) =>
784            {
785                if needs_block {
786                    err.multipart_suggestion(
787                        "consider using a semicolon here",
788                        ::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![
789                            (expression.span.shrink_to_lo(), "{ ".to_owned()),
790                            (expression.span.shrink_to_hi(), "; }".to_owned()),
791                        ],
792                        Applicability::MachineApplicable,
793                    );
794                } else if let hir::Node::Block(block) = self.tcx.parent_hir_node(expression.hir_id)
795                    && let hir::Node::Expr(expr) = self.tcx.parent_hir_node(block.hir_id)
796                    && let hir::Node::Expr(if_expr) = self.tcx.parent_hir_node(expr.hir_id)
797                    && let hir::ExprKind::If(_cond, _then, Some(_else)) = if_expr.kind
798                    && let hir::Node::Stmt(stmt) = self.tcx.parent_hir_node(if_expr.hir_id)
799                    && let hir::StmtKind::Expr(_) = stmt.kind
800                    && self.is_next_stmt_expr_continuation(stmt.hir_id)
801                {
802                    err.subdiagnostic(ExprParenthesesNeeded::surrounding(stmt.span));
803                } else {
804                    err.span_suggestion(
805                        expression.span.shrink_to_hi(),
806                        "consider using a semicolon here",
807                        ";",
808                        Applicability::MachineApplicable,
809                    );
810                }
811            }
812            ExprKind::Path(..) | ExprKind::Lit(_)
813                if parent_is_closure
814                    && !expression.span.in_external_macro(self.tcx.sess.source_map()) =>
815            {
816                err.span_suggestion_verbose(
817                    expression.span.shrink_to_lo(),
818                    "consider ignoring the value",
819                    "_ = ",
820                    Applicability::MachineApplicable,
821                );
822            }
823            _ => {
824                if let hir::Node::Block(block) = self.tcx.parent_hir_node(expression.hir_id)
825                    && let hir::Node::Expr(expr) = self.tcx.parent_hir_node(block.hir_id)
826                    && let hir::Node::Expr(if_expr) = self.tcx.parent_hir_node(expr.hir_id)
827                    && let hir::ExprKind::If(_cond, _then, Some(_else)) = if_expr.kind
828                    && let hir::Node::Stmt(stmt) = self.tcx.parent_hir_node(if_expr.hir_id)
829                    && let hir::StmtKind::Expr(_) = stmt.kind
830                    && self.is_next_stmt_expr_continuation(stmt.hir_id)
831                {
832                    // The error is pointing at an arm of an if-expression, and we want to get the
833                    // `Span` of the whole if-expression for the suggestion. This only works for a
834                    // single level of nesting, which is fine.
835                    // We have something like `if true { false } else { true } && true`. Suggest
836                    // wrapping in parentheses. We find the statement or expression following the
837                    // `if` (`&& true`) and see if it is something that can reasonably be
838                    // interpreted as a binop following an expression.
839                    err.subdiagnostic(ExprParenthesesNeeded::surrounding(stmt.span));
840                }
841            }
842        }
843    }
844
845    pub(crate) fn is_next_stmt_expr_continuation(&self, hir_id: HirId) -> bool {
846        if let hir::Node::Block(b) = self.tcx.parent_hir_node(hir_id)
847            && let mut stmts = b.stmts.iter().skip_while(|s| s.hir_id != hir_id)
848            && let Some(_) = stmts.next() // The statement the statement that was passed in
849            && let Some(next) = match (stmts.next(), b.expr) { // The following statement
850                (Some(next), _) => match next.kind {
851                    hir::StmtKind::Expr(next) | hir::StmtKind::Semi(next) => Some(next),
852                    _ => None,
853                },
854                (None, Some(next)) => Some(next),
855                _ => None,
856            }
857            && let hir::ExprKind::AddrOf(..) // prev_stmt && next
858                | hir::ExprKind::Unary(..) // prev_stmt * next
859                | hir::ExprKind::Err(_) = next.kind
860        // prev_stmt + next
861        {
862            true
863        } else {
864            false
865        }
866    }
867
868    /// A possible error is to forget to add a return type that is needed:
869    ///
870    /// ```compile_fail,E0308
871    /// # fn bar_that_returns_u32() -> u32 { 4 }
872    /// fn foo() {
873    ///     bar_that_returns_u32()
874    /// }
875    /// ```
876    ///
877    /// This routine checks if the return type is left as default, the method is not part of an
878    /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
879    /// type.
880    #[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(880u32),
                                    ::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 &&
                            !trait_ref.trait_ref.path.segments.last().and_then(|seg|
                                            seg.args).map_or(false, |args| !args.constraints.is_empty())
                        {
                        let trait_name =
                            trait_ref.trait_ref.path.segments.iter().map(|seg|
                                            seg.ident.as_str()).collect::<Vec<_>>().join("::");
                        err.subdiagnostic(errors::ExpectedReturnTypeLabel::ImplTrait {
                                span: hir_ty.span,
                                trait_name,
                            });
                        if let Some(ret_coercion_span) =
                                self.ret_coercion_span.get() {
                            let expected_name = expected.to_string();
                            err.span_label(ret_coercion_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("return type resolved to be `{0}`",
                                                expected_name))
                                    }));
                        }
                        let trait_def_id = trait_ref.trait_ref.path.res.def_id();
                        if self.tcx.is_dyn_compatible(trait_def_id) {
                            err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
                                    start_sp: hir_ty.span.with_hi(hir_ty.span.lo() +
                                            BytePos(4)),
                                    end_sp: hir_ty.span.shrink_to_hi(),
                                });
                            let body = self.tcx.hir_body_owned_by(fn_id);
                            let mut visitor = ReturnsVisitor::default();
                            visitor.visit_body(&body);
                            if !visitor.returns.is_empty() {
                                let starts: Vec<Span> =
                                    visitor.returns.iter().filter(|expr|
                                                    expr.span.can_be_used_for_suggestions()).map(|expr|
                                                expr.span.shrink_to_lo()).collect();
                                let ends: Vec<Span> =
                                    visitor.returns.iter().filter(|expr|
                                                    expr.span.can_be_used_for_suggestions()).map(|expr|
                                                expr.span.shrink_to_hi()).collect();
                                if !starts.is_empty() {
                                    err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr {
                                            starts,
                                            ends,
                                        });
                                }
                            }
                        }
                        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;
                    } else 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:1001",
                                                "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(1001u32),
                                                ::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:1019",
                                                "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(1019u32),
                                                ::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:1021",
                                                "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(1021u32),
                                                ::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:1022",
                                                "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(1022u32),
                                                ::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, Unnormalized::new_wip(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))]
881    pub(in super::super) fn suggest_missing_return_type(
882        &self,
883        err: &mut Diag<'_>,
884        fn_decl: &hir::FnDecl<'tcx>,
885        expected: Ty<'tcx>,
886        found: Ty<'tcx>,
887        fn_id: LocalDefId,
888    ) -> bool {
889        // Can't suggest `->` on a block-like coroutine
890        if let Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Block)) =
891            self.tcx.coroutine_kind(fn_id)
892        {
893            return false;
894        }
895
896        let found =
897            self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
898        // Only suggest changing the return type for methods that
899        // haven't set a return type at all (and aren't `fn main()`, impl or closure).
900        match &fn_decl.output {
901            // For closure with default returns, don't suggest adding return type
902            &hir::FnRetTy::DefaultReturn(_) if self.tcx.is_closure_like(fn_id.to_def_id()) => {}
903            &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
904                if !self.can_add_return_type(fn_id) {
905                    err.subdiagnostic(errors::ExpectedReturnTypeLabel::Unit { span });
906                } else if let Some(found) = found.make_suggestable(self.tcx, false, None) {
907                    err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
908                        span,
909                        found: found.to_string(),
910                    });
911                } else if let Some(sugg) = suggest_impl_trait(self, self.param_env, found) {
912                    err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { span, found: sugg });
913                } else {
914                    // FIXME: if `found` could be `impl Iterator` we should suggest that.
915                    err.subdiagnostic(errors::AddReturnTypeSuggestion::MissingHere { span });
916                }
917
918                return true;
919            }
920            hir::FnRetTy::Return(hir_ty) => {
921                if let hir::TyKind::OpaqueDef(op_ty, ..) = hir_ty.kind
922                    && let [hir::GenericBound::Trait(trait_ref)] = op_ty.bounds
923                    && !trait_ref
924                        .trait_ref
925                        .path
926                        .segments
927                        .last()
928                        .and_then(|seg| seg.args)
929                        .map_or(false, |args| !args.constraints.is_empty())
930                {
931                    // Use the path to get the trait name string
932                    let trait_name = trait_ref
933                        .trait_ref
934                        .path
935                        .segments
936                        .iter()
937                        .map(|seg| seg.ident.as_str())
938                        .collect::<Vec<_>>()
939                        .join("::");
940
941                    err.subdiagnostic(errors::ExpectedReturnTypeLabel::ImplTrait {
942                        span: hir_ty.span,
943                        trait_name,
944                    });
945
946                    if let Some(ret_coercion_span) = self.ret_coercion_span.get() {
947                        let expected_name = expected.to_string();
948                        err.span_label(
949                            ret_coercion_span,
950                            format!("return type resolved to be `{expected_name}`"),
951                        );
952                    }
953
954                    let trait_def_id = trait_ref.trait_ref.path.res.def_id();
955                    if self.tcx.is_dyn_compatible(trait_def_id) {
956                        err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
957                            start_sp: hir_ty.span.with_hi(hir_ty.span.lo() + BytePos(4)),
958                            end_sp: hir_ty.span.shrink_to_hi(),
959                        });
960
961                        let body = self.tcx.hir_body_owned_by(fn_id);
962                        let mut visitor = ReturnsVisitor::default();
963                        visitor.visit_body(&body);
964
965                        if !visitor.returns.is_empty() {
966                            let starts: Vec<Span> = visitor
967                                .returns
968                                .iter()
969                                .filter(|expr| expr.span.can_be_used_for_suggestions())
970                                .map(|expr| expr.span.shrink_to_lo())
971                                .collect();
972                            let ends: Vec<Span> = visitor
973                                .returns
974                                .iter()
975                                .filter(|expr| expr.span.can_be_used_for_suggestions())
976                                .map(|expr| expr.span.shrink_to_hi())
977                                .collect();
978
979                            if !starts.is_empty() {
980                                err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr {
981                                    starts,
982                                    ends,
983                                });
984                            }
985                        }
986                    }
987
988                    self.try_suggest_return_impl_trait(err, expected, found, fn_id);
989                    self.try_note_caller_chooses_ty_for_ty_param(err, expected, found);
990                    return true;
991                } else if let hir::TyKind::OpaqueDef(op_ty, ..) = hir_ty.kind
992                    // FIXME: account for RPITIT.
993                    && let [hir::GenericBound::Trait(trait_ref)] = op_ty.bounds
994                    && let Some(hir::PathSegment { args: Some(generic_args), .. }) =
995                        trait_ref.trait_ref.path.segments.last()
996                    && let [constraint] = generic_args.constraints
997                    && let Some(ty) = constraint.ty()
998                {
999                    // Check if async function's return type was omitted.
1000                    // Don't emit suggestions if the found type is `impl Future<...>`.
1001                    debug!(?found);
1002                    if found.is_suggestable(self.tcx, false) {
1003                        if ty.span.is_empty() {
1004                            err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
1005                                span: ty.span,
1006                                found: found.to_string(),
1007                            });
1008                            return true;
1009                        } else {
1010                            err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
1011                                span: ty.span,
1012                                expected,
1013                            });
1014                        }
1015                    }
1016                } else {
1017                    // Only point to return type if the expected type is the return type, as if they
1018                    // are not, the expectation must have been caused by something else.
1019                    debug!(?hir_ty, "return type");
1020                    let ty = self.lowerer().lower_ty(hir_ty);
1021                    debug!(?ty, "return type (lowered)");
1022                    debug!(?expected, "expected type");
1023                    let bound_vars =
1024                        self.tcx.late_bound_vars(self.tcx.local_def_id_to_hir_id(fn_id));
1025                    let ty = Binder::bind_with_vars(ty, bound_vars);
1026                    let ty = self.normalize(hir_ty.span, Unnormalized::new_wip(ty));
1027                    let ty = self.tcx.instantiate_bound_regions_with_erased(ty);
1028                    if self.may_coerce(expected, ty) {
1029                        err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
1030                            span: hir_ty.span,
1031                            expected,
1032                        });
1033                        self.try_suggest_return_impl_trait(err, expected, found, fn_id);
1034                        self.try_note_caller_chooses_ty_for_ty_param(err, expected, found);
1035                        return true;
1036                    }
1037                }
1038            }
1039            _ => {}
1040        }
1041        false
1042    }
1043
1044    /// Checks whether we can add a return type to a function.
1045    /// Assumes given function doesn't have a explicit return type.
1046    fn can_add_return_type(&self, fn_id: LocalDefId) -> bool {
1047        match self.tcx.hir_node_by_def_id(fn_id) {
1048            Node::Item(item) => {
1049                let (ident, _, _, _) = item.expect_fn();
1050                // This is less than ideal, it will not suggest a return type span on any
1051                // method called `main`, regardless of whether it is actually the entry point,
1052                // but it will still present it as the reason for the expected type.
1053                ident.name != sym::main
1054            }
1055            Node::ImplItem(item) => {
1056                // If it doesn't impl a trait, we can add a return type
1057                let Node::Item(&hir::Item {
1058                    kind: hir::ItemKind::Impl(hir::Impl { of_trait, .. }),
1059                    ..
1060                }) = self.tcx.parent_hir_node(item.hir_id())
1061                else {
1062                    ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1063                };
1064
1065                of_trait.is_none()
1066            }
1067            _ => true,
1068        }
1069    }
1070
1071    fn try_note_caller_chooses_ty_for_ty_param(
1072        &self,
1073        diag: &mut Diag<'_>,
1074        expected: Ty<'tcx>,
1075        found: Ty<'tcx>,
1076    ) {
1077        // Only show the note if:
1078        // 1. `expected` ty is a type parameter;
1079        // 2. The `expected` type parameter does *not* occur in the return expression type. This can
1080        //    happen for e.g. `fn foo<T>(t: &T) -> T { t }`, where `expected` is `T` but `found` is
1081        //    `&T`. Saying "the caller chooses a type for `T` which can be different from `&T`" is
1082        //    "well duh" and is only confusing and not helpful.
1083        let ty::Param(expected_ty_as_param) = expected.kind() else {
1084            return;
1085        };
1086
1087        if found.contains(expected) {
1088            return;
1089        }
1090
1091        diag.subdiagnostic(errors::NoteCallerChoosesTyForTyParam {
1092            ty_param_name: expected_ty_as_param.name,
1093            found_ty: found,
1094        });
1095    }
1096
1097    /// check whether the return type is a generic type with a trait bound
1098    /// only suggest this if the generic param is not present in the arguments
1099    /// if this is true, hint them towards changing the return type to `impl Trait`
1100    /// ```compile_fail,E0308
1101    /// fn cant_name_it<T: Fn() -> u32>() -> T {
1102    ///     || 3
1103    /// }
1104    /// ```
1105    fn try_suggest_return_impl_trait(
1106        &self,
1107        err: &mut Diag<'_>,
1108        expected: Ty<'tcx>,
1109        found: Ty<'tcx>,
1110        fn_id: LocalDefId,
1111    ) {
1112        // Only apply the suggestion if:
1113        //  - the return type is a generic parameter
1114        //  - the generic param is not used as a fn param
1115        //  - the generic param has at least one bound
1116        //  - the generic param doesn't appear in any other bounds where it's not the Self type
1117        // Suggest:
1118        //  - Changing the return type to be `impl <all bounds>`
1119
1120        {
    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:1120",
                        "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(1120u32),
                        ::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);
1121
1122        let ty::Param(expected_ty_as_param) = expected.kind() else { return };
1123
1124        let fn_node = self.tcx.hir_node_by_def_id(fn_id);
1125
1126        let hir::Node::Item(hir::Item {
1127            kind:
1128                hir::ItemKind::Fn {
1129                    sig:
1130                        hir::FnSig {
1131                            decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. },
1132                            ..
1133                        },
1134                    generics: hir::Generics { params, predicates, .. },
1135                    ..
1136                },
1137            ..
1138        }) = fn_node
1139        else {
1140            return;
1141        };
1142
1143        if params.get(expected_ty_as_param.index as usize).is_none() {
1144            return;
1145        };
1146
1147        // get all where BoundPredicates here, because they are used in two cases below
1148        let where_predicates = predicates
1149            .iter()
1150            .filter_map(|p| match p.kind {
1151                WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1152                    bounds,
1153                    bounded_ty,
1154                    ..
1155                }) => {
1156                    // FIXME: Maybe these calls to `lower_ty` can be removed (and the ones below)
1157                    let ty = self.lowerer().lower_ty(bounded_ty);
1158                    Some((ty, bounds))
1159                }
1160                _ => None,
1161            })
1162            .map(|(ty, bounds)| match ty.kind() {
1163                ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
1164                // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
1165                _ => match ty.contains(expected) {
1166                    true => Err(()),
1167                    false => Ok(None),
1168                },
1169            })
1170            .collect::<Result<Vec<_>, _>>();
1171
1172        let Ok(where_predicates) = where_predicates else { return };
1173
1174        // now get all predicates in the same types as the where bounds, so we can chain them
1175        let predicates_from_where =
1176            where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
1177
1178        // extract all bounds from the source code using their spans
1179        let all_matching_bounds_strs = predicates_from_where
1180            .filter_map(|bound| match bound {
1181                GenericBound::Trait(_) => {
1182                    self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
1183                }
1184                _ => None,
1185            })
1186            .collect::<Vec<String>>();
1187
1188        if all_matching_bounds_strs.is_empty() {
1189            return;
1190        }
1191
1192        let all_bounds_str = all_matching_bounds_strs.join(" + ");
1193
1194        let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
1195                let ty = self.lowerer().lower_ty( param);
1196                #[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)
1197            });
1198
1199        if ty_param_used_in_fn_params {
1200            return;
1201        }
1202
1203        err.span_suggestion(
1204            fn_return.span(),
1205            "consider using an impl return type",
1206            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("impl {0}", all_bounds_str))
    })format!("impl {all_bounds_str}"),
1207            Applicability::MaybeIncorrect,
1208        );
1209    }
1210
1211    pub(in super::super) fn suggest_missing_break_or_return_expr(
1212        &self,
1213        err: &mut Diag<'_>,
1214        expr: &'tcx hir::Expr<'tcx>,
1215        fn_decl: &hir::FnDecl<'tcx>,
1216        expected: Ty<'tcx>,
1217        found: Ty<'tcx>,
1218        id: HirId,
1219        fn_id: LocalDefId,
1220    ) {
1221        if !expected.is_unit() {
1222            return;
1223        }
1224        let found = self.resolve_vars_if_possible(found);
1225
1226        let innermost_loop = if self.is_loop(id) {
1227            Some(self.tcx.hir_node(id))
1228        } else {
1229            self.tcx
1230                .hir_parent_iter(id)
1231                .take_while(|(_, node)| {
1232                    // look at parents until we find the first body owner
1233                    node.body_id().is_none()
1234                })
1235                .find_map(|(parent_id, node)| self.is_loop(parent_id).then_some(node))
1236        };
1237        let can_break_with_value = innermost_loop.is_some_and(|node| {
1238            #[allow(non_exhaustive_omitted_patterns)] match node {
    Node::Expr(Expr { kind: ExprKind::Loop(_, _, LoopSource::Loop, ..), .. })
        => true,
    _ => false,
}matches!(
1239                node,
1240                Node::Expr(Expr { kind: ExprKind::Loop(_, _, LoopSource::Loop, ..), .. })
1241            )
1242        });
1243
1244        let in_local_statement = self.is_local_statement(id)
1245            || self
1246                .tcx
1247                .hir_parent_iter(id)
1248                .any(|(parent_id, _)| self.is_local_statement(parent_id));
1249
1250        if can_break_with_value && in_local_statement {
1251            err.multipart_suggestion(
1252                "you might have meant to break the loop with this value",
1253                ::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![
1254                    (expr.span.shrink_to_lo(), "break ".to_string()),
1255                    (expr.span.shrink_to_hi(), ";".to_string()),
1256                ],
1257                Applicability::MaybeIncorrect,
1258            );
1259            return;
1260        }
1261
1262        let scope = self.tcx.hir_parent_iter(id).find(|(_, node)| {
1263            #[allow(non_exhaustive_omitted_patterns)] match node {
    Node::Expr(Expr { kind: ExprKind::Closure(..), .. }) | Node::Item(_) |
        Node::TraitItem(_) | Node::ImplItem(_) => true,
    _ => false,
}matches!(
1264                node,
1265                Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
1266                    | Node::Item(_)
1267                    | Node::TraitItem(_)
1268                    | Node::ImplItem(_)
1269            )
1270        });
1271        let in_closure =
1272            #[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(..), .. }))));
1273
1274        let can_return = match fn_decl.output {
1275            hir::FnRetTy::Return(ty) => {
1276                let ty = self.lowerer().lower_ty(ty);
1277                let bound_vars = self.tcx.late_bound_vars(self.tcx.local_def_id_to_hir_id(fn_id));
1278                let ty = self
1279                    .tcx
1280                    .instantiate_bound_regions_with_erased(Binder::bind_with_vars(ty, bound_vars));
1281                let ty = match self.tcx.asyncness(fn_id) {
1282                    ty::Asyncness::Yes => {
1283                        self.err_ctxt().get_impl_future_output_ty(ty).unwrap_or_else(|| {
1284                            ::rustc_middle::util::bug::span_bug_fmt(fn_decl.output.span(),
    format_args!("failed to get output type of async function"))span_bug!(
1285                                fn_decl.output.span(),
1286                                "failed to get output type of async function"
1287                            )
1288                        })
1289                    }
1290                    ty::Asyncness::No => ty,
1291                };
1292                let ty = self.normalize(expr.span, Unnormalized::new_wip(ty));
1293                self.may_coerce(found, ty)
1294            }
1295            hir::FnRetTy::DefaultReturn(_) if in_closure => {
1296                self.ret_coercion.as_ref().is_some_and(|ret| {
1297                    let ret_ty = ret.borrow().expected_ty();
1298                    self.may_coerce(found, ret_ty)
1299                })
1300            }
1301            _ => false,
1302        };
1303        if can_return
1304            && let Some(span) = expr.span.find_ancestor_inside(
1305                self.tcx.hir_span_with_body(self.tcx.local_def_id_to_hir_id(fn_id)),
1306            )
1307        {
1308            // When the expr is in a match arm's body, we shouldn't add semicolon ';' at the end.
1309            // For example:
1310            // fn mismatch_types() -> i32 {
1311            //     match 1 {
1312            //         x => dbg!(x),
1313            //     }
1314            //     todo!()
1315            // }
1316            // -------------^^^^^^^-
1317            // Don't add semicolon `;` at the end of `dbg!(x)` expr
1318            fn is_in_arm<'tcx>(expr: &'tcx hir::Expr<'tcx>, tcx: TyCtxt<'tcx>) -> bool {
1319                for (_, node) in tcx.hir_parent_iter(expr.hir_id) {
1320                    match node {
1321                        hir::Node::Block(block) => {
1322                            if let Some(ret) = block.expr
1323                                && ret.hir_id == expr.hir_id
1324                            {
1325                                continue;
1326                            }
1327                        }
1328                        hir::Node::Arm(arm) => {
1329                            if let hir::ExprKind::Block(block, _) = arm.body.kind
1330                                && let Some(ret) = block.expr
1331                                && ret.hir_id == expr.hir_id
1332                            {
1333                                return true;
1334                            }
1335                        }
1336                        hir::Node::Expr(e) if let hir::ExprKind::Block(block, _) = e.kind => {
1337                            if let Some(ret) = block.expr
1338                                && ret.hir_id == expr.hir_id
1339                            {
1340                                continue;
1341                            }
1342                        }
1343                        _ => {
1344                            return false;
1345                        }
1346                    }
1347                }
1348
1349                false
1350            }
1351            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())];
1352            if !is_in_arm(expr, self.tcx) {
1353                suggs.push((span.shrink_to_hi(), ";".to_string()));
1354            }
1355            err.multipart_suggestion(
1356                "you might have meant to return this value",
1357                suggs,
1358                Applicability::MaybeIncorrect,
1359            );
1360        }
1361    }
1362
1363    pub(in super::super) fn suggest_missing_parentheses(
1364        &self,
1365        err: &mut Diag<'_>,
1366        expr: &hir::Expr<'_>,
1367    ) -> bool {
1368        let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None);
1369        if let Some(sp) = self.tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
1370            // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
1371            err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
1372            true
1373        } else {
1374            false
1375        }
1376    }
1377
1378    /// Given an expression type mismatch, peel any `&` expressions until we get to
1379    /// a block expression, and then suggest replacing the braces with square braces
1380    /// if it was possibly mistaken array syntax.
1381    pub(crate) fn suggest_block_to_brackets_peeling_refs(
1382        &self,
1383        diag: &mut Diag<'_>,
1384        mut expr: &hir::Expr<'_>,
1385        mut expr_ty: Ty<'tcx>,
1386        mut expected_ty: Ty<'tcx>,
1387    ) -> bool {
1388        loop {
1389            match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
1390                (
1391                    hir::ExprKind::AddrOf(_, _, inner_expr),
1392                    ty::Ref(_, inner_expr_ty, _),
1393                    ty::Ref(_, inner_expected_ty, _),
1394                ) => {
1395                    expr = *inner_expr;
1396                    expr_ty = *inner_expr_ty;
1397                    expected_ty = *inner_expected_ty;
1398                }
1399                (hir::ExprKind::Block(blk, _), _, _) => {
1400                    self.suggest_block_to_brackets(diag, blk, expr_ty, expected_ty);
1401                    break true;
1402                }
1403                _ => break false,
1404            }
1405        }
1406    }
1407
1408    pub(crate) fn suggest_clone_for_ref(
1409        &self,
1410        diag: &mut Diag<'_>,
1411        expr: &hir::Expr<'_>,
1412        expr_ty: Ty<'tcx>,
1413        expected_ty: Ty<'tcx>,
1414    ) -> bool {
1415        if let ty::Ref(_, inner_ty, hir::Mutability::Not) = expr_ty.kind()
1416            && let Some(clone_trait_def) = self.tcx.lang_items().clone_trait()
1417            && expected_ty == *inner_ty
1418            && self
1419                .infcx
1420                .type_implements_trait(
1421                    clone_trait_def,
1422                    [self.tcx.erase_and_anonymize_regions(expected_ty)],
1423                    self.param_env,
1424                )
1425                .must_apply_modulo_regions()
1426        {
1427            let suggestion = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1428                Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}.clone()", ident))
    })format!(": {ident}.clone()"),
1429                None => ".clone()".to_string(),
1430            };
1431
1432            let span = expr.span.find_ancestor_not_from_macro().unwrap_or(expr.span).shrink_to_hi();
1433
1434            diag.span_suggestion_verbose(
1435                span,
1436                "consider using clone here",
1437                suggestion,
1438                Applicability::MachineApplicable,
1439            );
1440            return true;
1441        }
1442        false
1443    }
1444
1445    pub(crate) fn suggest_copied_cloned_or_as_ref(
1446        &self,
1447        diag: &mut Diag<'_>,
1448        expr: &hir::Expr<'_>,
1449        expr_ty: Ty<'tcx>,
1450        expected_ty: Ty<'tcx>,
1451    ) -> bool {
1452        let ty::Adt(adt_def, args) = expr_ty.kind() else {
1453            return false;
1454        };
1455        let ty::Adt(expected_adt_def, expected_args) = expected_ty.kind() else {
1456            return false;
1457        };
1458        if adt_def != expected_adt_def {
1459            return false;
1460        }
1461
1462        if Some(adt_def.did()) == self.tcx.get_diagnostic_item(sym::Result)
1463            && self.can_eq(self.param_env, args.type_at(1), expected_args.type_at(1))
1464            || Some(adt_def.did()) == self.tcx.get_diagnostic_item(sym::Option)
1465        {
1466            let expr_inner_ty = args.type_at(0);
1467            let expected_inner_ty = expected_args.type_at(0);
1468            if let &ty::Ref(_, ty, _mutability) = expr_inner_ty.kind()
1469                && self.can_eq(self.param_env, ty, expected_inner_ty)
1470            {
1471                let def_path = self.tcx.def_path_str(adt_def.did());
1472                let span = expr.span.shrink_to_hi();
1473                let subdiag = if self.type_is_copy_modulo_regions(self.param_env, ty) {
1474                    errors::OptionResultRefMismatch::Copied { span, def_path }
1475                } else if self.type_is_clone_modulo_regions(self.param_env, ty) {
1476                    errors::OptionResultRefMismatch::Cloned { span, def_path }
1477                } else {
1478                    return false;
1479                };
1480                diag.subdiagnostic(subdiag);
1481                return true;
1482            }
1483        }
1484
1485        false
1486    }
1487
1488    pub(crate) fn suggest_into(
1489        &self,
1490        diag: &mut Diag<'_>,
1491        expr: &hir::Expr<'_>,
1492        expr_ty: Ty<'tcx>,
1493        expected_ty: Ty<'tcx>,
1494    ) -> bool {
1495        let expr = expr.peel_blocks();
1496
1497        // We have better suggestions for scalar interconversions...
1498        if expr_ty.is_scalar() && expected_ty.is_scalar() {
1499            return false;
1500        }
1501
1502        // Don't suggest turning a block into another type (e.g. `{}.into()`)
1503        if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    hir::ExprKind::Block(..) => true,
    _ => false,
}matches!(expr.kind, hir::ExprKind::Block(..)) {
1504            return false;
1505        }
1506
1507        // We'll later suggest `.as_ref` when noting the type error,
1508        // so skip if we will suggest that instead.
1509        if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1510            return false;
1511        }
1512
1513        if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1514            && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1515                self.tcx,
1516                self.misc(expr.span),
1517                self.param_env,
1518                ty::TraitRef::new(self.tcx, into_def_id, [expr_ty, expected_ty]),
1519            ))
1520            && !expr
1521                .span
1522                .macro_backtrace()
1523                .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, ..)))
1524        {
1525            let span = expr
1526                .span
1527                .find_ancestor_not_from_extern_macro(self.tcx.sess.source_map())
1528                .unwrap_or(expr.span);
1529
1530            let mut sugg = if self.precedence(expr) >= ExprPrecedence::Unambiguous {
1531                ::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())]
1532            } else {
1533                ::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![
1534                    (span.shrink_to_lo(), "(".to_owned()),
1535                    (span.shrink_to_hi(), ").into()".to_owned()),
1536                ]
1537            };
1538            if let Some(name) = self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1539                sugg.insert(0, (expr.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", name))
    })format!("{}: ", name)));
1540            }
1541            diag.multipart_suggestion(
1542                    ::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}`"),
1543                    sugg,
1544                    Applicability::MaybeIncorrect
1545                );
1546            return true;
1547        }
1548
1549        false
1550    }
1551
1552    /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
1553    pub(crate) fn suggest_option_to_bool(
1554        &self,
1555        diag: &mut Diag<'_>,
1556        expr: &hir::Expr<'_>,
1557        expr_ty: Ty<'tcx>,
1558        expected_ty: Ty<'tcx>,
1559    ) -> bool {
1560        if !expected_ty.is_bool() {
1561            return false;
1562        }
1563
1564        let ty::Adt(def, _) = expr_ty.peel_refs().kind() else {
1565            return false;
1566        };
1567        if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1568            return false;
1569        }
1570
1571        let cond_parent = self.tcx.hir_parent_iter(expr.hir_id).find(|(_, node)| {
1572            !#[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)
1573        });
1574        // Don't suggest:
1575        //     `let Some(_) = a.is_some() && b`
1576        //                     ++++++++++
1577        // since the user probably just misunderstood how `let else`
1578        // and `&&` work together.
1579        if let Some((_, hir::Node::LetStmt(local))) = cond_parent
1580            && let hir::PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), .. })
1581            | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1582            && let hir::QPath::Resolved(None, path) = qpath
1583            && let Some(did) = path
1584                .res
1585                .opt_def_id()
1586                .and_then(|did| self.tcx.opt_parent(did))
1587                .and_then(|did| self.tcx.opt_parent(did))
1588            && self.tcx.is_diagnostic_item(sym::Option, did)
1589        {
1590            return false;
1591        }
1592
1593        let suggestion = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1594            Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}.is_some()", ident))
    })format!(": {ident}.is_some()"),
1595            None => ".is_some()".to_string(),
1596        };
1597
1598        diag.span_suggestion_verbose(
1599            expr.span.shrink_to_hi(),
1600            "use `Option::is_some` to test if the `Option` has a value",
1601            suggestion,
1602            Applicability::MachineApplicable,
1603        );
1604        true
1605    }
1606
1607    // Suggest to change `Option<&Vec<T>>::unwrap_or(&[])` to `Option::map_or(&[], |v| v)`.
1608    #[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(1608u32),
                                    ::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))]
1609    pub(crate) fn suggest_deref_unwrap_or(
1610        &self,
1611        err: &mut Diag<'_>,
1612        callee_ty: Option<Ty<'tcx>>,
1613        call_ident: Option<Ident>,
1614        expected_ty: Ty<'tcx>,
1615        provided_ty: Ty<'tcx>,
1616        provided_expr: &Expr<'tcx>,
1617        is_method: bool,
1618    ) {
1619        if !is_method {
1620            return;
1621        }
1622        let Some(callee_ty) = callee_ty else {
1623            return;
1624        };
1625        let ty::Adt(callee_adt, _) = callee_ty.peel_refs().kind() else {
1626            return;
1627        };
1628        let adt_name = if self.tcx.is_diagnostic_item(sym::Option, callee_adt.did()) {
1629            "Option"
1630        } else if self.tcx.is_diagnostic_item(sym::Result, callee_adt.did()) {
1631            "Result"
1632        } else {
1633            return;
1634        };
1635
1636        let Some(call_ident) = call_ident else {
1637            return;
1638        };
1639        if call_ident.name != sym::unwrap_or {
1640            return;
1641        }
1642
1643        let ty::Ref(_, peeled, _mutability) = provided_ty.kind() else {
1644            return;
1645        };
1646
1647        // NOTE: Can we reuse `suggest_deref_or_ref`?
1648
1649        // Create an dummy type `&[_]` so that both &[] and `&Vec<T>` can coerce to it.
1650        let dummy_ty = if let ty::Array(elem_ty, size) = peeled.kind()
1651            && let ty::Infer(_) = elem_ty.kind()
1652            && self
1653                .try_structurally_resolve_const(provided_expr.span, *size)
1654                .try_to_target_usize(self.tcx)
1655                == Some(0)
1656        {
1657            let slice = Ty::new_slice(self.tcx, *elem_ty);
1658            Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, slice)
1659        } else {
1660            provided_ty
1661        };
1662
1663        if !self.may_coerce(expected_ty, dummy_ty) {
1664            return;
1665        }
1666        let msg = format!("use `{adt_name}::map_or` to deref inner value of `{adt_name}`");
1667        err.multipart_suggestion(
1668            msg,
1669            vec![
1670                (call_ident.span, "map_or".to_owned()),
1671                (provided_expr.span.shrink_to_hi(), ", |v| v".to_owned()),
1672            ],
1673            Applicability::MachineApplicable,
1674        );
1675    }
1676
1677    /// Suggest wrapping the block in square brackets instead of curly braces
1678    /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1679    pub(crate) fn suggest_block_to_brackets(
1680        &self,
1681        diag: &mut Diag<'_>,
1682        blk: &hir::Block<'_>,
1683        blk_ty: Ty<'tcx>,
1684        expected_ty: Ty<'tcx>,
1685    ) {
1686        if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1687            if self.may_coerce(blk_ty, *elem_ty)
1688                && blk.stmts.is_empty()
1689                && blk.rules == hir::BlockCheckMode::DefaultBlock
1690                && let source_map = self.tcx.sess.source_map()
1691                && let Ok(snippet) = source_map.span_to_snippet(blk.span)
1692                && snippet.starts_with('{')
1693                && snippet.ends_with('}')
1694            {
1695                diag.multipart_suggestion(
1696                    "to create an array, use square brackets instead of curly braces",
1697                    ::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![
1698                        (
1699                            blk.span
1700                                .shrink_to_lo()
1701                                .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1702                            "[".to_string(),
1703                        ),
1704                        (
1705                            blk.span
1706                                .shrink_to_hi()
1707                                .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1708                            "]".to_string(),
1709                        ),
1710                    ],
1711                    Applicability::MachineApplicable,
1712                );
1713            }
1714        }
1715    }
1716
1717    #[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(1717u32),
                                    ::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))]
1718    pub(crate) fn suggest_floating_point_literal(
1719        &self,
1720        err: &mut Diag<'_>,
1721        expr: &hir::Expr<'_>,
1722        expected_ty: Ty<'tcx>,
1723    ) -> bool {
1724        if !expected_ty.is_floating_point() {
1725            return false;
1726        }
1727        match expr.kind {
1728            ExprKind::Struct(&qpath, [start, end], _)
1729                if is_range_literal(expr)
1730                    && self.tcx.qpath_is_lang_item(qpath, LangItem::Range) =>
1731            {
1732                err.span_suggestion_verbose(
1733                    start.expr.span.shrink_to_hi().with_hi(end.expr.span.lo()),
1734                    "remove the unnecessary `.` operator for a floating point literal",
1735                    '.',
1736                    Applicability::MaybeIncorrect,
1737                );
1738                true
1739            }
1740            ExprKind::Struct(&qpath, [arg], _)
1741                if is_range_literal(expr)
1742                    && let Some(qpath @ (LangItem::RangeFrom | LangItem::RangeTo)) =
1743                        self.tcx.qpath_lang_item(qpath) =>
1744            {
1745                let range_span = expr.span.parent_callsite().unwrap();
1746                match qpath {
1747                    LangItem::RangeFrom => {
1748                        err.span_suggestion_verbose(
1749                            range_span.with_lo(arg.expr.span.hi()),
1750                            "remove the unnecessary `.` operator for a floating point literal",
1751                            '.',
1752                            Applicability::MaybeIncorrect,
1753                        );
1754                    }
1755                    _ => {
1756                        err.span_suggestion_verbose(
1757                            range_span.until(arg.expr.span),
1758                            "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1759                            "0.",
1760                            Applicability::MaybeIncorrect,
1761                        );
1762                    }
1763                }
1764                true
1765            }
1766            ExprKind::Lit(Spanned {
1767                node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed),
1768                span,
1769            }) => {
1770                let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) else {
1771                    return false;
1772                };
1773                if !(snippet.starts_with("0x") || snippet.starts_with("0X")) {
1774                    return false;
1775                }
1776                if snippet.len() <= 5 || !snippet.is_char_boundary(snippet.len() - 3) {
1777                    return false;
1778                }
1779                let (_, suffix) = snippet.split_at(snippet.len() - 3);
1780                let value = match suffix {
1781                    "f32" => (lit.get() - 0xf32) / (16 * 16 * 16),
1782                    "f64" => (lit.get() - 0xf64) / (16 * 16 * 16),
1783                    _ => return false,
1784                };
1785                err.span_suggestions(
1786                    expr.span,
1787                    "rewrite this as a decimal floating point literal, or use `as` to turn a hex literal into a float",
1788                    [format!("0x{value:X} as {suffix}"), format!("{value}_{suffix}")],
1789                    Applicability::MaybeIncorrect,
1790                );
1791                true
1792            }
1793            _ => false,
1794        }
1795    }
1796
1797    /// Suggest providing `std::ptr::null()` or `std::ptr::null_mut()` if they
1798    /// pass in a literal 0 to an raw pointer.
1799    #[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(1799u32),
                                    ::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))]
1800    pub(crate) fn suggest_null_ptr_for_literal_zero_given_to_ptr_arg(
1801        &self,
1802        err: &mut Diag<'_>,
1803        expr: &hir::Expr<'_>,
1804        expected_ty: Ty<'tcx>,
1805    ) -> bool {
1806        // Expected type needs to be a raw pointer.
1807        let ty::RawPtr(_, mutbl) = expected_ty.kind() else {
1808            return false;
1809        };
1810
1811        // Provided expression needs to be a literal `0`.
1812        let ExprKind::Lit(Spanned { node: rustc_ast::LitKind::Int(Pu128(0), _), span }) = expr.kind
1813        else {
1814            return false;
1815        };
1816
1817        // We need to find a null pointer symbol to suggest
1818        let null_sym = match mutbl {
1819            hir::Mutability::Not => sym::ptr_null,
1820            hir::Mutability::Mut => sym::ptr_null_mut,
1821        };
1822        let Some(null_did) = self.tcx.get_diagnostic_item(null_sym) else {
1823            return false;
1824        };
1825        let null_path_str = with_no_trimmed_paths!(self.tcx.def_path_str(null_did));
1826
1827        // We have satisfied all requirements to provide a suggestion. Emit it.
1828        err.span_suggestion(
1829            span,
1830            format!("if you meant to create a null pointer, use `{null_path_str}()`"),
1831            null_path_str + "()",
1832            Applicability::MachineApplicable,
1833        );
1834
1835        true
1836    }
1837
1838    pub(crate) fn suggest_associated_const(
1839        &self,
1840        err: &mut Diag<'_>,
1841        expr: &hir::Expr<'tcx>,
1842        expected_ty: Ty<'tcx>,
1843    ) -> bool {
1844        let Some((DefKind::AssocFn, old_def_id)) =
1845            self.typeck_results.borrow().type_dependent_def(expr.hir_id)
1846        else {
1847            return false;
1848        };
1849        let old_item_name = self.tcx.item_name(old_def_id);
1850        let capitalized_name = Symbol::intern(&old_item_name.as_str().to_uppercase());
1851        if old_item_name == capitalized_name {
1852            return false;
1853        }
1854        let (item, segment) = match expr.kind {
1855            hir::ExprKind::Path(QPath::Resolved(
1856                Some(ty),
1857                hir::Path { segments: [segment], .. },
1858            ))
1859            | hir::ExprKind::Path(QPath::TypeRelative(ty, segment))
1860                if let Some(self_ty) = self.typeck_results.borrow().node_type_opt(ty.hir_id)
1861                    && let Ok(pick) = self.probe_for_name(
1862                        Mode::Path,
1863                        Ident::new(capitalized_name, segment.ident.span),
1864                        Some(expected_ty),
1865                        IsSuggestion(true),
1866                        self_ty,
1867                        expr.hir_id,
1868                        ProbeScope::TraitsInScope,
1869                    ) =>
1870            {
1871                (pick.item, segment)
1872            }
1873            hir::ExprKind::Path(QPath::Resolved(
1874                None,
1875                hir::Path { segments: [.., segment], .. },
1876            )) => {
1877                // we resolved through some path that doesn't end in the item name,
1878                // better not do a bad suggestion by accident.
1879                if old_item_name != segment.ident.name {
1880                    return false;
1881                }
1882                let Some(item) = self
1883                    .tcx
1884                    .associated_items(self.tcx.parent(old_def_id))
1885                    .filter_by_name_unhygienic(capitalized_name)
1886                    .next()
1887                else {
1888                    return false;
1889                };
1890                (*item, segment)
1891            }
1892            _ => return false,
1893        };
1894        if item.def_id == old_def_id
1895            || !#[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 { .. })
1896        {
1897            // Same item
1898            return false;
1899        }
1900        let item_ty = self.tcx.type_of(item.def_id).instantiate_identity().skip_norm_wip();
1901        // FIXME(compiler-errors): This check is *so* rudimentary
1902        if item_ty.has_param() {
1903            return false;
1904        }
1905        if self.may_coerce(item_ty, expected_ty) {
1906            err.span_suggestion_verbose(
1907                segment.ident.span,
1908                ::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",),
1909                capitalized_name,
1910                Applicability::MachineApplicable,
1911            );
1912            true
1913        } else {
1914            false
1915        }
1916    }
1917
1918    fn is_loop(&self, id: HirId) -> bool {
1919        let node = self.tcx.hir_node(id);
1920        #[allow(non_exhaustive_omitted_patterns)] match node {
    Node::Expr(Expr { kind: ExprKind::Loop(..), .. }) => true,
    _ => false,
}matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1921    }
1922
1923    fn is_local_statement(&self, id: HirId) -> bool {
1924        let node = self.tcx.hir_node(id);
1925        #[allow(non_exhaustive_omitted_patterns)] match node {
    Node::Stmt(Stmt { kind: StmtKind::Let(..), .. }) => true,
    _ => false,
}matches!(node, Node::Stmt(Stmt { kind: StmtKind::Let(..), .. }))
1926    }
1927
1928    /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1929    /// which is a side-effect of autoref.
1930    pub(crate) fn note_type_is_not_clone(
1931        &self,
1932        diag: &mut Diag<'_>,
1933        expected_ty: Ty<'tcx>,
1934        found_ty: Ty<'tcx>,
1935        expr: &hir::Expr<'_>,
1936    ) {
1937        // When `expr` is `x` in something like `let x = foo.clone(); x`, need to recurse up to get
1938        // `foo` and `clone`.
1939        let expr = self.note_type_is_not_clone_inner_expr(expr);
1940
1941        // If we've recursed to an `expr` of `foo.clone()`, get `foo` and `clone`.
1942        let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else {
1943            return;
1944        };
1945
1946        let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else {
1947            return;
1948        };
1949        let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1950        let results = self.typeck_results.borrow();
1951        // First, look for a `Clone::clone` call
1952        if segment.ident.name == sym::clone
1953            && results.type_dependent_def_id(expr.hir_id).is_some_and(|did| {
1954                    let assoc_item = self.tcx.associated_item(did);
1955                    assoc_item.container == ty::AssocContainer::Trait
1956                        && assoc_item.container_id(self.tcx) == clone_trait_did
1957                })
1958            // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1959            // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1960            && !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(..)))
1961            // Check that we're in fact trying to clone into the expected type
1962            && self.may_coerce(*pointee_ty, expected_ty)
1963            && let trait_ref = ty::TraitRef::new(self.tcx, clone_trait_did, [expected_ty])
1964            // And the expected type doesn't implement `Clone`
1965            && !self.predicate_must_hold_considering_regions(&traits::Obligation::new(
1966                self.tcx,
1967                traits::ObligationCause::dummy(),
1968                self.param_env,
1969                trait_ref,
1970            ))
1971        {
1972            diag.span_note(
1973                callee_expr.span,
1974                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` does not implement `Clone`, so `{1}` was cloned instead",
                expected_ty, found_ty))
    })format!(
1975                    "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1976                ),
1977            );
1978            let owner = self.tcx.hir_enclosing_body_owner(expr.hir_id);
1979            if let ty::Param(param) = expected_ty.kind()
1980                && let Some(generics) = self.tcx.hir_get_generics(owner)
1981            {
1982                suggest_constraining_type_params(
1983                    self.tcx,
1984                    generics,
1985                    diag,
1986                    ::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(),
1987                    None,
1988                );
1989            } else {
1990                let mut suggest_derive = true;
1991                if let Some(errors) =
1992                    self.type_implements_trait_shallow(clone_trait_did, expected_ty, self.param_env)
1993                {
1994                    let manually_impl = "consider manually implementing `Clone` to avoid the \
1995                        implicit type parameter bounds";
1996                    match &errors[..] {
1997                        [] => {}
1998                        [error] => {
1999                            let msg = "`Clone` is not implemented because a trait bound is not \
2000                                satisfied";
2001                            if let traits::ObligationCauseCode::ImplDerived(data) =
2002                                error.obligation.cause.code()
2003                            {
2004                                let mut span: MultiSpan = data.span.into();
2005                                if self.tcx.is_automatically_derived(data.impl_or_alias_def_id) {
2006                                    span.push_span_label(
2007                                        data.span,
2008                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("derive introduces an implicit `{0}` bound",
                error.obligation.predicate))
    })format!(
2009                                            "derive introduces an implicit `{}` bound",
2010                                            error.obligation.predicate
2011                                        ),
2012                                    );
2013                                }
2014                                diag.span_help(span, msg);
2015                                if self.tcx.is_automatically_derived(data.impl_or_alias_def_id)
2016                                    && data.impl_or_alias_def_id.is_local()
2017                                {
2018                                    diag.help(manually_impl);
2019                                    suggest_derive = false;
2020                                }
2021                            } else {
2022                                diag.help(msg);
2023                            }
2024                        }
2025                        _ => {
2026                            let unsatisfied_bounds: Vec<_> = errors
2027                                .iter()
2028                                .filter_map(|error| match error.obligation.cause.code() {
2029                                    traits::ObligationCauseCode::ImplDerived(data) => {
2030                                        let pre = if self
2031                                            .tcx
2032                                            .is_automatically_derived(data.impl_or_alias_def_id)
2033                                        {
2034                                            "derive introduces an implicit "
2035                                        } else {
2036                                            ""
2037                                        };
2038                                        Some((
2039                                            data.span,
2040                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}unsatisfied trait bound `{0}`",
                error.obligation.predicate, pre))
    })format!(
2041                                                "{pre}unsatisfied trait bound `{}`",
2042                                                error.obligation.predicate
2043                                            ),
2044                                        ))
2045                                    }
2046                                    _ => None,
2047                                })
2048                                .collect();
2049                            let msg = "`Clone` is not implemented because the some trait bounds \
2050                                could not be satisfied";
2051                            if errors.len() == unsatisfied_bounds.len() {
2052                                let mut unsatisfied_bounds_spans: MultiSpan = unsatisfied_bounds
2053                                    .iter()
2054                                    .map(|(span, _)| *span)
2055                                    .collect::<Vec<Span>>()
2056                                    .into();
2057                                for (span, label) in unsatisfied_bounds {
2058                                    unsatisfied_bounds_spans.push_span_label(span, label);
2059                                }
2060                                diag.span_help(unsatisfied_bounds_spans, msg);
2061                                if errors.iter().all(|error| match error.obligation.cause.code() {
2062                                    traits::ObligationCauseCode::ImplDerived(data) => {
2063                                        self.tcx.is_automatically_derived(data.impl_or_alias_def_id)
2064                                            && data.impl_or_alias_def_id.is_local()
2065                                    }
2066                                    _ => false,
2067                                }) {
2068                                    diag.help(manually_impl);
2069                                    suggest_derive = false;
2070                                }
2071                            } else {
2072                                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!(
2073                                    "{msg}: {}",
2074                                    listify(&errors, |e| format!("`{}`", e.obligation.predicate))
2075                                        .unwrap(),
2076                                ));
2077                            }
2078                        }
2079                    }
2080                    for error in errors {
2081                        if let traits::FulfillmentErrorCode::Select(
2082                            traits::SelectionError::Unimplemented,
2083                        ) = error.code
2084                            && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2085                                error.obligation.predicate.kind().skip_binder()
2086                        {
2087                            self.infcx.err_ctxt().suggest_derive(
2088                                &error.obligation,
2089                                diag,
2090                                error.obligation.predicate.kind().rebind(pred),
2091                            );
2092                        }
2093                    }
2094                }
2095                if suggest_derive {
2096                    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)]);
2097                }
2098            }
2099        }
2100    }
2101
2102    /// Given a type mismatch error caused by `&T` being cloned instead of `T`, and
2103    /// the `expr` as the source of this type mismatch, try to find the method call
2104    /// as the source of this error and return that instead. Otherwise, return the
2105    /// original expression.
2106    fn note_type_is_not_clone_inner_expr<'b>(
2107        &'b self,
2108        expr: &'b hir::Expr<'b>,
2109    ) -> &'b hir::Expr<'b> {
2110        match expr.peel_blocks().kind {
2111            hir::ExprKind::Path(hir::QPath::Resolved(
2112                None,
2113                hir::Path { segments: [_], res: crate::Res::Local(binding), .. },
2114            )) => {
2115                let hir::Node::Pat(hir::Pat { hir_id, .. }) = self.tcx.hir_node(*binding) else {
2116                    return expr;
2117                };
2118
2119                match self.tcx.parent_hir_node(*hir_id) {
2120                    // foo.clone()
2121                    hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) => {
2122                        self.note_type_is_not_clone_inner_expr(init)
2123                    }
2124                    // When `expr` is more complex like a tuple
2125                    hir::Node::Pat(hir::Pat {
2126                        hir_id: pat_hir_id,
2127                        kind: hir::PatKind::Tuple(pats, ..),
2128                        ..
2129                    }) => {
2130                        let hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) =
2131                            self.tcx.parent_hir_node(*pat_hir_id)
2132                        else {
2133                            return expr;
2134                        };
2135
2136                        match init.peel_blocks().kind {
2137                            ExprKind::Tup(init_tup) => {
2138                                if let Some(init) = pats
2139                                    .iter()
2140                                    .enumerate()
2141                                    .filter(|x| x.1.hir_id == *hir_id)
2142                                    .find_map(|(i, _)| init_tup.get(i))
2143                                {
2144                                    self.note_type_is_not_clone_inner_expr(init)
2145                                } else {
2146                                    expr
2147                                }
2148                            }
2149                            _ => expr,
2150                        }
2151                    }
2152                    _ => expr,
2153                }
2154            }
2155            // If we're calling into a closure that may not be typed recurse into that call. no need
2156            // to worry if it's a call to a typed function or closure as this would ne handled
2157            // previously.
2158            hir::ExprKind::Call(Expr { kind: call_expr_kind, .. }, _) => {
2159                if let hir::ExprKind::Path(hir::QPath::Resolved(None, call_expr_path)) =
2160                    call_expr_kind
2161                    && let hir::Path { segments: [_], res: crate::Res::Local(binding), .. } =
2162                        call_expr_path
2163                    && let hir::Node::Pat(hir::Pat { hir_id, .. }) = self.tcx.hir_node(*binding)
2164                    && let hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) =
2165                        self.tcx.parent_hir_node(*hir_id)
2166                    && let Expr {
2167                        kind: hir::ExprKind::Closure(hir::Closure { body: body_id, .. }),
2168                        ..
2169                    } = init
2170                {
2171                    let hir::Body { value: body_expr, .. } = self.tcx.hir_body(*body_id);
2172                    self.note_type_is_not_clone_inner_expr(body_expr)
2173                } else {
2174                    expr
2175                }
2176            }
2177            _ => expr,
2178        }
2179    }
2180
2181    pub(crate) fn is_field_suggestable(
2182        &self,
2183        field: &ty::FieldDef,
2184        hir_id: HirId,
2185        span: Span,
2186    ) -> bool {
2187        // The field must be visible in the containing module.
2188        field.vis.is_accessible_from(self.tcx.parent_module(hir_id), self.tcx)
2189            // The field must not be unstable.
2190            && !#[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!(
2191                self.tcx.eval_stability(field.did, None, rustc_span::DUMMY_SP, None),
2192                rustc_middle::middle::stability::EvalResult::Deny { .. }
2193            )
2194            // If the field is from an external crate it must not be `doc(hidden)`.
2195            && (field.did.is_local() || !self.tcx.is_doc_hidden(field.did))
2196            // If the field is hygienic it must come from the same syntax context.
2197            && self.tcx.def_ident_span(field.did).unwrap().normalize_to_macros_2_0().eq_ctxt(span)
2198    }
2199
2200    pub(crate) fn suggest_missing_unwrap_expect(
2201        &self,
2202        err: &mut Diag<'_>,
2203        expr: &hir::Expr<'tcx>,
2204        expected: Ty<'tcx>,
2205        found: Ty<'tcx>,
2206    ) -> bool {
2207        let ty::Adt(adt, args) = found.kind() else {
2208            return false;
2209        };
2210        let ret_ty_matches = |diagnostic_item| {
2211            let Some(sig) = self.body_fn_sig() else {
2212                return false;
2213            };
2214            let ty::Adt(kind, _) = sig.output().kind() else {
2215                return false;
2216            };
2217            self.tcx.is_diagnostic_item(diagnostic_item, kind.did())
2218        };
2219
2220        // don't suggest anything like `Ok(ok_val).unwrap()` , `Some(some_val).unwrap()`,
2221        // `None.unwrap()` etc.
2222        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!(
2223            expr.kind,
2224            hir::ExprKind::Call(
2225                hir::Expr {
2226                    kind: hir::ExprKind::Path(hir::QPath::Resolved(
2227                        None,
2228                        hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. },
2229                    )),
2230                    ..
2231                },
2232                ..,
2233            ) | hir::ExprKind::Path(hir::QPath::Resolved(
2234                None,
2235                hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. },
2236            )),
2237        );
2238
2239        let (article, kind, variant, sugg_operator) = if self.tcx.is_diagnostic_item(sym::Result, adt.did())
2240            // Do not suggest `.expect()` in const context where it's not available. rust-lang/rust#149316
2241            && !self.tcx.hir_is_inside_const_context(expr.hir_id)
2242        {
2243            ("a", "Result", "Err", ret_ty_matches(sym::Result))
2244        } else if self.tcx.is_diagnostic_item(sym::Option, adt.did()) {
2245            ("an", "Option", "None", ret_ty_matches(sym::Option))
2246        } else {
2247            return false;
2248        };
2249        if is_ctor || !self.may_coerce(args.type_at(0), expected) {
2250            return false;
2251        }
2252
2253        let (msg, sugg) = if sugg_operator {
2254            (
2255                ::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!(
2256                    "use the `?` operator to extract the `{found}` value, propagating \
2257                            {article} `{kind}::{variant}` value to the caller"
2258                ),
2259                "?",
2260            )
2261        } else {
2262            (
2263                ::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!(
2264                    "consider using `{kind}::expect` to unwrap the `{found}` value, \
2265                                panicking if the value is {article} `{kind}::{variant}`"
2266                ),
2267                ".expect(\"REASON\")",
2268            )
2269        };
2270
2271        let sugg = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
2272            Some(_) if expr.span.from_expansion() => return false,
2273            Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}{1}", ident, sugg))
    })format!(": {ident}{sugg}"),
2274            None => sugg.to_string(),
2275        };
2276
2277        let span = expr
2278            .span
2279            .find_ancestor_not_from_extern_macro(self.tcx.sess.source_map())
2280            .unwrap_or(expr.span);
2281        err.span_suggestion_verbose(span.shrink_to_hi(), msg, sugg, Applicability::HasPlaceholders);
2282        true
2283    }
2284
2285    pub(crate) fn suggest_coercing_result_via_try_operator(
2286        &self,
2287        err: &mut Diag<'_>,
2288        expr: &hir::Expr<'tcx>,
2289        expected: Ty<'tcx>,
2290        found: Ty<'tcx>,
2291    ) -> bool {
2292        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!(
2293            self.tcx.parent_hir_node(expr.hir_id),
2294            hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
2295        ) || self.tcx.hir_get_fn_id_for_return_block(expr.hir_id).is_some();
2296        if returned
2297            && let ty::Adt(e, args_e) = expected.kind()
2298            && let ty::Adt(f, args_f) = found.kind()
2299            && e.did() == f.did()
2300            && Some(e.did()) == self.tcx.get_diagnostic_item(sym::Result)
2301            && let e_ok = args_e.type_at(0)
2302            && let f_ok = args_f.type_at(0)
2303            && self.infcx.can_eq(self.param_env, f_ok, e_ok)
2304            && let e_err = args_e.type_at(1)
2305            && let f_err = args_f.type_at(1)
2306            && self
2307                .infcx
2308                .type_implements_trait(
2309                    self.tcx.get_diagnostic_item(sym::Into).unwrap(),
2310                    [f_err, e_err],
2311                    self.param_env,
2312                )
2313                .must_apply_modulo_regions()
2314        {
2315            err.multipart_suggestion(
2316                "use `?` to coerce and return an appropriate `Err`, and wrap the resulting value \
2317                 in `Ok` so the expression remains of type `Result`",
2318                ::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![
2319                    (expr.span.shrink_to_lo(), "Ok(".to_string()),
2320                    (expr.span.shrink_to_hi(), "?)".to_string()),
2321                ],
2322                Applicability::MaybeIncorrect,
2323            );
2324            return true;
2325        }
2326        false
2327    }
2328
2329    // If the expr is a while or for loop and is the tail expr of its
2330    // enclosing body suggest returning a value right after it
2331    pub(crate) fn suggest_returning_value_after_loop(
2332        &self,
2333        err: &mut Diag<'_>,
2334        expr: &hir::Expr<'tcx>,
2335        expected: Ty<'tcx>,
2336    ) -> bool {
2337        let tcx = self.tcx;
2338        let enclosing_scope =
2339            tcx.hir_get_enclosing_scope(expr.hir_id).map(|hir_id| tcx.hir_node(hir_id));
2340
2341        // Get tail expr of the enclosing block or body
2342        let tail_expr = if let Some(Node::Block(hir::Block { expr, .. })) = enclosing_scope
2343            && expr.is_some()
2344        {
2345            *expr
2346        } else {
2347            let body_def_id = tcx.hir_enclosing_body_owner(expr.hir_id);
2348            let body = tcx.hir_body_owned_by(body_def_id);
2349
2350            // Get tail expr of the body
2351            match body.value.kind {
2352                // Regular function body etc.
2353                hir::ExprKind::Block(block, _) => block.expr,
2354                // Anon const body (there's no block in this case)
2355                hir::ExprKind::DropTemps(expr) => Some(expr),
2356                _ => None,
2357            }
2358        };
2359
2360        let Some(tail_expr) = tail_expr else {
2361            return false; // Body doesn't have a tail expr we can compare with
2362        };
2363
2364        // Get the loop expr within the tail expr
2365        let loop_expr_in_tail = match expr.kind {
2366            hir::ExprKind::Loop(_, _, hir::LoopSource::While, _) => tail_expr,
2367            hir::ExprKind::Loop(_, _, hir::LoopSource::ForLoop, _) => {
2368                match tail_expr.peel_drop_temps() {
2369                    Expr { kind: ExprKind::Match(_, [Arm { body, .. }], _), .. } => body,
2370                    _ => return false, // Not really a for loop
2371                }
2372            }
2373            _ => return false, // Not a while or a for loop
2374        };
2375
2376        // If the expr is the loop expr in the tail
2377        // then make the suggestion
2378        if expr.hir_id == loop_expr_in_tail.hir_id {
2379            let span = expr.span;
2380
2381            let (msg, suggestion) = if expected.is_never() {
2382                (
2383                    "consider adding a diverging expression here",
2384                    "`loop {}` or `panic!(\"...\")`".to_string(),
2385                )
2386            } else {
2387                ("consider returning a value here", ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` value", expected))
    })format!("`{expected}` value"))
2388            };
2389
2390            let src_map = tcx.sess.source_map();
2391            let suggestion = if src_map.is_multiline(expr.span) {
2392                let indentation = src_map.indentation_before(span).unwrap_or_default();
2393                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}/* {1} */", indentation,
                suggestion))
    })format!("\n{indentation}/* {suggestion} */")
2394            } else {
2395                // If the entire expr is on a single line
2396                // put the suggestion also on the same line
2397                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" /* {0} */", suggestion))
    })format!(" /* {suggestion} */")
2398            };
2399
2400            err.span_suggestion_verbose(
2401                span.shrink_to_hi(),
2402                msg,
2403                suggestion,
2404                Applicability::MaybeIncorrect,
2405            );
2406
2407            true
2408        } else {
2409            false
2410        }
2411    }
2412
2413    /// Suggest replacing comma with semicolon in incorrect repeat expressions
2414    /// like `["_", 10]` or `vec![String::new(), 10]`.
2415    pub(crate) fn suggest_semicolon_in_repeat_expr(
2416        &self,
2417        err: &mut Diag<'_>,
2418        expr: &hir::Expr<'_>,
2419        expr_ty: Ty<'tcx>,
2420    ) -> bool {
2421        // Check if `expr` is contained in array of two elements
2422        if let hir::Node::Expr(array_expr) = self.tcx.parent_hir_node(expr.hir_id)
2423            && let hir::ExprKind::Array(elements) = array_expr.kind
2424            && let [first, second] = elements
2425            && second.hir_id == expr.hir_id
2426        {
2427            // Span between the two elements of the array
2428            let comma_span = first.span.between(second.span);
2429
2430            // Check if `expr` is a constant value of type `usize`.
2431            // This can only detect const variable declarations and
2432            // calls to const functions.
2433
2434            // Checking this here instead of rustc_hir::hir because
2435            // this check needs access to `self.tcx` but rustc_hir
2436            // has no access to `TyCtxt`.
2437            let expr_is_const_usize = expr_ty.is_usize()
2438                && match expr.kind {
2439                    ExprKind::Path(QPath::Resolved(
2440                        None,
2441                        Path { res: Res::Def(DefKind::Const { .. }, _), .. },
2442                    )) => true,
2443                    ExprKind::Call(
2444                        Expr {
2445                            kind:
2446                                ExprKind::Path(QPath::Resolved(
2447                                    None,
2448                                    Path { res: Res::Def(DefKind::Fn, fn_def_id), .. },
2449                                )),
2450                            ..
2451                        },
2452                        _,
2453                    ) => self.tcx.is_const_fn(*fn_def_id),
2454                    _ => false,
2455                };
2456
2457            // Type of the first element is guaranteed to be checked
2458            // when execution reaches here because `mismatched types`
2459            // error occurs only when type of second element of array
2460            // is not the same as type of first element.
2461            let first_ty = self.typeck_results.borrow().expr_ty(first);
2462
2463            // `array_expr` is from a macro `vec!["a", 10]` if
2464            // 1. array expression's span is imported from a macro
2465            // 2. first element of array implements `Clone` trait
2466            // 3. second element is an integer literal or is an expression of `usize` like type
2467            if self.tcx.sess.source_map().is_imported(array_expr.span)
2468                && self.type_is_clone_modulo_regions(self.param_env, first_ty)
2469                && (expr.is_size_lit() || expr_ty.is_usize_like())
2470            {
2471                err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2472                    comma_span,
2473                    descr: "a vector",
2474                });
2475                return true;
2476            }
2477
2478            // `array_expr` is from an array `["a", 10]` if
2479            // 1. first element of array implements `Copy` trait
2480            // 2. second element is an integer literal or is a const value of type `usize`
2481            if self.type_is_copy_modulo_regions(self.param_env, first_ty)
2482                && (expr.is_size_lit() || expr_is_const_usize)
2483            {
2484                err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2485                    comma_span,
2486                    descr: "an array",
2487                });
2488                return true;
2489            }
2490        }
2491        false
2492    }
2493
2494    /// If the expected type is an enum (Issue #55250) with any variants whose
2495    /// sole field is of the found type, suggest such variants. (Issue #42764)
2496    pub(crate) fn suggest_compatible_variants(
2497        &self,
2498        err: &mut Diag<'_>,
2499        expr: &hir::Expr<'_>,
2500        expected: Ty<'tcx>,
2501        expr_ty: Ty<'tcx>,
2502    ) -> bool {
2503        if expr.span.in_external_macro(self.tcx.sess.source_map()) {
2504            return false;
2505        }
2506        if let ty::Adt(expected_adt, args) = expected.kind() {
2507            if let hir::ExprKind::Field(base, ident) = expr.kind {
2508                let base_ty = self.typeck_results.borrow().expr_ty(base);
2509                if self.can_eq(self.param_env, base_ty, expected)
2510                    && let Some(base_span) = base.span.find_ancestor_inside(expr.span)
2511                {
2512                    err.span_suggestion_verbose(
2513                        expr.span.with_lo(base_span.hi()),
2514                        ::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}`"),
2515                        "",
2516                        Applicability::MaybeIncorrect,
2517                    );
2518                    return true;
2519                }
2520            }
2521
2522            // If the expression is of type () and it's the return expression of a block,
2523            // we suggest adding a separate return expression instead.
2524            // (To avoid things like suggesting `Ok(while .. { .. })`.)
2525            if expr_ty.is_unit() {
2526                let mut id = expr.hir_id;
2527                let mut parent;
2528
2529                // Unroll desugaring, to make sure this works for `for` loops etc.
2530                loop {
2531                    parent = self.tcx.parent_hir_id(id);
2532                    let parent_span = self.tcx.hir_span(parent);
2533                    if parent_span.find_ancestor_inside(expr.span).is_some() {
2534                        // The parent node is part of the same span, so is the result of the
2535                        // same expansion/desugaring and not the 'real' parent node.
2536                        id = parent;
2537                        continue;
2538                    }
2539                    break;
2540                }
2541
2542                if let hir::Node::Block(&hir::Block { span: block_span, expr: Some(e), .. }) =
2543                    self.tcx.hir_node(parent)
2544                {
2545                    if e.hir_id == id {
2546                        if let Some(span) = expr.span.find_ancestor_inside(block_span) {
2547                            let return_suggestions = if self
2548                                .tcx
2549                                .is_diagnostic_item(sym::Result, expected_adt.did())
2550                            {
2551                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        ["Ok(())"]))vec!["Ok(())"]
2552                            } else if self.tcx.is_diagnostic_item(sym::Option, expected_adt.did()) {
2553                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        ["None", "Some(())"]))vec!["None", "Some(())"]
2554                            } else {
2555                                return false;
2556                            };
2557                            if let Some(indent) =
2558                                self.tcx.sess.source_map().indentation_before(span.shrink_to_lo())
2559                            {
2560                                // Add a semicolon, except after `}`.
2561                                let semicolon =
2562                                    match self.tcx.sess.source_map().span_to_snippet(span) {
2563                                        Ok(s) if s.ends_with('}') => "",
2564                                        _ => ";",
2565                                    };
2566                                err.span_suggestions(
2567                                    span.shrink_to_hi(),
2568                                    "try adding an expression at the end of the block",
2569                                    return_suggestions
2570                                        .into_iter()
2571                                        .map(|r| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\n{1}{2}", semicolon, indent,
                r))
    })format!("{semicolon}\n{indent}{r}")),
2572                                    Applicability::MaybeIncorrect,
2573                                );
2574                            }
2575                            return true;
2576                        }
2577                    }
2578                }
2579            }
2580
2581            let compatible_variants: Vec<(String, _, _, Option<String>)> = expected_adt
2582                .variants()
2583                .iter()
2584                .filter(|variant| {
2585                    variant.fields.len() == 1
2586                })
2587                .filter_map(|variant| {
2588                    let sole_field = &variant.single_field();
2589
2590                    // When expected_ty and expr_ty are the same ADT, we prefer to compare their internal generic params,
2591                    // When the current variant has a sole field whose type is still an unresolved inference variable,
2592                    // suggestions would be often wrong. So suppress the suggestion. See #145294.
2593                    if let (ty::Adt(exp_adt, _), ty::Adt(act_adt, _)) = (expected.kind(), expr_ty.kind())
2594                        && exp_adt.did() == act_adt.did()
2595                        && sole_field.ty(self.tcx, args).is_ty_var() {
2596                            return None;
2597                    }
2598
2599                    let field_is_local = sole_field.did.is_local();
2600                    let field_is_accessible =
2601                        sole_field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
2602                        // Skip suggestions for unstable public fields (for example `Pin::__pointer`)
2603                        && #[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);
2604
2605                    if !field_is_local && !field_is_accessible {
2606                        return None;
2607                    }
2608
2609                    let note_about_variant_field_privacy = (field_is_local && !field_is_accessible)
2610                        .then(|| " (its field is private, but it's local to this crate and its privacy can be changed)".to_string());
2611
2612                    let sole_field_ty = sole_field.ty(self.tcx, args);
2613                    if self.may_coerce(expr_ty, sole_field_ty) {
2614                        let variant_path =
2615                            { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(variant.def_id) }with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
2616                        // FIXME #56861: DRYer prelude filtering
2617                        if let Some(path) = variant_path.strip_prefix("std::prelude::")
2618                            && let Some((_, path)) = path.split_once("::")
2619                        {
2620                            return Some((path.to_string(), variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy));
2621                        }
2622                        Some((variant_path, variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy))
2623                    } else {
2624                        None
2625                    }
2626                })
2627                .collect();
2628
2629            let suggestions_for = |variant: &_, ctor_kind, field_name| {
2630                let prefix = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
2631                    Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", ident))
    })format!("{ident}: "),
2632                    None => String::new(),
2633                };
2634
2635                let (open, close) = match ctor_kind {
2636                    Some(CtorKind::Fn) => ("(".to_owned(), ")"),
2637                    None => (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{ {0}: ", field_name))
    })format!(" {{ {field_name}: "), " }"),
2638
2639                    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"),
2640                };
2641
2642                // Suggest constructor as deep into the block tree as possible.
2643                // This fixes https://github.com/rust-lang/rust/issues/101065,
2644                // and also just helps make the most minimal suggestions.
2645                let mut expr = expr;
2646                while let hir::ExprKind::Block(block, _) = &expr.kind
2647                    && let Some(expr_) = &block.expr
2648                {
2649                    expr = expr_
2650                }
2651
2652                ::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![
2653                    (expr.span.shrink_to_lo(), format!("{prefix}{variant}{open}")),
2654                    (expr.span.shrink_to_hi(), close.to_owned()),
2655                ]
2656            };
2657
2658            match &compatible_variants[..] {
2659                [] => { /* No variants to format */ }
2660                [(variant, ctor_kind, field_name, note)] => {
2661                    // Just a single matching variant.
2662                    err.multipart_suggestion(
2663                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("try wrapping the expression in `{1}`{0}",
                note.as_deref().unwrap_or(""), variant))
    })format!(
2664                            "try wrapping the expression in `{variant}`{note}",
2665                            note = note.as_deref().unwrap_or("")
2666                        ),
2667                        suggestions_for(&**variant, *ctor_kind, *field_name),
2668                        Applicability::MaybeIncorrect,
2669                    );
2670                    return true;
2671                }
2672                _ => {
2673                    // More than one matching variant.
2674                    err.multipart_suggestions(
2675                        ::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!(
2676                            "try wrapping the expression in a variant of `{}`",
2677                            self.tcx.def_path_str(expected_adt.did())
2678                        ),
2679                        compatible_variants.into_iter().map(
2680                            |(variant, ctor_kind, field_name, _)| {
2681                                suggestions_for(&variant, ctor_kind, field_name)
2682                            },
2683                        ),
2684                        Applicability::MaybeIncorrect,
2685                    );
2686                    return true;
2687                }
2688            }
2689        }
2690
2691        false
2692    }
2693
2694    pub(crate) fn suggest_non_zero_new_unwrap(
2695        &self,
2696        err: &mut Diag<'_>,
2697        expr: &hir::Expr<'_>,
2698        expected: Ty<'tcx>,
2699        expr_ty: Ty<'tcx>,
2700    ) -> bool {
2701        let tcx = self.tcx;
2702        let (adt, args, unwrap) = match expected.kind() {
2703            // In case `Option<NonZero<T>>` is wanted, but `T` is provided, suggest calling `new`.
2704            ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Option, adt.did()) => {
2705                let nonzero_type = args.type_at(0); // Unwrap option type.
2706                let ty::Adt(adt, args) = nonzero_type.kind() else {
2707                    return false;
2708                };
2709                (adt, args, "")
2710            }
2711            // In case `NonZero<T>` is wanted but `T` is provided, also add `.unwrap()` to satisfy types.
2712            ty::Adt(adt, args) => (adt, args, ".unwrap()"),
2713            _ => return false,
2714        };
2715
2716        if !self.tcx.is_diagnostic_item(sym::NonZero, adt.did()) {
2717            return false;
2718        }
2719
2720        let int_type = args.type_at(0);
2721        if !self.may_coerce(expr_ty, int_type) {
2722            return false;
2723        }
2724
2725        err.multipart_suggestion(
2726            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider calling `{0}::new`",
                sym::NonZero))
    })format!("consider calling `{}::new`", sym::NonZero),
2727            ::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![
2728                (expr.span.shrink_to_lo(), format!("{}::new(", sym::NonZero)),
2729                (expr.span.shrink_to_hi(), format!("){unwrap}")),
2730            ],
2731            Applicability::MaybeIncorrect,
2732        );
2733
2734        true
2735    }
2736
2737    /// Identify some cases where `as_ref()` would be appropriate and suggest it.
2738    ///
2739    /// Given the following code:
2740    /// ```compile_fail,E0308
2741    /// struct Foo;
2742    /// fn takes_ref(_: &Foo) {}
2743    /// let ref opt = Some(Foo);
2744    ///
2745    /// opt.map(|param| takes_ref(param));
2746    /// ```
2747    /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
2748    ///
2749    /// It only checks for `Option` and `Result` and won't work with
2750    /// ```ignore (illustrative)
2751    /// opt.map(|param| { takes_ref(param) });
2752    /// ```
2753    fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Vec<(Span, String)>, &'static str)> {
2754        let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind else {
2755            return None;
2756        };
2757
2758        let hir::def::Res::Local(local_id) = path.res else {
2759            return None;
2760        };
2761
2762        let Node::Param(hir::Param { hir_id: param_hir_id, .. }) =
2763            self.tcx.parent_hir_node(local_id)
2764        else {
2765            return None;
2766        };
2767
2768        let Node::Expr(hir::Expr {
2769            hir_id: expr_hir_id,
2770            kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }),
2771            ..
2772        }) = self.tcx.parent_hir_node(*param_hir_id)
2773        else {
2774            return None;
2775        };
2776
2777        let hir = self.tcx.parent_hir_node(*expr_hir_id);
2778        let closure_params_len = closure_fn_decl.inputs.len();
2779        let (
2780            Node::Expr(hir::Expr {
2781                kind: hir::ExprKind::MethodCall(method_path, receiver, ..),
2782                ..
2783            }),
2784            1,
2785        ) = (hir, closure_params_len)
2786        else {
2787            return None;
2788        };
2789
2790        let self_ty = self.typeck_results.borrow().expr_ty(receiver);
2791        let name = method_path.ident.name;
2792        let is_as_ref_able = match self_ty.peel_refs().kind() {
2793            ty::Adt(def, _) => {
2794                (self.tcx.is_diagnostic_item(sym::Option, def.did())
2795                    || self.tcx.is_diagnostic_item(sym::Result, def.did()))
2796                    && (name == sym::map || name == sym::and_then)
2797            }
2798            _ => false,
2799        };
2800        if is_as_ref_able {
2801            Some((
2802                ::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())],
2803                "consider using `as_ref` instead",
2804            ))
2805        } else {
2806            None
2807        }
2808    }
2809
2810    /// This function is used to determine potential "simple" improvements or users' errors and
2811    /// provide them useful help. For example:
2812    ///
2813    /// ```compile_fail,E0308
2814    /// fn some_fn(s: &str) {}
2815    ///
2816    /// let x = "hey!".to_owned();
2817    /// some_fn(x); // error
2818    /// ```
2819    ///
2820    /// No need to find every potential function which could make a coercion to transform a
2821    /// `String` into a `&str` since a `&` would do the trick!
2822    ///
2823    /// In addition of this check, it also checks between references mutability state. If the
2824    /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
2825    /// `&mut`!".
2826    pub(crate) fn suggest_deref_or_ref(
2827        &self,
2828        expr: &hir::Expr<'tcx>,
2829        checked_ty: Ty<'tcx>,
2830        expected: Ty<'tcx>,
2831    ) -> Option<(
2832        Vec<(Span, String)>,
2833        String,
2834        Applicability,
2835        bool, /* verbose */
2836        bool, /* suggest `&` or `&mut` type annotation */
2837    )> {
2838        let sess = self.sess();
2839        let sp = expr.range_span().unwrap_or(expr.span);
2840        let sm = sess.source_map();
2841
2842        // If the span is from an external macro, there's no suggestion we can make.
2843        if sp.in_external_macro(sm) {
2844            return None;
2845        }
2846
2847        let replace_prefix = |s: &str, old: &str, new: &str| {
2848            s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
2849        };
2850
2851        // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
2852        let expr = expr.peel_drop_temps();
2853
2854        match (&expr.kind, expected.kind(), checked_ty.kind()) {
2855            (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (exp.kind(), check.kind()) {
2856                (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
2857                    if let hir::ExprKind::Lit(_) = expr.kind
2858                        && let Ok(src) = sm.span_to_snippet(sp)
2859                        && replace_prefix(&src, "b\"", "\"").is_some()
2860                    {
2861                        let pos = sp.lo() + BytePos(1);
2862                        return Some((
2863                            ::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())],
2864                            "consider removing the leading `b`".to_string(),
2865                            Applicability::MachineApplicable,
2866                            true,
2867                            false,
2868                        ));
2869                    }
2870                }
2871                (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
2872                    if let hir::ExprKind::Lit(_) = expr.kind
2873                        && let Ok(src) = sm.span_to_snippet(sp)
2874                        && replace_prefix(&src, "\"", "b\"").is_some()
2875                    {
2876                        return Some((
2877                            ::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())],
2878                            "consider adding a leading `b`".to_string(),
2879                            Applicability::MachineApplicable,
2880                            true,
2881                            false,
2882                        ));
2883                    }
2884                }
2885                _ => {}
2886            },
2887            (_, &ty::Ref(_, _, mutability), _) => {
2888                // Check if it can work when put into a ref. For example:
2889                //
2890                // ```
2891                // fn bar(x: &mut i32) {}
2892                //
2893                // let x = 0u32;
2894                // bar(&x); // error, expected &mut
2895                // ```
2896                let ref_ty = match mutability {
2897                    hir::Mutability::Mut => {
2898                        Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, checked_ty)
2899                    }
2900                    hir::Mutability::Not => {
2901                        Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, checked_ty)
2902                    }
2903                };
2904                if self.may_coerce(ref_ty, expected) {
2905                    let mut sugg_sp = sp;
2906                    if let hir::ExprKind::MethodCall(segment, receiver, args, _) = expr.kind {
2907                        let clone_trait =
2908                            self.tcx.require_lang_item(LangItem::Clone, segment.ident.span);
2909                        if args.is_empty()
2910                            && self
2911                                .typeck_results
2912                                .borrow()
2913                                .type_dependent_def_id(expr.hir_id)
2914                                .is_some_and(|did| {
2915                                    let ai = self.tcx.associated_item(did);
2916                                    ai.trait_container(self.tcx) == Some(clone_trait)
2917                                })
2918                            && segment.ident.name == sym::clone
2919                        {
2920                            // If this expression had a clone call when suggesting borrowing
2921                            // we want to suggest removing it because it'd now be unnecessary.
2922                            sugg_sp = receiver.span;
2923                        }
2924                    }
2925
2926                    if let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
2927                        && let Some(1) = self.deref_steps_for_suggestion(expected, checked_ty)
2928                        && self.typeck_results.borrow().expr_ty(inner).is_ref()
2929                    {
2930                        // We have `*&T`, check if what was expected was `&T`.
2931                        // If so, we may want to suggest removing a `*`.
2932                        sugg_sp = sugg_sp.with_hi(inner.span.lo());
2933                        return Some((
2934                            ::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())],
2935                            "consider removing deref here".to_string(),
2936                            Applicability::MachineApplicable,
2937                            true,
2938                            false,
2939                        ));
2940                    }
2941
2942                    // Don't try to suggest ref/deref on an `if` expression, because:
2943                    // - The `if` could be part of a desugared `if else` statement,
2944                    //   which would create impossible suggestions such as `if ... { ... } else &if { ... } else { ... }`.
2945                    // - In general the suggestions it creates such as `&if ... { ... } else { ... }` are not very helpful.
2946                    // We try to generate a suggestion such as `if ... { &... } else { &... }` instead.
2947                    if let hir::ExprKind::If(_c, then, els) = expr.kind {
2948                        // The `then` of a `Expr::If` always contains a block, and that block may have a final expression that we can borrow
2949                        // If the block does not have a final expression, it will return () and we do not make a suggestion to borrow that.
2950                        let ExprKind::Block(then, _) = then.kind else { return None };
2951                        let Some(then) = then.expr else { return None };
2952                        let (mut suggs, help, app, verbose, mutref) =
2953                            self.suggest_deref_or_ref(then, checked_ty, expected)?;
2954
2955                        // If there is no `else`, the return type of this `if` will be (), so suggesting to change the `then` block is useless
2956                        let els_expr = match els?.kind {
2957                            ExprKind::Block(block, _) => block.expr?,
2958                            _ => els?,
2959                        };
2960                        let (else_suggs, ..) =
2961                            self.suggest_deref_or_ref(els_expr, checked_ty, expected)?;
2962                        suggs.extend(else_suggs);
2963
2964                        return Some((suggs, help, app, verbose, mutref));
2965                    }
2966
2967                    if let Some((sugg, msg)) = self.can_use_as_ref(expr) {
2968                        return Some((
2969                            sugg,
2970                            msg.to_string(),
2971                            Applicability::MachineApplicable,
2972                            true,
2973                            false,
2974                        ));
2975                    }
2976
2977                    let prefix = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
2978                        Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", ident))
    })format!("{ident}: "),
2979                        None => String::new(),
2980                    };
2981
2982                    if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Assign(..), .. }) =
2983                        self.tcx.parent_hir_node(expr.hir_id)
2984                    {
2985                        if mutability.is_mut() {
2986                            // Suppressing this diagnostic, we'll properly print it in `check_expr_assign`
2987                            return None;
2988                        }
2989                    }
2990
2991                    let make_sugg = |expr: &Expr<'_>, span: Span, sugg: &str| {
2992                        if expr_needs_parens(expr) {
2993                            (
2994                                ::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![
2995                                    (span.shrink_to_lo(), format!("{prefix}{sugg}(")),
2996                                    (span.shrink_to_hi(), ")".to_string()),
2997                                ],
2998                                false,
2999                            )
3000                        } else {
3001                            (::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)
3002                        }
3003                    };
3004
3005                    // Suggest dereferencing the lhs for expressions such as `&T <= T`
3006                    if let hir::Node::Expr(hir::Expr {
3007                        kind: hir::ExprKind::Binary(_, lhs, ..),
3008                        ..
3009                    }) = self.tcx.parent_hir_node(expr.hir_id)
3010                        && let &ty::Ref(..) = self.check_expr(lhs).kind()
3011                    {
3012                        let (sugg, verbose) = make_sugg(lhs, lhs.span, "*");
3013
3014                        return Some((
3015                            sugg,
3016                            "consider dereferencing the borrow".to_string(),
3017                            Applicability::MachineApplicable,
3018                            verbose,
3019                            false,
3020                        ));
3021                    }
3022
3023                    let sugg = mutability.ref_prefix_str();
3024                    let (sugg, verbose) = make_sugg(expr, sp, sugg);
3025                    return Some((
3026                        sugg,
3027                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider {0}borrowing here",
                mutability.mutably_str()))
    })format!("consider {}borrowing here", mutability.mutably_str()),
3028                        Applicability::MachineApplicable,
3029                        verbose,
3030                        false,
3031                    ));
3032                }
3033            }
3034            (hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr), _, &ty::Ref(_, checked, _))
3035                if self.can_eq(self.param_env, checked, expected) =>
3036            {
3037                let make_sugg = |start: Span, end: BytePos| {
3038                    // skip `(` for tuples such as `(c) = (&123)`.
3039                    // make sure we won't suggest like `(c) = 123)` which is incorrect.
3040                    let sp = sm
3041                        .span_extend_while(start.shrink_to_lo(), |c| c == '(' || c.is_whitespace())
3042                        .map_or(start, |s| s.shrink_to_hi());
3043                    Some((
3044                        ::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())],
3045                        "consider removing the borrow".to_string(),
3046                        Applicability::MachineApplicable,
3047                        true,
3048                        true,
3049                    ))
3050                };
3051
3052                // We have `&T`, check if what was expected was `T`. If so,
3053                // we may want to suggest removing a `&`.
3054                if sm.is_imported(expr.span) {
3055                    // Go through the spans from which this span was expanded,
3056                    // and find the one that's pointing inside `sp`.
3057                    //
3058                    // E.g. for `&format!("")`, where we want the span to the
3059                    // `format!()` invocation instead of its expansion.
3060                    if let Some(call_span) =
3061                        iter::successors(Some(expr.span), |s| s.parent_callsite())
3062                            .find(|&s| sp.contains(s))
3063                        && sm.is_span_accessible(call_span)
3064                    {
3065                        return make_sugg(sp, call_span.lo());
3066                    }
3067                    return None;
3068                }
3069                if sp.contains(expr.span) && sm.is_span_accessible(expr.span) {
3070                    return make_sugg(sp, expr.span.lo());
3071                }
3072            }
3073            (_, &ty::RawPtr(ty_b, mutbl_b), &ty::Ref(_, ty_a, mutbl_a)) => {
3074                if let Some(steps) = self.deref_steps_for_suggestion(ty_a, ty_b)
3075                    // Only suggest valid if dereferencing needed.
3076                    && steps > 0
3077                    // The pointer type implements `Copy` trait so the suggestion is always valid.
3078                    && let Ok(src) = sm.span_to_snippet(sp)
3079                {
3080                    let derefs = "*".repeat(steps);
3081                    let old_prefix = mutbl_a.ref_prefix_str();
3082                    let new_prefix = mutbl_b.ref_prefix_str().to_owned() + &derefs;
3083
3084                    let suggestion = replace_prefix(&src, old_prefix, &new_prefix).map(|_| {
3085                        // skip `&` or `&mut ` if both mutabilities are mutable
3086                        let lo = sp.lo()
3087                            + BytePos(min(old_prefix.len(), mutbl_b.ref_prefix_str().len()) as _);
3088                        // skip `&` or `&mut `
3089                        let hi = sp.lo() + BytePos(old_prefix.len() as _);
3090                        let sp = sp.with_lo(lo).with_hi(hi);
3091
3092                        (
3093                            sp,
3094                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}",
                if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" },
                derefs))
    })format!(
3095                                "{}{derefs}",
3096                                if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" }
3097                            ),
3098                            if mutbl_b <= mutbl_a {
3099                                Applicability::MachineApplicable
3100                            } else {
3101                                Applicability::MaybeIncorrect
3102                            },
3103                        )
3104                    });
3105
3106                    if let Some((span, src, applicability)) = suggestion {
3107                        return Some((
3108                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, src)]))vec![(span, src)],
3109                            "consider dereferencing".to_string(),
3110                            applicability,
3111                            true,
3112                            false,
3113                        ));
3114                    }
3115                }
3116            }
3117            _ if sp == expr.span => {
3118                if let Some(mut steps) = self.deref_steps_for_suggestion(checked_ty, expected) {
3119                    let mut expr = expr.peel_blocks();
3120                    let mut prefix_span = expr.span.shrink_to_lo();
3121                    let mut remove = String::new();
3122
3123                    // Try peeling off any existing `&` and `&mut` to reach our target type
3124                    while steps > 0 {
3125                        if let hir::ExprKind::AddrOf(_, mutbl, inner) = expr.kind {
3126                            // If the expression has `&`, removing it would fix the error
3127                            prefix_span = prefix_span.with_hi(inner.span.lo());
3128                            expr = inner;
3129                            remove.push_str(mutbl.ref_prefix_str());
3130                            steps -= 1;
3131                        } else {
3132                            break;
3133                        }
3134                    }
3135                    // If we've reached our target type with just removing `&`, then just print now.
3136                    if steps == 0 && !remove.trim().is_empty() {
3137                        return Some((
3138                            ::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())],
3139                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing the `{0}`",
                remove.trim()))
    })format!("consider removing the `{}`", remove.trim()),
3140                            // Do not remove `&&` to get to bool, because it might be something like
3141                            // { a } && b, which we have a separate fixup suggestion that is more
3142                            // likely correct...
3143                            if remove.trim() == "&&" && expected == self.tcx.types.bool {
3144                                Applicability::MaybeIncorrect
3145                            } else {
3146                                Applicability::MachineApplicable
3147                            },
3148                            true,
3149                            false,
3150                        ));
3151                    }
3152
3153                    // For this suggestion to make sense, the type would need to be `Copy`,
3154                    // or we have to be moving out of a `Box<T>`
3155                    if self.type_is_copy_modulo_regions(self.param_env, expected)
3156                        // FIXME(compiler-errors): We can actually do this if the checked_ty is
3157                        // `steps` layers of boxes, not just one, but this is easier and most likely.
3158                        || (checked_ty.is_box() && steps == 1)
3159                        // We can always deref a binop that takes its arguments by ref.
3160                        || #[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!(
3161                            self.tcx.parent_hir_node(expr.hir_id),
3162                            hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, ..), .. })
3163                                if !op.node.is_by_value()
3164                        )
3165                    {
3166                        let deref_kind = if checked_ty.is_box() {
3167                            // detect Box::new(..)
3168                            if let ExprKind::Call(box_new, [_]) = expr.kind
3169                                && let ExprKind::Path(qpath) = &box_new.kind
3170                                && let Res::Def(DefKind::AssocFn, fn_id) =
3171                                    self.typeck_results.borrow().qpath_res(qpath, box_new.hir_id)
3172                                && self.tcx.is_diagnostic_item(sym::box_new, fn_id)
3173                            {
3174                                let l_paren = self.tcx.sess.source_map().next_point(box_new.span);
3175                                let r_paren = self.tcx.sess.source_map().end_point(expr.span);
3176                                return Some((
3177                                    ::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![
3178                                        (box_new.span.to(l_paren), String::new()),
3179                                        (r_paren, String::new()),
3180                                    ],
3181                                    "consider removing the Box".to_string(),
3182                                    Applicability::MachineApplicable,
3183                                    false,
3184                                    false,
3185                                ));
3186                            }
3187                            "unboxing the value"
3188                        } else if checked_ty.is_ref() {
3189                            "dereferencing the borrow"
3190                        } else {
3191                            "dereferencing the type"
3192                        };
3193
3194                        // Suggest removing `&` if we have removed any, otherwise suggest just
3195                        // dereferencing the remaining number of steps.
3196                        let message = if remove.is_empty() {
3197                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider {0}", deref_kind))
    })format!("consider {deref_kind}")
3198                        } else {
3199                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing the `{0}` and {1} instead",
                remove.trim(), deref_kind))
    })format!(
3200                                "consider removing the `{}` and {} instead",
3201                                remove.trim(),
3202                                deref_kind
3203                            )
3204                        };
3205
3206                        let prefix =
3207                            match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
3208                                Some(ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", ident))
    })format!("{ident}: "),
3209                                None => String::new(),
3210                            };
3211
3212                        let (span, suggestion) = if self.is_else_if_block(expr) {
3213                            // Don't suggest nonsense like `else *if`
3214                            return None;
3215                        } else if let Some(expr) = self.maybe_get_block_expr(expr) {
3216                            // prefix should be empty here..
3217                            (expr.span.shrink_to_lo(), "*".to_string())
3218                        } else {
3219                            (prefix_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", prefix,
                "*".repeat(steps)))
    })format!("{}{}", prefix, "*".repeat(steps)))
3220                        };
3221                        if suggestion.trim().is_empty() {
3222                            return None;
3223                        }
3224
3225                        if expr_needs_parens(expr) {
3226                            return Some((
3227                                ::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![
3228                                    (span, format!("{suggestion}(")),
3229                                    (expr.span.shrink_to_hi(), ")".to_string()),
3230                                ],
3231                                message,
3232                                Applicability::MachineApplicable,
3233                                true,
3234                                false,
3235                            ));
3236                        }
3237
3238                        return Some((
3239                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, suggestion)]))vec![(span, suggestion)],
3240                            message,
3241                            Applicability::MachineApplicable,
3242                            true,
3243                            false,
3244                        ));
3245                    }
3246                }
3247            }
3248            _ => {}
3249        }
3250        None
3251    }
3252
3253    /// Returns whether the given expression is an `else if`.
3254    fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool {
3255        if let hir::ExprKind::If(..) = expr.kind
3256            && let Node::Expr(hir::Expr { kind: hir::ExprKind::If(_, _, Some(else_expr)), .. }) =
3257                self.tcx.parent_hir_node(expr.hir_id)
3258        {
3259            return else_expr.hir_id == expr.hir_id;
3260        }
3261        false
3262    }
3263
3264    pub(crate) fn suggest_cast(
3265        &self,
3266        err: &mut Diag<'_>,
3267        expr: &hir::Expr<'_>,
3268        checked_ty: Ty<'tcx>,
3269        expected_ty: Ty<'tcx>,
3270        expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
3271    ) -> bool {
3272        if self.tcx.sess.source_map().is_imported(expr.span) {
3273            // Ignore if span is from within a macro.
3274            return false;
3275        }
3276
3277        let span = if let hir::ExprKind::Lit(lit) = &expr.kind { lit.span } else { expr.span };
3278        let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) else {
3279            return false;
3280        };
3281
3282        // If casting this expression to a given numeric type would be appropriate in case of a type
3283        // mismatch.
3284        //
3285        // We want to minimize the amount of casting operations that are suggested, as it can be a
3286        // lossy operation with potentially bad side effects, so we only suggest when encountering
3287        // an expression that indicates that the original type couldn't be directly changed.
3288        //
3289        // For now, don't suggest casting with `as`.
3290        let can_cast = false;
3291
3292        let mut sugg = ::alloc::vec::Vec::new()vec![];
3293
3294        if let hir::Node::ExprField(field) = self.tcx.parent_hir_node(expr.hir_id) {
3295            // `expr` is a literal field for a struct, only suggest if appropriate
3296            if field.is_shorthand {
3297                // This is a field literal
3298                sugg.push((field.ident.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", field.ident))
    })format!("{}: ", field.ident)));
3299            } else {
3300                // Likely a field was meant, but this field wasn't found. Do not suggest anything.
3301                return false;
3302            }
3303        };
3304
3305        if let hir::ExprKind::Call(path, args) = &expr.kind
3306            && let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
3307                (&path.kind, args.len())
3308            // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
3309            && let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
3310                (&base_ty.kind, path_segment.ident.name)
3311        {
3312            if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
3313                match ident.name {
3314                    sym::i128
3315                    | sym::i64
3316                    | sym::i32
3317                    | sym::i16
3318                    | sym::i8
3319                    | sym::u128
3320                    | sym::u64
3321                    | sym::u32
3322                    | sym::u16
3323                    | sym::u8
3324                    | sym::isize
3325                    | sym::usize
3326                        if base_ty_path.segments.len() == 1 =>
3327                    {
3328                        return false;
3329                    }
3330                    _ => {}
3331                }
3332            }
3333        }
3334
3335        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!(
3336            "you can convert {} `{}` to {} `{}`",
3337            checked_ty.kind().article(),
3338            checked_ty,
3339            expected_ty.kind().article(),
3340            expected_ty,
3341        );
3342        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!(
3343            "you can cast {} `{}` to {} `{}`",
3344            checked_ty.kind().article(),
3345            checked_ty,
3346            expected_ty.kind().article(),
3347            expected_ty,
3348        );
3349        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!(
3350            "change the type of the numeric literal from `{checked_ty}` to `{expected_ty}`",
3351        );
3352
3353        let close_paren = if self.precedence(expr) < ExprPrecedence::Unambiguous {
3354            sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
3355            ")"
3356        } else {
3357            ""
3358        };
3359
3360        let mut cast_suggestion = sugg.clone();
3361        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}")));
3362        let mut into_suggestion = sugg.clone();
3363        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()")));
3364        let mut suffix_suggestion = sugg.clone();
3365        suffix_suggestion.push((
3366            if #[allow(non_exhaustive_omitted_patterns)] match (expected_ty.kind(),
        checked_ty.kind()) {
    (ty::Int(_) | ty::Uint(_), ty::Float(_)) => true,
    _ => false,
}matches!(
3367                (expected_ty.kind(), checked_ty.kind()),
3368                (ty::Int(_) | ty::Uint(_), ty::Float(_))
3369            ) {
3370                // Remove fractional part from literal, for example `42.0f32` into `42`
3371                let src = src.trim_end_matches(&checked_ty.to_string());
3372                let len = src.split('.').next().unwrap().len();
3373                span.with_lo(span.lo() + BytePos(len as u32))
3374            } else {
3375                let len = src.trim_end_matches(&checked_ty.to_string()).len();
3376                span.with_lo(span.lo() + BytePos(len as u32))
3377            },
3378            if self.precedence(expr) < ExprPrecedence::Unambiguous {
3379                // Readd `)`
3380                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0})", expected_ty))
    })format!("{expected_ty})")
3381            } else {
3382                expected_ty.to_string()
3383            },
3384        ));
3385        let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
3386            if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
3387        };
3388        let is_negative_int =
3389            |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, ..));
3390        let is_uint = |ty: Ty<'_>| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Uint(..) => true,
    _ => false,
}matches!(ty.kind(), ty::Uint(..));
3391
3392        let in_const_context = self.tcx.hir_is_inside_const_context(expr.hir_id);
3393
3394        let suggest_fallible_into_or_lhs_from =
3395            |err: &mut Diag<'_>, exp_to_found_is_fallible: bool| {
3396                // If we know the expression the expected type is derived from, we might be able
3397                // to suggest a widening conversion rather than a narrowing one (which may
3398                // panic). For example, given x: u8 and y: u32, if we know the span of "x",
3399                //   x > y
3400                // can be given the suggestion "u32::from(x) > y" rather than
3401                // "x > y.try_into().unwrap()".
3402                let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
3403                    self.tcx
3404                        .sess
3405                        .source_map()
3406                        .span_to_snippet(expr.span)
3407                        .ok()
3408                        .map(|src| (expr, src))
3409                });
3410                let (msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
3411                    (lhs_expr_and_src, exp_to_found_is_fallible)
3412                {
3413                    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!(
3414                        "you can convert `{lhs_src}` from `{expected_ty}` to `{checked_ty}`, matching the type of `{src}`",
3415                    );
3416                    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![
3417                        (lhs_expr.span.shrink_to_lo(), format!("{checked_ty}::from(")),
3418                        (lhs_expr.span.shrink_to_hi(), ")".to_string()),
3419                    ];
3420                    (msg, suggestion)
3421                } else {
3422                    let msg =
3423                        ::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());
3424                    let mut suggestion = sugg.clone();
3425                    suggestion.push((
3426                        expr.span.shrink_to_hi(),
3427                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.try_into().unwrap()",
                close_paren))
    })format!("{close_paren}.try_into().unwrap()"),
3428                    ));
3429                    (msg, suggestion)
3430                };
3431                err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
3432            };
3433
3434        let suggest_to_change_suffix_or_into =
3435            |err: &mut Diag<'_>, found_to_exp_is_fallible: bool, exp_to_found_is_fallible: bool| {
3436                let exp_is_lhs = expected_ty_expr.is_some_and(|e| self.tcx.hir_is_lhs(e.hir_id));
3437
3438                if exp_is_lhs {
3439                    return;
3440                }
3441
3442                let always_fallible = found_to_exp_is_fallible
3443                    && (exp_to_found_is_fallible || expected_ty_expr.is_none());
3444                let msg = if literal_is_ty_suffixed(expr) {
3445                    lit_msg.clone()
3446                } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
3447                    // We now know that converting either the lhs or rhs is fallible. Before we
3448                    // suggest a fallible conversion, check if the value can never fit in the
3449                    // expected type.
3450                    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}`");
3451                    err.note(msg);
3452                    return;
3453                } else if in_const_context {
3454                    // Do not recommend `into` or `try_into` in const contexts.
3455                    return;
3456                } else if found_to_exp_is_fallible {
3457                    return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
3458                } else {
3459                    msg.clone()
3460                };
3461                let suggestion = if literal_is_ty_suffixed(expr) {
3462                    suffix_suggestion.clone()
3463                } else {
3464                    into_suggestion.clone()
3465                };
3466                err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
3467            };
3468
3469        match (expected_ty.kind(), checked_ty.kind()) {
3470            (ty::Int(exp), ty::Int(found)) => {
3471                let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3472                {
3473                    (Some(exp), Some(found)) if exp < found => (true, false),
3474                    (Some(exp), Some(found)) if exp > found => (false, true),
3475                    (None, Some(8 | 16)) => (false, true),
3476                    (Some(8 | 16), None) => (true, false),
3477                    (None, _) | (_, None) => (true, true),
3478                    _ => (false, false),
3479                };
3480                suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3481                true
3482            }
3483            (ty::Uint(exp), ty::Uint(found)) => {
3484                let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3485                {
3486                    (Some(exp), Some(found)) if exp < found => (true, false),
3487                    (Some(exp), Some(found)) if exp > found => (false, true),
3488                    (None, Some(8 | 16)) => (false, true),
3489                    (Some(8 | 16), None) => (true, false),
3490                    (None, _) | (_, None) => (true, true),
3491                    _ => (false, false),
3492                };
3493                suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3494                true
3495            }
3496            (&ty::Int(exp), &ty::Uint(found)) => {
3497                let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3498                {
3499                    (Some(exp), Some(found)) if found < exp => (false, true),
3500                    (None, Some(8)) => (false, true),
3501                    _ => (true, true),
3502                };
3503                suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3504                true
3505            }
3506            (&ty::Uint(exp), &ty::Int(found)) => {
3507                let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3508                {
3509                    (Some(exp), Some(found)) if found > exp => (true, false),
3510                    (Some(8), None) => (true, false),
3511                    _ => (true, true),
3512                };
3513                suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3514                true
3515            }
3516            (ty::Float(exp), ty::Float(found)) => {
3517                if found.bit_width() < exp.bit_width() {
3518                    suggest_to_change_suffix_or_into(err, false, true);
3519                } else if literal_is_ty_suffixed(expr) {
3520                    err.multipart_suggestion(
3521                        lit_msg,
3522                        suffix_suggestion,
3523                        Applicability::MachineApplicable,
3524                    );
3525                } else if can_cast {
3526                    // Missing try_into implementation for `f64` to `f32`
3527                    err.multipart_suggestion(
3528                        ::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"),
3529                        cast_suggestion,
3530                        Applicability::MaybeIncorrect, // lossy conversion
3531                    );
3532                }
3533                true
3534            }
3535            (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
3536                if literal_is_ty_suffixed(expr) {
3537                    err.multipart_suggestion(
3538                        lit_msg,
3539                        suffix_suggestion,
3540                        Applicability::MachineApplicable,
3541                    );
3542                } else if can_cast {
3543                    // Missing try_into implementation for `{float}` to `{integer}`
3544                    err.multipart_suggestion(
3545                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, rounding the float towards zero",
                msg))
    })format!("{msg}, rounding the float towards zero"),
3546                        cast_suggestion,
3547                        Applicability::MaybeIncorrect, // lossy conversion
3548                    );
3549                }
3550                true
3551            }
3552            (ty::Float(exp), ty::Uint(found)) => {
3553                // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
3554                if exp.bit_width() > found.bit_width().unwrap_or(256) {
3555                    err.multipart_suggestion(
3556                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer",
                msg))
    })format!(
3557                            "{msg}, producing the floating point representation of the integer",
3558                        ),
3559                        into_suggestion,
3560                        Applicability::MachineApplicable,
3561                    );
3562                } else if literal_is_ty_suffixed(expr) {
3563                    err.multipart_suggestion(
3564                        lit_msg,
3565                        suffix_suggestion,
3566                        Applicability::MachineApplicable,
3567                    );
3568                } else {
3569                    // Missing try_into implementation for `{integer}` to `{float}`
3570                    err.multipart_suggestion(
3571                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer, rounded if necessary",
                cast_msg))
    })format!(
3572                            "{cast_msg}, producing the floating point representation of the integer, \
3573                                 rounded if necessary",
3574                        ),
3575                        cast_suggestion,
3576                        Applicability::MaybeIncorrect, // lossy conversion
3577                    );
3578                }
3579                true
3580            }
3581            (ty::Float(exp), ty::Int(found)) => {
3582                // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
3583                if exp.bit_width() > found.bit_width().unwrap_or(256) {
3584                    err.multipart_suggestion(
3585                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer",
                msg.clone()))
    })format!(
3586                            "{}, producing the floating point representation of the integer",
3587                            msg.clone(),
3588                        ),
3589                        into_suggestion,
3590                        Applicability::MachineApplicable,
3591                    );
3592                } else if literal_is_ty_suffixed(expr) {
3593                    err.multipart_suggestion(
3594                        lit_msg,
3595                        suffix_suggestion,
3596                        Applicability::MachineApplicable,
3597                    );
3598                } else {
3599                    // Missing try_into implementation for `{integer}` to `{float}`
3600                    err.multipart_suggestion(
3601                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer, rounded if necessary",
                &msg))
    })format!(
3602                            "{}, producing the floating point representation of the integer, \
3603                                rounded if necessary",
3604                            &msg,
3605                        ),
3606                        cast_suggestion,
3607                        Applicability::MaybeIncorrect, // lossy conversion
3608                    );
3609                }
3610                true
3611            }
3612            (
3613                &ty::Uint(ty::UintTy::U32 | ty::UintTy::U64 | ty::UintTy::U128)
3614                | &ty::Int(ty::IntTy::I32 | ty::IntTy::I64 | ty::IntTy::I128),
3615                &ty::Char,
3616            ) => {
3617                err.multipart_suggestion(
3618                    ::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"),
3619                    cast_suggestion,
3620                    Applicability::MachineApplicable,
3621                );
3622                true
3623            }
3624            _ => false,
3625        }
3626    }
3627
3628    /// Identify when the user has written `foo..bar()` instead of `foo.bar()`.
3629    pub(crate) fn suggest_method_call_on_range_literal(
3630        &self,
3631        err: &mut Diag<'_>,
3632        expr: &hir::Expr<'tcx>,
3633        checked_ty: Ty<'tcx>,
3634        expected_ty: Ty<'tcx>,
3635    ) {
3636        if !hir::is_range_literal(expr) {
3637            return;
3638        }
3639        let hir::ExprKind::Struct(&qpath, [start, end], _) = expr.kind else {
3640            return;
3641        };
3642        if !self.tcx.qpath_is_lang_item(qpath, LangItem::Range) {
3643            return;
3644        }
3645        if let hir::Node::ExprField(_) = self.tcx.parent_hir_node(expr.hir_id) {
3646            // Ignore `Foo { field: a..Default::default() }`
3647            return;
3648        }
3649        let mut expr = end.expr;
3650        let mut expectation = Some(expected_ty);
3651        while let hir::ExprKind::MethodCall(_, rcvr, ..) = expr.kind {
3652            // Getting to the root receiver and asserting it is a fn call let's us ignore cases in
3653            // `tests/ui/methods/issues/issue-90315.stderr`.
3654            expr = rcvr;
3655            // If we have more than one layer of calls, then the expected ty
3656            // cannot guide the method probe.
3657            expectation = None;
3658        }
3659        let hir::ExprKind::Call(method_name, _) = expr.kind else {
3660            return;
3661        };
3662        let ty::Adt(adt, _) = checked_ty.kind() else {
3663            return;
3664        };
3665        if self.tcx.lang_items().range_struct() != Some(adt.did()) {
3666            return;
3667        }
3668        if let ty::Adt(adt, _) = expected_ty.kind()
3669            && self.tcx.is_lang_item(adt.did(), LangItem::Range)
3670        {
3671            return;
3672        }
3673        // Check if start has method named end.
3674        let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else {
3675            return;
3676        };
3677        let [hir::PathSegment { ident, .. }] = p.segments else {
3678            return;
3679        };
3680        let self_ty = self.typeck_results.borrow().expr_ty(start.expr);
3681        let Ok(_pick) = self.lookup_probe_for_diagnostic(
3682            *ident,
3683            self_ty,
3684            expr,
3685            probe::ProbeScope::AllTraits,
3686            expectation,
3687        ) else {
3688            return;
3689        };
3690        let mut sugg = ".";
3691        let mut span = start.expr.span.between(end.expr.span);
3692        if span.lo() + BytePos(2) == span.hi() {
3693            // There's no space between the start, the range op and the end, suggest removal which
3694            // will be more noticeable than the replacement of `..` with `.`.
3695            span = span.with_lo(span.lo() + BytePos(1));
3696            sugg = "";
3697        }
3698        err.span_suggestion_verbose(
3699            span,
3700            "you likely meant to write a method call instead of a range",
3701            sugg,
3702            Applicability::MachineApplicable,
3703        );
3704    }
3705
3706    /// Identify when the type error is because `()` is found in a binding that was assigned a
3707    /// block without a tail expression.
3708    pub(crate) fn suggest_return_binding_for_missing_tail_expr(
3709        &self,
3710        err: &mut Diag<'_>,
3711        expr: &hir::Expr<'_>,
3712        checked_ty: Ty<'tcx>,
3713        expected_ty: Ty<'tcx>,
3714    ) {
3715        if !checked_ty.is_unit() {
3716            return;
3717        }
3718        let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
3719            return;
3720        };
3721        let hir::def::Res::Local(hir_id) = path.res else {
3722            return;
3723        };
3724        let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
3725            return;
3726        };
3727        let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
3728            self.tcx.parent_hir_node(pat.hir_id)
3729        else {
3730            return;
3731        };
3732        let hir::ExprKind::Block(block, None) = init.kind else {
3733            return;
3734        };
3735        if block.expr.is_some() {
3736            return;
3737        }
3738        let [.., stmt] = block.stmts else {
3739            err.span_label(block.span, "this empty block is missing a tail expression");
3740            return;
3741        };
3742        let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
3743            return;
3744        };
3745        let Some(ty) = self.node_ty_opt(tail_expr.hir_id) else {
3746            return;
3747        };
3748        if self.can_eq(self.param_env, expected_ty, ty)
3749            // FIXME: this happens with macro calls. Need to figure out why the stmt
3750            // `println!();` doesn't include the `;` in its `Span`. (#133845)
3751            // We filter these out to avoid ICEs with debug assertions on caused by
3752            // empty suggestions.
3753            && stmt.span.hi() != tail_expr.span.hi()
3754        {
3755            err.span_suggestion_short(
3756                stmt.span.with_lo(tail_expr.span.hi()),
3757                "remove this semicolon",
3758                "",
3759                Applicability::MachineApplicable,
3760            );
3761        } else {
3762            err.span_label(block.span, "this block is missing a tail expression");
3763        }
3764    }
3765
3766    pub(crate) fn suggest_swapping_lhs_and_rhs(
3767        &self,
3768        err: &mut Diag<'_>,
3769        rhs_ty: Ty<'tcx>,
3770        lhs_ty: Ty<'tcx>,
3771        rhs_expr: &'tcx hir::Expr<'tcx>,
3772        lhs_expr: &'tcx hir::Expr<'tcx>,
3773    ) {
3774        if let Some(partial_eq_def_id) = self.infcx.tcx.lang_items().eq_trait()
3775            && self
3776                .infcx
3777                .type_implements_trait(partial_eq_def_id, [rhs_ty, lhs_ty], self.param_env)
3778                .must_apply_modulo_regions()
3779        {
3780            let sm = self.tcx.sess.source_map();
3781            // If the span of rhs_expr or lhs_expr is in an external macro,
3782            // we just suppress the suggestion. See issue #139050
3783            if !rhs_expr.span.in_external_macro(sm)
3784                && !lhs_expr.span.in_external_macro(sm)
3785                && let Ok(rhs_snippet) = sm.span_to_snippet(rhs_expr.span)
3786                && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_expr.span)
3787            {
3788                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}>`"));
3789                err.multipart_suggestion(
3790                    "consider swapping the equality",
3791                    ::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)],
3792                    Applicability::MaybeIncorrect,
3793                );
3794            }
3795        }
3796    }
3797}