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