Skip to main content

rustc_hir_typeck/fn_ctxt/
suggestions.rs

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