Skip to main content

rustc_trait_selection/error_reporting/infer/
need_type_info.rs

1use std::borrow::Cow;
2use std::iter;
3use std::path::PathBuf;
4
5use rustc_errors::codes::*;
6use rustc_errors::{Diag, IntoDiagArg};
7use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
8use rustc_hir::def_id::{DefId, LocalDefId};
9use rustc_hir::intravisit::{self, Visitor};
10use rustc_hir::{
11    self as hir, Body, Closure, Expr, ExprKind, FnRetTy, HirId, LetStmt, LocalSource, PatKind,
12};
13use rustc_middle::bug;
14use rustc_middle::hir::nested_filter;
15use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, DerefAdjustKind};
16use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Print, Printer};
17use rustc_middle::ty::{
18    self, GenericArg, GenericArgKind, GenericArgsRef, GenericParamDefKind, InferConst,
19    IsSuggestable, Term, TermKind, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
20    TypeVisitableExt, TypeckResults,
21};
22use rustc_next_trait_solver::solve::TyOrConstInferVar;
23use rustc_span::{BytePos, DUMMY_SP, Ident, Span, sym};
24use tracing::{debug, instrument, warn};
25
26use super::nice_region_error::placeholder_error::Highlighted;
27use crate::diagnostics::{
28    AmbiguousImpl, AmbiguousReturn, AnnotationRequired, InferenceBadError, SourceKindSubdiag,
29    SpecifyGenericParamsSuggestion,
30};
31use crate::error_reporting::TypeErrCtxt;
32use crate::infer::InferCtxt;
33
34pub enum TypeAnnotationNeeded {
35    /// ```compile_fail,E0282
36    /// let x;
37    /// ```
38    E0282,
39    /// An implementation cannot be chosen unambiguously because of lack of information.
40    /// ```compile_fail,E0790
41    /// let _ = Default::default();
42    /// ```
43    E0283,
44    /// ```compile_fail,E0284
45    /// let mut d: u64 = 2;
46    /// d = d % 1u32.into();
47    /// ```
48    E0284,
49}
50
51impl From<TypeAnnotationNeeded> for ErrCode {
52    fn from(val: TypeAnnotationNeeded) -> Self {
53        match val {
54            TypeAnnotationNeeded::E0282 => E0282,
55            TypeAnnotationNeeded::E0283 => E0283,
56            TypeAnnotationNeeded::E0284 => E0284,
57        }
58    }
59}
60
61/// Information about a constant or a type containing inference variables.
62pub struct InferenceDiagnosticsData {
63    pub name: String,
64    pub span: Option<Span>,
65    pub kind: UnderspecifiedArgKind,
66    pub parent: Option<InferenceDiagnosticsParentData>,
67}
68
69/// Data on the parent definition where a generic argument was declared.
70pub struct InferenceDiagnosticsParentData {
71    prefix: &'static str,
72    name: String,
73}
74
75#[derive(#[automatically_derived]
impl ::core::clone::Clone for UnderspecifiedArgKind {
    #[inline]
    fn clone(&self) -> UnderspecifiedArgKind {
        match self {
            UnderspecifiedArgKind::Type { prefix: __self_0 } =>
                UnderspecifiedArgKind::Type {
                    prefix: ::core::clone::Clone::clone(__self_0),
                },
            UnderspecifiedArgKind::Const { is_parameter: __self_0 } =>
                UnderspecifiedArgKind::Const {
                    is_parameter: ::core::clone::Clone::clone(__self_0),
                },
        }
    }
}Clone)]
76pub enum UnderspecifiedArgKind {
77    Type { prefix: Cow<'static, str> },
78    Const { is_parameter: bool },
79}
80
81impl InferenceDiagnosticsData {
82    fn can_add_more_info(&self) -> bool {
83        !(self.name == "_" && #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    UnderspecifiedArgKind::Type { .. } => true,
    _ => false,
}matches!(self.kind, UnderspecifiedArgKind::Type { .. }))
84    }
85
86    fn where_x_is_kind<'tcx>(&self, infcx: &InferCtxt<'tcx>, in_type: Ty<'tcx>) -> &'static str {
87        if in_type.is_ty_or_numeric_infer() {
88            ""
89        } else if self.name == "_" {
90            let displayed_ty = infcx
91                .resolve_vars_if_possible(in_type)
92                .fold_with(&mut ClosureEraser { infcx, depth: 0 });
93            if displayed_ty.is_ty_or_numeric_infer() {
94                ""
95            } else {
96                match displayed_ty
97                    .walk()
98                    .filter_map(TyOrConstInferVar::maybe_from_generic_arg::<TyCtxt<'tcx>>)
99                    .take(2)
100                    .count()
101                {
102                    0 => "",
103                    1 => "underscore_single",
104                    _ => "underscore_multiple",
105                }
106            }
107        } else {
108            "has_name"
109        }
110    }
111
112    /// Generate a label for a generic argument which can't be inferred. When not
113    /// much is known about the argument, `use_diag` may be used to describe the
114    /// labeled value.
115    fn make_bad_error(&self, span: Span) -> InferenceBadError<'_> {
116        let has_parent = self.parent.is_some();
117        let bad_kind = if self.can_add_more_info() { "more_info" } else { "other" };
118        let (parent_prefix, parent_name) = self
119            .parent
120            .as_ref()
121            .map(|parent| (parent.prefix, parent.name.clone()))
122            .unwrap_or_default();
123        InferenceBadError {
124            span,
125            bad_kind,
126            prefix_kind: self.kind.clone(),
127            prefix: self.kind.try_get_prefix().unwrap_or_default(),
128            name: self.name.clone(),
129            has_parent,
130            parent_prefix,
131            parent_name,
132        }
133    }
134}
135
136impl InferenceDiagnosticsParentData {
137    fn for_parent_def_id(
138        tcx: TyCtxt<'_>,
139        parent_def_id: DefId,
140    ) -> Option<InferenceDiagnosticsParentData> {
141        let parent_name =
142            tcx.def_key(parent_def_id).disambiguated_data.data.get_opt_name()?.to_string();
143
144        Some(InferenceDiagnosticsParentData {
145            prefix: tcx.def_descr(parent_def_id),
146            name: parent_name,
147        })
148    }
149
150    fn for_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<InferenceDiagnosticsParentData> {
151        Self::for_parent_def_id(tcx, tcx.parent(def_id))
152    }
153}
154
155impl IntoDiagArg for UnderspecifiedArgKind {
156    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
157        let kind = match self {
158            Self::Type { .. } => "type",
159            Self::Const { is_parameter: true } => "const_with_param",
160            Self::Const { is_parameter: false } => "const",
161        };
162        rustc_errors::DiagArgValue::Str(kind.into())
163    }
164}
165
166impl UnderspecifiedArgKind {
167    fn try_get_prefix(&self) -> Option<&str> {
168        match self {
169            Self::Type { prefix } => Some(prefix.as_ref()),
170            Self::Const { .. } => None,
171        }
172    }
173}
174
175struct ClosureEraser<'a, 'tcx> {
176    infcx: &'a InferCtxt<'tcx>,
177    depth: usize,
178}
179
180impl<'a, 'tcx> ClosureEraser<'a, 'tcx> {
181    fn new_infer(&mut self) -> Ty<'tcx> {
182        self.infcx.next_ty_var(DUMMY_SP)
183    }
184}
185
186impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ClosureEraser<'a, 'tcx> {
187    fn cx(&self) -> TyCtxt<'tcx> {
188        self.infcx.tcx
189    }
190
191    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
192        self.depth += 1;
193        let ty = match ty.kind() {
194            ty::Closure(_, args) => {
195                // For a closure type, we turn it into a function pointer so that it gets rendered
196                // as `fn(args) -> Ret`.
197                let closure_sig = args.as_closure().sig();
198                Ty::new_fn_ptr(
199                    self.cx(),
200                    self.cx().signature_unclosure(closure_sig, hir::Safety::Safe),
201                )
202            }
203            ty::Adt(_, args) if !args.iter().any(|a| a.has_infer()) => {
204                // We have a type that doesn't have any inference variables, so we replace
205                // the whole thing with `_`. The type system already knows about this type in
206                // its entirety and it is redundant to specify it for the user. The user only
207                // needs to specify the type parameters that we *couldn't* figure out.
208                self.new_infer()
209            }
210            ty::Adt(def, args) => {
211                let generics = self.cx().generics_of(def.did());
212                let generics: Vec<bool> = generics
213                    .own_params
214                    .iter()
215                    .map(|param| param.default_value(self.cx()).is_some())
216                    .collect();
217                let ty = Ty::new_adt(
218                    self.cx(),
219                    *def,
220                    self.cx().mk_args_from_iter(generics.into_iter().zip(args.iter()).map(
221                        |(has_default, arg)| {
222                            if arg.has_infer() {
223                                // This param has an unsubstituted type variable, meaning that this
224                                // type has a (potentially deeply nested) type parameter from the
225                                // corresponding type's definition. We have explicitly asked this
226                                // type to not be hidden. In either case, we keep the type and don't
227                                // substitute with `_` just yet.
228                                arg.fold_with(self)
229                            } else if has_default {
230                                // We have a type param that has a default type, like the allocator
231                                // in Vec. We decided to show `Vec` itself, because it hasn't yet
232                                // been replaced by an `_` `Infer`, but we want to ensure that the
233                                // type parameter with default types does *not* get replaced with
234                                // `_` because then we'd end up with `Vec<_, _>`, instead of
235                                // `Vec<_>`.
236                                arg
237                            } else if let GenericArgKind::Type(_) = arg.kind() {
238                                // We don't replace lifetime or const params, only type params.
239                                self.new_infer().into()
240                            } else {
241                                arg.fold_with(self)
242                            }
243                        },
244                    )),
245                );
246                ty
247            }
248            _ if ty.has_infer() => {
249                // This type has a (potentially nested) type parameter that we couldn't figure out.
250                // We will print this depth of type, so at least the type name and at least one of
251                // its type parameters.
252                ty.super_fold_with(self)
253            }
254            // We are in the top-level type, not one of its type parameters. Name it with its
255            // parameters replaced.
256            _ if self.depth == 1 => ty.super_fold_with(self),
257            // We don't have an unknown type parameter anywhere, and we are in a type parameter.
258            // Replace with `_`.
259            _ => self.new_infer(),
260        };
261        self.depth -= 1;
262        ty
263    }
264
265    fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
266        // Avoid accidentally erasing the type of the const.
267        c
268    }
269}
270
271fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'tcx>, ns: Namespace) -> FmtPrinter<'a, 'tcx> {
272    let mut p = FmtPrinter::new(infcx.tcx, ns);
273    let ty_getter = move |ty_vid| {
274        if infcx.try_resolve_ty_var(ty_vid).is_ok() {
275            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs:275",
                        "rustc_trait_selection::error_reporting::infer::need_type_info",
                        ::tracing::Level::WARN,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs"),
                        ::tracing_core::__macro_support::Option::Some(275u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::WARN <=
                    ::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!("resolved ty var in error message")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};warn!("resolved ty var in error message");
276        }
277
278        let var_origin = infcx.type_var_origin(ty_vid);
279        if let Some(def_id) = var_origin.param_def_id
280            // The `Self` param of a trait has the def-id of the trait,
281            // since it's a synthetic parameter.
282            && infcx.tcx.def_kind(def_id) == DefKind::TyParam
283            && let name = infcx.tcx.item_name(def_id)
284            && !var_origin.span.from_expansion()
285        {
286            let generics = infcx.tcx.generics_of(infcx.tcx.parent(def_id));
287            let idx = generics.param_def_id_to_index(infcx.tcx, def_id).unwrap();
288            let generic_param_def = generics.param_at(idx as usize, infcx.tcx);
289            if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param_def.kind {
290                None
291            } else {
292                Some(name)
293            }
294        } else {
295            None
296        }
297    };
298    p.ty_infer_name_resolver = Some(Box::new(ty_getter));
299    let const_getter =
300        move |ct_vid| Some(infcx.tcx.item_name(infcx.const_var_origin(ct_vid)?.param_def_id?));
301    p.const_infer_name_resolver = Some(Box::new(const_getter));
302    p
303}
304
305fn ty_to_string<'tcx>(
306    infcx: &InferCtxt<'tcx>,
307    ty: Ty<'tcx>,
308    called_method_def_id: Option<DefId>,
309) -> String {
310    let mut p = fmt_printer(infcx, Namespace::TypeNS);
311    let ty = infcx.resolve_vars_if_possible(ty);
312    // We use `fn` ptr syntax for closures, but this only works when the closure does not capture
313    // anything. We also remove all type parameters that are fully known to the type system.
314    let ty = ty.fold_with(&mut ClosureEraser { infcx, depth: 0 });
315
316    match (ty.kind(), called_method_def_id) {
317        // We don't want the regular output for `fn`s because it includes its path in
318        // invalid pseudo-syntax, we want the `fn`-pointer output instead.
319        (ty::FnDef(..), _) => {
320            ty.fn_sig(infcx.tcx).print(&mut p).unwrap();
321            p.into_buffer()
322        }
323        (_, Some(def_id))
324            if ty.is_ty_or_numeric_infer()
325                && infcx.tcx.get_diagnostic_item(sym::iterator_collect_fn) == Some(def_id) =>
326        {
327            "Vec<_>".to_string()
328        }
329        _ if ty.is_ty_or_numeric_infer() => "/* Type */".to_string(),
330        _ => {
331            ty.print(&mut p).unwrap();
332            p.into_buffer()
333        }
334    }
335}
336
337/// We don't want to directly use `ty_to_string` for closures as their type isn't really
338/// something users are familiar with. Directly printing the `fn_sig` of closures also
339/// doesn't work as they actually use the "rust-call" API.
340fn closure_as_fn_str<'tcx>(infcx: &InferCtxt<'tcx>, ty: Ty<'tcx>) -> String {
341    let ty::Closure(_, args) = ty.kind() else {
342        ::rustc_middle::util::bug::bug_fmt(format_args!("cannot convert non-closure to fn str in `closure_as_fn_str`"))bug!("cannot convert non-closure to fn str in `closure_as_fn_str`")
343    };
344    let fn_sig = args.as_closure().sig();
345    let args = fn_sig
346        .inputs()
347        .skip_binder()
348        .iter()
349        .next()
350        .map(|args| {
351            args.tuple_fields()
352                .iter()
353                .map(|arg| ty_to_string(infcx, arg, None))
354                .collect::<Vec<_>>()
355                .join(", ")
356        })
357        .unwrap_or_default();
358    let ret = if fn_sig.output().skip_binder().is_unit() {
359        String::new()
360    } else {
361        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" -> {0}",
                ty_to_string(infcx, fn_sig.output().skip_binder(), None)))
    })format!(" -> {}", ty_to_string(infcx, fn_sig.output().skip_binder(), None))
362    };
363    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("fn({0}){1}", args, ret))
    })format!("fn({args}){ret}")
364}
365
366impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
367    /// Extracts data used by diagnostic for either types or constants
368    /// which were stuck during inference.
369    pub fn extract_inference_diagnostics_data(
370        &self,
371        term: Term<'tcx>,
372        highlight: ty::print::RegionHighlightMode<'tcx>,
373    ) -> InferenceDiagnosticsData {
374        let tcx = self.tcx;
375        match term.kind() {
376            TermKind::Ty(ty) => {
377                if let ty::Infer(ty::TyVar(ty_vid)) = *ty.kind() {
378                    let var_origin = self.infcx.type_var_origin(ty_vid);
379                    if let Some(def_id) = var_origin.param_def_id
380                        // The `Self` param of a trait has the def-id of the trait,
381                        // since it's a synthetic parameter.
382                        && self.tcx.def_kind(def_id) == DefKind::TyParam
383                        && !var_origin.span.from_expansion()
384                    {
385                        return InferenceDiagnosticsData {
386                            name: self.tcx.item_name(def_id).to_string(),
387                            span: Some(var_origin.span),
388                            kind: UnderspecifiedArgKind::Type { prefix: "type parameter".into() },
389                            parent: InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id),
390                        };
391                    }
392                }
393
394                InferenceDiagnosticsData {
395                    name: Highlighted { highlight, ns: Namespace::TypeNS, tcx, value: ty }
396                        .to_string(),
397                    span: None,
398                    kind: UnderspecifiedArgKind::Type { prefix: ty.prefix_string(self.tcx) },
399                    parent: None,
400                }
401            }
402            TermKind::Const(ct) => {
403                if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
404                    let origin = self.const_var_origin(vid).expect("expected unresolved const var");
405                    if let Some(def_id) = origin.param_def_id {
406                        return InferenceDiagnosticsData {
407                            name: self.tcx.item_name(def_id).to_string(),
408                            span: Some(origin.span),
409                            kind: UnderspecifiedArgKind::Const { is_parameter: true },
410                            parent: InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id),
411                        };
412                    }
413
414                    if true {
    if !!origin.span.is_dummy() {
        ::core::panicking::panic("assertion failed: !origin.span.is_dummy()")
    };
};debug_assert!(!origin.span.is_dummy());
415                    InferenceDiagnosticsData {
416                        name: Highlighted { highlight, ns: Namespace::ValueNS, tcx, value: ct }
417                            .to_string(),
418                        span: Some(origin.span),
419                        kind: UnderspecifiedArgKind::Const { is_parameter: false },
420                        parent: None,
421                    }
422                } else {
423                    // If we end up here the `FindInferSourceVisitor`
424                    // won't work, as its expected argument isn't an inference variable.
425                    //
426                    // FIXME: Ideally we should look into the generic constant
427                    // to figure out which inference var is actually unresolved so that
428                    // this path is unreachable.
429                    InferenceDiagnosticsData {
430                        name: Highlighted { highlight, ns: Namespace::ValueNS, tcx, value: ct }
431                            .to_string(),
432                        span: None,
433                        kind: UnderspecifiedArgKind::Const { is_parameter: false },
434                        parent: None,
435                    }
436                }
437            }
438        }
439    }
440
441    /// Used as a fallback in [TypeErrCtxt::emit_inference_failure_err]
442    /// in case we weren't able to get a better error.
443    fn bad_inference_failure_err(
444        &self,
445        span: Span,
446        arg_data: InferenceDiagnosticsData,
447        error_code: TypeAnnotationNeeded,
448    ) -> Diag<'a> {
449        let source_kind = "other";
450        let source_name = "";
451        let failure_span = None;
452        let subdiagnostic = None;
453        let bad_label = Some(arg_data.make_bad_error(span));
454        match error_code {
455            TypeAnnotationNeeded::E0282 => self.dcx().create_err(AnnotationRequired {
456                span,
457                source_kind,
458                source_name,
459                failure_span,
460                subdiagnostic,
461                bad_label,
462            }),
463            TypeAnnotationNeeded::E0283 => self.dcx().create_err(AmbiguousImpl {
464                span,
465                source_kind,
466                source_name,
467                failure_span,
468                subdiagnostic,
469                bad_label,
470            }),
471            TypeAnnotationNeeded::E0284 => self.dcx().create_err(AmbiguousReturn {
472                span,
473                source_kind,
474                source_name,
475                failure_span,
476                subdiagnostic,
477                bad_label,
478            }),
479        }
480    }
481
482    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("emit_inference_failure_err",
                                    "rustc_trait_selection::error_reporting::infer::need_type_info",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs"),
                                    ::tracing_core::__macro_support::Option::Some(482u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("body_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("body_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("failure_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("failure_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("term")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("term");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("should_label_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("should_label_span");
                                                        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::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::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(&body_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&failure_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&term)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&should_label_span
                                                            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: Diag<'a> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.emit_inference_failure_err_with_type_hint(body_def_id,
                failure_span, term, error_code, should_label_span, None)
        }
    }
}#[instrument(level = "debug", skip(self, error_code))]
483    pub fn emit_inference_failure_err(
484        &self,
485        body_def_id: LocalDefId,
486        failure_span: Span,
487        term: Term<'tcx>,
488        error_code: TypeAnnotationNeeded,
489        should_label_span: bool,
490    ) -> Diag<'a> {
491        self.emit_inference_failure_err_with_type_hint(
492            body_def_id,
493            failure_span,
494            term,
495            error_code,
496            should_label_span,
497            None,
498        )
499    }
500
501    pub fn emit_inference_failure_err_with_type_hint(
502        &self,
503        body_def_id: LocalDefId,
504        failure_span: Span,
505        term: Term<'tcx>,
506        error_code: TypeAnnotationNeeded,
507        should_label_span: bool,
508        ty: Option<Ty<'tcx>>,
509    ) -> Diag<'a> {
510        let term = self.resolve_vars_if_possible(term);
511        let arg_data = self
512            .extract_inference_diagnostics_data(term, ty::print::RegionHighlightMode::default());
513
514        let Some(typeck_results) = &self.typeck_results else {
515            // If we don't have any typeck results we're outside
516            // of a body, so we won't be able to get better info
517            // here.
518            return self.bad_inference_failure_err(failure_span, arg_data, error_code);
519        };
520
521        let mut local_visitor = FindInferSourceVisitor::new(self, typeck_results, term, ty);
522        if let Some(body) =
523            self.tcx.hir_maybe_body_owned_by(self.tcx.typeck_root_def_id_local(body_def_id))
524        {
525            let expr = body.value;
526            local_visitor.visit_expr(expr);
527        }
528
529        let Some(InferSource { span, kind }) = local_visitor.infer_source else {
530            let silence = if let DefKind::AssocFn = self.tcx.def_kind(body_def_id)
531                && let parent = self.tcx.local_parent(body_def_id)
532                && self.tcx.is_automatically_derived(parent.to_def_id())
533                && let hir::Node::Item(item) = self.tcx.hir_node_by_def_id(parent)
534                && let hir::ItemKind::Impl(imp) = item.kind
535                && let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = imp.self_ty.kind
536                && let Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, def_id) = path.res
537                && let Some(def_id) = def_id.as_local()
538                && let hir::Node::Item(item) = self.tcx.hir_node_by_def_id(def_id)
539            {
540                // We have encountered an inference error within an automatically derived `impl`,
541                // from a `#[derive(..)]` on an item that had a parse error. Because the parse
542                // error might have caused the expanded code to be malformed, we silence the
543                // inference error.
544                item.kind.recovered()
545            } else {
546                false
547            };
548            let mut err = self.bad_inference_failure_err(failure_span, arg_data, error_code);
549            if silence {
550                err.downgrade_to_delayed_bug();
551            }
552            return err;
553        };
554
555        let (source_kind, name, long_ty_path) = kind.ty_localized_msg(self);
556        let failure_span = if should_label_span && !failure_span.overlaps(span) {
557            Some(failure_span)
558        } else {
559            None
560        };
561
562        let subdiagnostic = kind.suggestion(
563            self.tcx,
564            self.infcx,
565            body_def_id,
566            term,
567            &arg_data,
568            typeck_results,
569            span,
570        );
571
572        let mut err = match error_code {
573            TypeAnnotationNeeded::E0282 => self.dcx().create_err(AnnotationRequired {
574                span,
575                source_kind,
576                source_name: &name,
577                failure_span,
578                subdiagnostic,
579                bad_label: None,
580            }),
581            TypeAnnotationNeeded::E0283 => self.dcx().create_err(AmbiguousImpl {
582                span,
583                source_kind,
584                source_name: &name,
585                failure_span,
586                subdiagnostic,
587                bad_label: None,
588            }),
589            TypeAnnotationNeeded::E0284 => self.dcx().create_err(AmbiguousReturn {
590                span,
591                source_kind,
592                source_name: &name,
593                failure_span,
594                subdiagnostic,
595                bad_label: None,
596            }),
597        };
598        *err.long_ty_path() = long_ty_path;
599        if let InferSourceKind::ClosureArg { kind: PatKind::Err(_), .. } = kind {
600            // We will have already emitted an error about this pattern.
601            err.downgrade_to_delayed_bug();
602        }
603        err
604    }
605}
606
607#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InferSource<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "InferSource",
            "span", &self.span, "kind", &&self.kind)
    }
}Debug)]
608struct InferSource<'tcx> {
609    span: Span,
610    kind: InferSourceKind<'tcx>,
611}
612
613#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InferSourceKind<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            InferSourceKind::LetBinding {
                insert_span: __self_0,
                pattern_name: __self_1,
                ty: __self_2,
                def_id: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "LetBinding", "insert_span", __self_0, "pattern_name",
                    __self_1, "ty", __self_2, "def_id", &__self_3),
            InferSourceKind::ClosureArg {
                insert_span: __self_0, ty: __self_1, kind: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "ClosureArg", "insert_span", __self_0, "ty", __self_1,
                    "kind", &__self_2),
            InferSourceKind::GenericArg {
                insert_span: __self_0,
                argument_index: __self_1,
                generics_def_id: __self_2,
                def_id: __self_3,
                generic_args: __self_4,
                have_turbofish: __self_5,
                hir_id: __self_6 } => {
                let names: &'static _ =
                    &["insert_span", "argument_index", "generics_def_id",
                                "def_id", "generic_args", "have_turbofish", "hir_id"];
                let values: &[&dyn ::core::fmt::Debug] =
                    &[__self_0, __self_1, __self_2, __self_3, __self_4,
                                __self_5, &__self_6];
                ::core::fmt::Formatter::debug_struct_fields_finish(f,
                    "GenericArg", names, values)
            }
            InferSourceKind::FullyQualifiedMethodCall {
                receiver: __self_0,
                successor: __self_1,
                args: __self_2,
                def_id: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "FullyQualifiedMethodCall", "receiver", __self_0,
                    "successor", __self_1, "args", __self_2, "def_id",
                    &__self_3),
            InferSourceKind::ClosureReturn {
                ty: __self_0, data: __self_1, should_wrap_expr: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "ClosureReturn", "ty", __self_0, "data", __self_1,
                    "should_wrap_expr", &__self_2),
        }
    }
}Debug)]
614enum InferSourceKind<'tcx> {
615    LetBinding {
616        insert_span: Span,
617        pattern_name: Option<Ident>,
618        ty: Ty<'tcx>,
619        def_id: Option<DefId>,
620    },
621    ClosureArg {
622        insert_span: Span,
623        ty: Ty<'tcx>,
624        kind: PatKind<'tcx>,
625    },
626    GenericArg {
627        insert_span: Span,
628        argument_index: usize,
629        generics_def_id: DefId,
630        def_id: DefId,
631        generic_args: &'tcx [GenericArg<'tcx>],
632        have_turbofish: bool,
633        hir_id: HirId,
634    },
635    FullyQualifiedMethodCall {
636        receiver: &'tcx Expr<'tcx>,
637        /// If the method has other arguments, this is ", " and the start of the first argument,
638        /// while for methods without arguments this is ")" and the end of the method call.
639        successor: (&'static str, BytePos),
640        args: GenericArgsRef<'tcx>,
641        def_id: DefId,
642    },
643    ClosureReturn {
644        ty: Ty<'tcx>,
645        data: &'tcx FnRetTy<'tcx>,
646        should_wrap_expr: Option<Span>,
647    },
648}
649
650impl<'tcx> InferSource<'tcx> {
651    fn from_expansion(&self) -> bool {
652        let source_from_expansion = match self.kind {
653            InferSourceKind::LetBinding { insert_span, .. }
654            | InferSourceKind::ClosureArg { insert_span, .. }
655            | InferSourceKind::GenericArg { insert_span, .. } => insert_span.from_expansion(),
656            InferSourceKind::FullyQualifiedMethodCall { receiver, .. } => {
657                receiver.span.from_expansion()
658            }
659            InferSourceKind::ClosureReturn { data, should_wrap_expr, .. } => {
660                data.span().from_expansion() || should_wrap_expr.is_some_and(Span::from_expansion)
661            }
662        };
663        source_from_expansion || self.span.from_expansion()
664    }
665}
666
667impl<'tcx> InferSourceKind<'tcx> {
668    fn ty_localized_msg(&self, infcx: &InferCtxt<'tcx>) -> (&'static str, String, Option<PathBuf>) {
669        let mut long_ty_path = None;
670        match *self {
671            InferSourceKind::LetBinding { ty, .. }
672            | InferSourceKind::ClosureArg { ty, .. }
673            | InferSourceKind::ClosureReturn { ty, .. } => {
674                if ty.is_closure() {
675                    ("closure", closure_as_fn_str(infcx, ty), long_ty_path)
676                } else if ty.is_ty_or_numeric_infer()
677                    || ty.is_primitive()
678                    || #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Adt(_, args) if
        args.types().count() == 0 && args.consts().count() == 0 => true,
    _ => false,
}matches!(
679                        ty.kind(),
680                        ty::Adt(_, args)
681                        if args.types().count() == 0 && args.consts().count() == 0
682                    )
683                {
684                    // `ty` is either `_`, a primitive type like `u32` or a type with no type or
685                    // const parameters. We will not mention the type in the main inference error
686                    // message.
687                    ("other", String::new(), long_ty_path)
688                } else {
689                    ("normal", infcx.tcx.short_string(ty, &mut long_ty_path), long_ty_path)
690                }
691            }
692            // FIXME: We should be able to add some additional info here.
693            InferSourceKind::GenericArg { .. }
694            | InferSourceKind::FullyQualifiedMethodCall { .. } => {
695                ("other", String::new(), long_ty_path)
696            }
697        }
698    }
699
700    fn suggestion<'local>(
701        &self,
702        tcx: TyCtxt<'tcx>,
703        infcx: &InferCtxt<'tcx>,
704        body_def_id: LocalDefId,
705        term: Term<'tcx>,
706        arg_data: &'local InferenceDiagnosticsData,
707        typeck_results: &TypeckResults<'tcx>,
708        span: Span,
709    ) -> Option<SourceKindSubdiag<'local>>
710    where
711        'tcx: 'local,
712    {
713        let subdiag = match *self {
714            InferSourceKind::LetBinding { insert_span, pattern_name, ty, def_id } => {
715                SourceKindSubdiag::LetLike {
716                    span: insert_span,
717                    name: pattern_name.map(|name| name.to_string()).unwrap_or_else(String::new),
718                    x_kind: arg_data.where_x_is_kind(infcx, ty),
719                    prefix_kind: arg_data.kind.clone(),
720                    prefix: arg_data.kind.try_get_prefix().unwrap_or_default(),
721                    arg_name: &arg_data.name,
722                    kind: if pattern_name.is_some() { "with_pattern" } else { "other" },
723                    type_name: ty_to_string(infcx, ty, def_id),
724                }
725            }
726            InferSourceKind::ClosureArg { insert_span, ty, .. } => SourceKindSubdiag::LetLike {
727                span: insert_span,
728                name: String::new(),
729                x_kind: arg_data.where_x_is_kind(infcx, ty),
730                prefix_kind: arg_data.kind.clone(),
731                prefix: arg_data.kind.try_get_prefix().unwrap_or_default(),
732                arg_name: &arg_data.name,
733                kind: "closure",
734                type_name: ty_to_string(infcx, ty, None),
735            },
736            InferSourceKind::GenericArg {
737                insert_span,
738                argument_index,
739                generics_def_id,
740                def_id: _,
741                generic_args,
742                have_turbofish,
743                hir_id,
744            } => {
745                let generics = tcx.generics_of(generics_def_id);
746                let is_type = term.as_type().is_some();
747
748                let (parent_exists, parent_prefix, parent_name) =
749                    InferenceDiagnosticsParentData::for_parent_def_id(tcx, generics_def_id)
750                        .map_or((false, String::new(), String::new()), |parent| {
751                            (true, parent.prefix.to_string(), parent.name)
752                        });
753
754                let param = &generics.own_params[argument_index];
755                let param_name = param.name.to_string();
756
757                let mut used_fallback = false;
758                let args = if tcx.get_diagnostic_item(sym::iterator_collect_fn)
759                    == Some(generics_def_id)
760                {
761                    if let hir::Node::Expr(expr) = tcx.parent_hir_node(hir_id)
762                        && let hir::ExprKind::Call(expr, _args) = expr.kind
763                        && let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind
764                        && let Res::Def(DefKind::AssocFn, def_id) = path.res
765                        && let Some(try_trait) = tcx.lang_items().try_trait()
766                        && try_trait == tcx.parent(def_id)
767                        && let DefKind::Fn | DefKind::AssocFn =
768                            tcx.def_kind(body_def_id.to_def_id())
769                        && let ret = tcx
770                            .fn_sig(body_def_id.to_def_id())
771                            .instantiate_identity()
772                            .skip_binder()
773                            .output()
774                        && let ty::Adt(adt, _args) = ret.kind()
775                        && let Some(sym::Option | sym::Result) = tcx.get_diagnostic_name(adt.did())
776                    {
777                        if let Some(sym::Option) = tcx.get_diagnostic_name(adt.did()) {
778                            "Option<_>".to_string()
779                        } else {
780                            "Result<_, _>".to_string()
781                        }
782                    } else {
783                        "Vec<_>".to_string()
784                    }
785                } else {
786                    let mut p = fmt_printer(infcx, Namespace::TypeNS);
787                    p.comma_sep(generic_args.iter().copied().map(|arg| {
788                        if arg.is_suggestable(tcx, true) {
789                            used_fallback = true;
790                            return arg;
791                        }
792                        match arg.kind() {
793                            GenericArgKind::Lifetime(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected lifetime"))bug!("unexpected lifetime"),
794                            GenericArgKind::Type(_) => infcx.next_ty_var(DUMMY_SP).into(),
795                            GenericArgKind::Const(_) => infcx.next_const_var(DUMMY_SP).into(),
796                        }
797                    }))
798                    .unwrap();
799                    p.into_buffer()
800                };
801
802                let suggestion = if have_turbofish {
803                    None
804                } else if generic_args.len() == 1 && used_fallback {
805                    match param.kind {
806                        GenericParamDefKind::Type { .. } => {
807                            Some(SpecifyGenericParamsSuggestion::GenericTypeSuggestion {
808                                span: insert_span,
809                                param: param_name.clone(),
810                            })
811                        }
812                        GenericParamDefKind::Const { .. } => {
813                            Some(SpecifyGenericParamsSuggestion::ConstGenericSuggestion {
814                                span: insert_span,
815                                param: param_name.clone(),
816                            })
817                        }
818                        GenericParamDefKind::Lifetime => {
819                            ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected lifetime"))bug!("unexpected lifetime")
820                        }
821                    }
822                } else {
823                    Some(SpecifyGenericParamsSuggestion::GenericSuggestion {
824                        span: insert_span,
825                        arg_count: generic_args.len(),
826                        args,
827                    })
828                };
829
830                SourceKindSubdiag::Generic {
831                    span,
832                    is_type,
833                    param_name,
834                    parent_exists,
835                    parent_prefix,
836                    parent_name,
837                    suggestion,
838                }
839            }
840            InferSourceKind::FullyQualifiedMethodCall { receiver, successor, args, def_id } => {
841                let placeholder = Some(infcx.next_ty_var(DUMMY_SP));
842                let args = args.make_suggestable(tcx, true, placeholder)?;
843
844                let mut p = fmt_printer(infcx, Namespace::ValueNS);
845                p.print_def_path(def_id, args).unwrap();
846                let def_path = p.into_buffer();
847
848                // We only care about whether we have to add `&` or `&mut ` for now.
849                // This is the case if the last adjustment is a borrow and the
850                // first adjustment was not a builtin deref.
851                let adjustment = match typeck_results.expr_adjustments(receiver) {
852                    [
853                        Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: _ },
854                        ..,
855                        Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), target: _ },
856                    ] => "",
857                    [.., Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mut_)), target: _ }] => {
858                        hir::Mutability::from(*mut_).ref_prefix_str()
859                    }
860                    _ => "",
861                };
862
863                SourceKindSubdiag::new_fully_qualified(
864                    receiver.span,
865                    def_path,
866                    adjustment,
867                    successor,
868                )
869            }
870            InferSourceKind::ClosureReturn { ty, data, should_wrap_expr } => {
871                let placeholder = Some(infcx.next_ty_var(DUMMY_SP));
872
873                let ty = ty.make_suggestable(tcx, true, placeholder)?;
874                let ty_info = ty_to_string(infcx, ty, None);
875                SourceKindSubdiag::new_closure_return(ty_info, data, should_wrap_expr)
876            }
877        };
878
879        Some(subdiag)
880    }
881}
882
883#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InsertableGenericArgs<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "InsertableGenericArgs", "insert_span", &self.insert_span, "args",
            &self.args, "generics_def_id", &self.generics_def_id, "def_id",
            &self.def_id, "have_turbofish", &&self.have_turbofish)
    }
}Debug)]
884struct InsertableGenericArgs<'tcx> {
885    insert_span: Span,
886    args: GenericArgsRef<'tcx>,
887    generics_def_id: DefId,
888    def_id: DefId,
889    have_turbofish: bool,
890}
891
892/// A visitor which searches for the "best" spot to use in the inference error.
893///
894/// For this it walks over the hir body and tries to check all places where
895/// inference variables could be bound.
896///
897/// While doing so, the currently best spot is stored in `infer_source`.
898/// For details on how we rank spots, see [Self::source_cost]
899struct FindInferSourceVisitor<'a, 'tcx> {
900    tecx: &'a TypeErrCtxt<'a, 'tcx>,
901    typeck_results: &'a TypeckResults<'tcx>,
902
903    target: Term<'tcx>,
904    ty: Option<Ty<'tcx>>,
905
906    attempt: usize,
907    infer_source_cost: usize,
908    infer_source: Option<InferSource<'tcx>>,
909}
910
911impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> {
912    fn new(
913        tecx: &'a TypeErrCtxt<'a, 'tcx>,
914        typeck_results: &'a TypeckResults<'tcx>,
915        target: Term<'tcx>,
916        ty: Option<Ty<'tcx>>,
917    ) -> Self {
918        FindInferSourceVisitor {
919            tecx,
920            typeck_results,
921
922            target,
923            ty,
924
925            attempt: 0,
926            infer_source_cost: usize::MAX,
927            infer_source: None,
928        }
929    }
930
931    /// Computes cost for the given source.
932    ///
933    /// Sources with a small cost are prefer and should result
934    /// in a clearer and idiomatic suggestion.
935    fn source_cost(&self, source: &InferSource<'tcx>) -> usize {
936        #[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for CostCtxt<'tcx> {
    #[inline]
    fn clone(&self) -> CostCtxt<'tcx> {
        let _: ::core::clone::AssertParamIsClone<TyCtxt<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for CostCtxt<'tcx> { }Copy)]
937        struct CostCtxt<'tcx> {
938            tcx: TyCtxt<'tcx>,
939        }
940        impl<'tcx> CostCtxt<'tcx> {
941            fn arg_cost(self, arg: GenericArg<'tcx>) -> usize {
942                match arg.kind() {
943                    GenericArgKind::Lifetime(_) => 0, // erased
944                    GenericArgKind::Type(ty) => self.ty_cost(ty),
945                    GenericArgKind::Const(_) => 3, // some non-zero value
946                }
947            }
948            fn ty_cost(self, ty: Ty<'tcx>) -> usize {
949                match *ty.kind() {
950                    ty::Closure(..) => 1000,
951                    ty::FnDef(..) => 150,
952                    ty::FnPtr(..) => 30,
953                    ty::Adt(def, args) => {
954                        5 + self
955                            .tcx
956                            .generics_of(def.did())
957                            .own_args_no_defaults(self.tcx, args)
958                            .iter()
959                            .map(|&arg| self.arg_cost(arg))
960                            .sum::<usize>()
961                    }
962                    ty::Tuple(args) => 5 + args.iter().map(|arg| self.ty_cost(arg)).sum::<usize>(),
963                    ty::Ref(_, ty, _) => 2 + self.ty_cost(ty),
964                    ty::Infer(..) => 0,
965                    _ => 1,
966                }
967            }
968        }
969
970        // The sources are listed in order of preference here.
971        let tcx = self.tecx.tcx;
972        let ctx = CostCtxt { tcx };
973        match source.kind {
974            InferSourceKind::LetBinding { ty, .. } => ctx.ty_cost(ty),
975            InferSourceKind::ClosureArg { ty, .. } => ctx.ty_cost(ty),
976            InferSourceKind::GenericArg { def_id, generic_args, .. } => {
977                let variant_cost = match tcx.def_kind(def_id) {
978                    // `None::<u32>` and friends are ugly.
979                    DefKind::Variant | DefKind::Ctor(CtorOf::Variant, _) => 15,
980                    _ => 10,
981                };
982                variant_cost + generic_args.iter().map(|&arg| ctx.arg_cost(arg)).sum::<usize>()
983            }
984            InferSourceKind::FullyQualifiedMethodCall { args, .. } => {
985                20 + args.iter().map(|arg| ctx.arg_cost(arg)).sum::<usize>()
986            }
987            InferSourceKind::ClosureReturn { ty, should_wrap_expr, .. } => {
988                30 + ctx.ty_cost(ty) + if should_wrap_expr.is_some() { 10 } else { 0 }
989            }
990        }
991    }
992
993    /// Uses `fn source_cost` to determine whether this inference source is preferable to
994    /// previous sources. We generally prefer earlier sources.
995    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("update_infer_source",
                                    "rustc_trait_selection::error_reporting::infer::need_type_info",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs"),
                                    ::tracing_core::__macro_support::Option::Some(995u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("new_source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("new_source");
                                                        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::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::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(&new_source)
                                                            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 new_source.from_expansion() { return; }
            let cost = self.source_cost(&new_source) + self.attempt;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs:1002",
                                    "rustc_trait_selection::error_reporting::infer::need_type_info",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1002u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cost")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cost");
                                                        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(&cost)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            self.attempt += 1;
            if let Some(InferSource {
                            kind: InferSourceKind::GenericArg { def_id: did, .. }, .. })
                            = self.infer_source &&
                        let InferSourceKind::LetBinding { ref ty, ref mut def_id, ..
                            } = new_source.kind && ty.is_ty_or_numeric_infer() {
                *def_id = Some(did);
            }
            if cost < self.infer_source_cost {
                self.infer_source_cost = cost;
                self.infer_source = Some(new_source);
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
996    fn update_infer_source(&mut self, mut new_source: InferSource<'tcx>) {
997        if new_source.from_expansion() {
998            return;
999        }
1000
1001        let cost = self.source_cost(&new_source) + self.attempt;
1002        debug!(?cost);
1003        self.attempt += 1;
1004        if let Some(InferSource { kind: InferSourceKind::GenericArg { def_id: did, .. }, .. }) =
1005            self.infer_source
1006            && let InferSourceKind::LetBinding { ref ty, ref mut def_id, .. } = new_source.kind
1007            && ty.is_ty_or_numeric_infer()
1008        {
1009            // Customize the output so we talk about `let x: Vec<_> = iter.collect();` instead of
1010            // `let x: _ = iter.collect();`, as this is a very common case.
1011            *def_id = Some(did);
1012        }
1013
1014        if cost < self.infer_source_cost {
1015            self.infer_source_cost = cost;
1016            self.infer_source = Some(new_source);
1017        }
1018    }
1019
1020    fn node_args_opt(&self, hir_id: HirId) -> Option<GenericArgsRef<'tcx>> {
1021        let args = self.typeck_results.node_args_opt(hir_id);
1022        self.tecx.resolve_vars_if_possible(args)
1023    }
1024
1025    fn opt_node_type(&self, hir_id: HirId) -> Option<Ty<'tcx>> {
1026        let ty = self.typeck_results.node_type_opt(hir_id);
1027        self.tecx.resolve_vars_if_possible(ty)
1028    }
1029
1030    // Check whether this generic argument is the inference variable we
1031    // are looking for.
1032    fn generic_arg_is_target(&self, arg: GenericArg<'tcx>) -> bool {
1033        if arg == self.target.into() {
1034            return true;
1035        }
1036
1037        match (arg.kind(), self.target.kind()) {
1038            (GenericArgKind::Type(inner_ty), TermKind::Ty(target_ty)) => {
1039                use ty::{Infer, TyVar};
1040                match (inner_ty.kind(), target_ty.kind()) {
1041                    (&Infer(TyVar(a_vid)), &Infer(TyVar(b_vid))) => {
1042                        self.tecx.sub_unification_table_root_var(a_vid)
1043                            == self.tecx.sub_unification_table_root_var(b_vid)
1044                    }
1045                    _ => false,
1046                }
1047            }
1048            (GenericArgKind::Const(inner_ct), TermKind::Const(target_ct)) => {
1049                match (inner_ct.kind(), target_ct.kind()) {
1050                    (
1051                        ty::ConstKind::Infer(ty::InferConst::Var(a_vid)),
1052                        ty::ConstKind::Infer(ty::InferConst::Var(b_vid)),
1053                    ) => self.tecx.root_const_var(a_vid) == self.tecx.root_const_var(b_vid),
1054                    _ => false,
1055                }
1056            }
1057            _ => false,
1058        }
1059    }
1060
1061    /// Does this generic argument contain our target inference variable
1062    /// in a way which can be written by the user.
1063    fn generic_arg_contains_target(&self, arg: GenericArg<'tcx>) -> bool {
1064        let mut walker = arg.walk();
1065        while let Some(inner) = walker.next() {
1066            if self.generic_arg_is_target(inner) {
1067                return true;
1068            }
1069            match inner.kind() {
1070                GenericArgKind::Lifetime(_) => {}
1071                GenericArgKind::Type(ty) => {
1072                    if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) |
        ty::Closure(..) | ty::CoroutineClosure(..) | ty::Coroutine(..) =>
        true,
    _ => false,
}matches!(
1073                        ty.kind(),
1074                        ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. })
1075                            | ty::Closure(..)
1076                            | ty::CoroutineClosure(..)
1077                            | ty::Coroutine(..)
1078                    ) {
1079                        // Opaque types can't be named by the user right now.
1080                        //
1081                        // Both the generic arguments of closures and coroutines can
1082                        // also not be named. We may want to only look into the closure
1083                        // signature in case it has no captures, as that can be represented
1084                        // using `fn(T) -> R`.
1085
1086                        // FIXME(type_alias_impl_trait): These opaque types
1087                        // can actually be named, so it would make sense to
1088                        // adjust this case and add a test for it.
1089                        walker.skip_current_subtree();
1090                    }
1091                }
1092                GenericArgKind::Const(ct) => {
1093                    if #[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
    ty::ConstKind::Alias(..) => true,
    _ => false,
}matches!(ct.kind(), ty::ConstKind::Alias(..)) {
1094                        // You can't write the generic arguments for
1095                        // alias constants.
1096                        walker.skip_current_subtree();
1097                    }
1098                }
1099            }
1100        }
1101        false
1102    }
1103
1104    fn expr_inferred_arg_iter(
1105        &self,
1106        expr: &'tcx hir::Expr<'tcx>,
1107    ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
1108        let tcx = self.tecx.tcx;
1109        match expr.kind {
1110            hir::ExprKind::Path(ref path) => {
1111                if let Some(args) = self.node_args_opt(expr.hir_id) {
1112                    return self.path_inferred_arg_iter(expr.hir_id, args, path);
1113                }
1114            }
1115            // FIXME(#98711): Ideally we would also deal with type relative
1116            // paths here, even if that is quite rare.
1117            //
1118            // See the `need_type_info/expr-struct-type-relative-gat.rs` test
1119            // for an example where that would be needed.
1120            //
1121            // However, the `type_dependent_def_id` for `Self::Output` in an
1122            // impl is currently the `DefId` of `Output` in the trait definition
1123            // which makes this somewhat difficult and prevents us from just
1124            // using `self.path_inferred_arg_iter` here.
1125            hir::ExprKind::Struct(&hir::QPath::Resolved(_self_ty, path), _, _)
1126            // FIXME(TaKO8Ki): Ideally we should support other kinds,
1127            // such as `TyAlias` or `AssocTy`. For that we have to map
1128            // back from the self type to the type alias though. That's difficult.
1129            //
1130            // See the `need_type_info/issue-103053.rs` test for
1131            // a example.
1132            if #[allow(non_exhaustive_omitted_patterns)] match path.res {
    Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => true,
    _ => false,
}matches!(path.res, Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) => {
1133                if let Some(ty) = self.opt_node_type(expr.hir_id)
1134                    && let ty::Adt(_, args) = ty.kind()
1135                {
1136                    return Box::new(self.resolved_path_inferred_arg_iter(path, args));
1137                }
1138            }
1139            hir::ExprKind::MethodCall(segment, ..) => {
1140                if let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) {
1141                    let generics = tcx.generics_of(def_id);
1142                    let insertable = try {
1143                        if generics.has_impl_trait() {
1144                            None?
1145                        }
1146                        let args = self.node_args_opt(expr.hir_id)?;
1147                        let span = tcx.hir_span(segment.hir_id);
1148                        let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1149                        let have_turbofish = segment.args.is_some_and(|args| {
1150                            args.args.iter().any(|arg| arg.is_ty_or_const())
1151                        });
1152                        InsertableGenericArgs {
1153                            insert_span,
1154                            args,
1155                            generics_def_id: def_id,
1156                            def_id,
1157                            have_turbofish,
1158                        }
1159                    };
1160                    return Box::new(insertable.into_iter());
1161                }
1162            }
1163            _ => {}
1164        }
1165
1166        Box::new(iter::empty())
1167    }
1168
1169    fn resolved_path_inferred_arg_iter(
1170        &self,
1171        path: &'tcx hir::Path<'tcx>,
1172        args: GenericArgsRef<'tcx>,
1173    ) -> impl Iterator<Item = InsertableGenericArgs<'tcx>> + 'tcx {
1174        let tcx = self.tecx.tcx;
1175        let have_turbofish = path.segments.iter().any(|segment| {
1176            segment.args.is_some_and(|args| args.args.iter().any(|arg| arg.is_ty_or_const()))
1177        });
1178        // The last segment of a path often has `Res::Err` and the
1179        // correct `Res` is the one of the whole path.
1180        //
1181        // FIXME: We deal with that one separately for now,
1182        // would be good to remove this special case.
1183        let last_segment_using_path_data = try {
1184            let generics_def_id = tcx.res_generics_def_id(path.res)?;
1185            let generics = tcx.generics_of(generics_def_id);
1186            if generics.has_impl_trait() {
1187                do yeet ();
1188            }
1189            let insert_span =
1190                path.segments.last().unwrap().ident.span.shrink_to_hi().with_hi(path.span.hi());
1191            InsertableGenericArgs {
1192                insert_span,
1193                args,
1194                generics_def_id,
1195                def_id: path.res.def_id(),
1196                have_turbofish,
1197            }
1198        };
1199
1200        path.segments
1201            .iter()
1202            .filter_map(move |segment| {
1203                let res = segment.res;
1204                let generics_def_id = tcx.res_generics_def_id(res)?;
1205                let generics = tcx.generics_of(generics_def_id);
1206                if generics.has_impl_trait() {
1207                    return None;
1208                }
1209                let span = tcx.hir_span(segment.hir_id);
1210                let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1211                Some(InsertableGenericArgs {
1212                    insert_span,
1213                    args,
1214                    generics_def_id,
1215                    def_id: res.def_id(),
1216                    have_turbofish,
1217                })
1218            })
1219            .chain(last_segment_using_path_data)
1220    }
1221
1222    fn path_inferred_arg_iter(
1223        &self,
1224        hir_id: HirId,
1225        args: GenericArgsRef<'tcx>,
1226        qpath: &'tcx hir::QPath<'tcx>,
1227    ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
1228        let tcx = self.tecx.tcx;
1229        match qpath {
1230            hir::QPath::Resolved(_self_ty, path) => {
1231                Box::new(self.resolved_path_inferred_arg_iter(path, args))
1232            }
1233            hir::QPath::TypeRelative(ty, segment) => {
1234                let Some(def_id) = self.typeck_results.type_dependent_def_id(hir_id) else {
1235                    return Box::new(iter::empty());
1236                };
1237
1238                let generics = tcx.generics_of(def_id);
1239                let segment = if !segment.infer_args || generics.has_impl_trait() {
1240                    None
1241                } else {
1242                    let span = tcx.hir_span(segment.hir_id);
1243                    let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1244                    Some(InsertableGenericArgs {
1245                        insert_span,
1246                        args,
1247                        generics_def_id: def_id,
1248                        def_id,
1249                        have_turbofish: false,
1250                    })
1251                };
1252
1253                let parent_def_id = generics.parent.unwrap();
1254                if let DefKind::Impl { .. } = tcx.def_kind(parent_def_id) {
1255                    let parent_ty =
1256                        tcx.type_of(parent_def_id).instantiate(tcx, args).skip_norm_wip();
1257                    match (parent_ty.kind(), &ty.kind) {
1258                        (
1259                            ty::Adt(def, args),
1260                            hir::TyKind::Path(hir::QPath::Resolved(_self_ty, path)),
1261                        ) => {
1262                            if tcx.res_generics_def_id(path.res) != Some(def.did()) {
1263                                match path.res {
1264                                    Res::Def(DefKind::TyAlias, _) => {
1265                                        // FIXME: Ideally we should support this. For that
1266                                        // we have to map back from the self type to the
1267                                        // type alias though. That's difficult.
1268                                        //
1269                                        // See the `need_type_info/type-alias.rs` test for
1270                                        // some examples.
1271                                    }
1272                                    // There cannot be inference variables in the self type,
1273                                    // so there's nothing for us to do here.
1274                                    Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {}
1275                                    _ => {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs:1275",
                        "rustc_trait_selection::error_reporting::infer::need_type_info",
                        ::tracing::Level::WARN,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs"),
                        ::tracing_core::__macro_support::Option::Some(1275u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::WARN <=
                    ::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!("unexpected path: def={0:?} args={1:?} path={2:?}",
                                                    def, args, path) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
}warn!(
1276                                        "unexpected path: def={:?} args={:?} path={:?}",
1277                                        def, args, path,
1278                                    ),
1279                                }
1280                            } else {
1281                                return Box::new(
1282                                    self.resolved_path_inferred_arg_iter(path, args).chain(segment),
1283                                );
1284                            }
1285                        }
1286                        _ => (),
1287                    }
1288                }
1289
1290                Box::new(segment.into_iter())
1291            }
1292        }
1293    }
1294}
1295
1296impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> {
1297    type NestedFilter = nested_filter::OnlyBodies;
1298
1299    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1300        self.tecx.tcx
1301    }
1302
1303    fn visit_local(&mut self, local: &'tcx LetStmt<'tcx>) {
1304        intravisit::walk_local(self, local);
1305
1306        if let Some(mut ty) = self.opt_node_type(local.hir_id) {
1307            if self.generic_arg_contains_target(ty.into()) {
1308                fn get_did(
1309                    typeck_results: &TypeckResults<'_>,
1310                    expr: &hir::Expr<'_>,
1311                ) -> Option<DefId> {
1312                    match expr.kind {
1313                        hir::ExprKind::Match(expr, _, hir::MatchSource::TryDesugar(_))
1314                            if let hir::ExprKind::Call(_, [expr]) = expr.kind =>
1315                        {
1316                            get_did(typeck_results, expr)
1317                        }
1318                        hir::ExprKind::Call(base, _args)
1319                            if let hir::ExprKind::Path(path) = base.kind
1320                                && let hir::QPath::Resolved(_, path) = path
1321                                && let Res::Def(_, did) = path.res =>
1322                        {
1323                            Some(did)
1324                        }
1325                        hir::ExprKind::MethodCall(..)
1326                            if let Some(did) =
1327                                typeck_results.type_dependent_def_id(expr.hir_id) =>
1328                        {
1329                            Some(did)
1330                        }
1331                        _ => None,
1332                    }
1333                }
1334                if let Some(t) = self.ty
1335                    && ty.has_infer()
1336                {
1337                    ty = t;
1338                }
1339                if let LocalSource::Normal = local.source
1340                    && local.ty.is_none()
1341                {
1342                    self.update_infer_source(InferSource {
1343                        span: local.pat.span,
1344                        kind: InferSourceKind::LetBinding {
1345                            insert_span: local.pat.span.shrink_to_hi(),
1346                            pattern_name: local.pat.simple_ident(),
1347                            ty,
1348                            def_id: local.init.and_then(|expr| get_did(self.typeck_results, expr)),
1349                        },
1350                    });
1351                }
1352            }
1353        }
1354    }
1355
1356    /// For closures, we first visit the parameters and then the content,
1357    /// as we prefer those.
1358    fn visit_body(&mut self, body: &Body<'tcx>) {
1359        for param in body.params {
1360            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs:1360",
                        "rustc_trait_selection::error_reporting::infer::need_type_info",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs"),
                        ::tracing_core::__macro_support::Option::Some(1360u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                        ::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!("param: span {0:?}, ty_span {1:?}, pat.span {2:?}",
                                                    param.span, param.ty_span, param.pat.span) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1361                "param: span {:?}, ty_span {:?}, pat.span {:?}",
1362                param.span, param.ty_span, param.pat.span
1363            );
1364            if param.ty_span != param.pat.span {
1365                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs:1365",
                        "rustc_trait_selection::error_reporting::infer::need_type_info",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs"),
                        ::tracing_core::__macro_support::Option::Some(1365u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                        ::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!("skipping param: has explicit type")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("skipping param: has explicit type");
1366                continue;
1367            }
1368
1369            let Some(param_ty) = self.opt_node_type(param.hir_id) else { continue };
1370
1371            if self.generic_arg_contains_target(param_ty.into()) {
1372                self.update_infer_source(InferSource {
1373                    span: param.pat.span,
1374                    kind: InferSourceKind::ClosureArg {
1375                        insert_span: param.pat.span.shrink_to_hi(),
1376                        ty: param_ty,
1377                        kind: param.pat.kind,
1378                    },
1379                })
1380            }
1381        }
1382        intravisit::walk_body(self, body);
1383    }
1384
1385    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("visit_expr",
                                    "rustc_trait_selection::error_reporting::infer::need_type_info",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1385u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                                    ::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()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::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))])
                            })
                } 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;
        }
        {
            let tcx = self.tecx.tcx;
            match expr.kind {
                ExprKind::Call(func, args) => {
                    for arg in args { self.visit_expr(arg); }
                    self.visit_expr(func);
                }
                _ => intravisit::walk_expr(self, expr),
            }
            for args in self.expr_inferred_arg_iter(expr) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs:1401",
                                        "rustc_trait_selection::error_reporting::infer::need_type_info",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1401u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                                        ::tracing_core::field::FieldSet::new(&[{
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("args")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("args");
                                                            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(&args)
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                let InsertableGenericArgs {
                        insert_span, args, generics_def_id, def_id, have_turbofish
                        } = args;
                let generics = tcx.generics_of(generics_def_id);
                if let Some(argument_index) =
                        generics.own_args(args).iter().position(|&arg|
                                self.generic_arg_contains_target(arg)) {
                    let args = self.tecx.resolve_vars_if_possible(args);
                    let generic_args =
                        &generics.own_args_no_defaults(tcx,
                                    args)[generics.own_counts().lifetimes..];
                    let span =
                        match expr.kind {
                            ExprKind::MethodCall(segment, ..) if
                                have_turbofish && let Some(hir_args) = segment.args &&
                                        let Some(idx) =
                                            argument_index.checked_sub(generics.own_counts().lifetimes)
                                    &&
                                    let Some(arg) =
                                        hir_args.args.get(hir_args.num_lifetime_args() + idx) => {
                                arg.span()
                            }
                            ExprKind::MethodCall(segment, ..) => segment.ident.span,
                            _ => expr.span,
                        };
                    let mut argument_index = argument_index;
                    if generics.has_own_self() { argument_index += 1; }
                    self.update_infer_source(InferSource {
                            span,
                            kind: InferSourceKind::GenericArg {
                                insert_span,
                                argument_index,
                                generics_def_id,
                                def_id,
                                generic_args,
                                have_turbofish,
                                hir_id: expr.hir_id,
                            },
                        });
                }
            }
            if let Some(node_ty) = self.opt_node_type(expr.hir_id) {
                if let (&ExprKind::Closure(&Closure {
                        fn_decl, body, fn_decl_span, .. }), ty::Closure(_, args)) =
                        (&expr.kind, node_ty.kind()) {
                    let output = args.as_closure().sig().output().skip_binder();
                    if self.generic_arg_contains_target(output.into()) {
                        let body = self.tecx.tcx.hir_body(body);
                        let should_wrap_expr =
                            if #[allow(non_exhaustive_omitted_patterns)] match body.value.kind
                                    {
                                    ExprKind::Block(..) => true,
                                    _ => false,
                                } {
                                None
                            } else { Some(body.value.span.shrink_to_hi()) };
                        self.update_infer_source(InferSource {
                                span: fn_decl_span,
                                kind: InferSourceKind::ClosureReturn {
                                    ty: output,
                                    data: &fn_decl.output,
                                    should_wrap_expr,
                                },
                            })
                    }
                }
            }
            let has_impl_trait =
                |def_id|
                    {
                        iter::successors(Some(tcx.generics_of(def_id)),
                                |generics|
                                    {
                                        generics.parent.map(|def_id| tcx.generics_of(def_id))
                                    }).any(|generics| generics.has_impl_trait())
                    };
            if let ExprKind::MethodCall(path, receiver, method_args, span) =
                                            expr.kind &&
                                        let Some(args) = self.node_args_opt(expr.hir_id) &&
                                    args.iter().any(|arg| self.generic_arg_contains_target(arg))
                                &&
                                let Some(def_id) =
                                    self.typeck_results.type_dependent_def_id(expr.hir_id) &&
                            self.tecx.tcx.trait_of_assoc(def_id).is_some() &&
                        !has_impl_trait(def_id) &&
                    tcx.hir_opt_delegation_sig_id(expr.hir_id.owner.def_id).is_none()
                {
                let successor =
                    method_args.get(0).map_or_else(|| (")", span.hi()),
                        |arg| (", ", arg.span.lo()));
                let args = self.tecx.resolve_vars_if_possible(args);
                self.update_infer_source(InferSource {
                        span: path.ident.span,
                        kind: InferSourceKind::FullyQualifiedMethodCall {
                            receiver,
                            successor,
                            args,
                            def_id,
                        },
                    })
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1386    fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1387        let tcx = self.tecx.tcx;
1388        match expr.kind {
1389            // When encountering `func(arg)` first look into `arg` and then `func`,
1390            // as `arg` is "more specific".
1391            ExprKind::Call(func, args) => {
1392                for arg in args {
1393                    self.visit_expr(arg);
1394                }
1395                self.visit_expr(func);
1396            }
1397            _ => intravisit::walk_expr(self, expr),
1398        }
1399
1400        for args in self.expr_inferred_arg_iter(expr) {
1401            debug!(?args);
1402            let InsertableGenericArgs {
1403                insert_span,
1404                args,
1405                generics_def_id,
1406                def_id,
1407                have_turbofish,
1408            } = args;
1409            let generics = tcx.generics_of(generics_def_id);
1410            if let Some(argument_index) = generics
1411                .own_args(args)
1412                .iter()
1413                .position(|&arg| self.generic_arg_contains_target(arg))
1414            {
1415                let args = self.tecx.resolve_vars_if_possible(args);
1416                let generic_args =
1417                    &generics.own_args_no_defaults(tcx, args)[generics.own_counts().lifetimes..];
1418                let span = match expr.kind {
1419                    ExprKind::MethodCall(segment, ..)
1420                        if have_turbofish
1421                            && let Some(hir_args) = segment.args
1422                            && let Some(idx) =
1423                                argument_index.checked_sub(generics.own_counts().lifetimes)
1424                            && let Some(arg) =
1425                                hir_args.args.get(hir_args.num_lifetime_args() + idx) =>
1426                    {
1427                        arg.span()
1428                    }
1429                    ExprKind::MethodCall(segment, ..) => segment.ident.span,
1430                    _ => expr.span,
1431                };
1432                let mut argument_index = argument_index;
1433                if generics.has_own_self() {
1434                    argument_index += 1;
1435                }
1436
1437                self.update_infer_source(InferSource {
1438                    span,
1439                    kind: InferSourceKind::GenericArg {
1440                        insert_span,
1441                        argument_index,
1442                        generics_def_id,
1443                        def_id,
1444                        generic_args,
1445                        have_turbofish,
1446                        hir_id: expr.hir_id,
1447                    },
1448                });
1449            }
1450        }
1451
1452        if let Some(node_ty) = self.opt_node_type(expr.hir_id) {
1453            if let (
1454                &ExprKind::Closure(&Closure { fn_decl, body, fn_decl_span, .. }),
1455                ty::Closure(_, args),
1456            ) = (&expr.kind, node_ty.kind())
1457            {
1458                let output = args.as_closure().sig().output().skip_binder();
1459                if self.generic_arg_contains_target(output.into()) {
1460                    let body = self.tecx.tcx.hir_body(body);
1461                    let should_wrap_expr = if matches!(body.value.kind, ExprKind::Block(..)) {
1462                        None
1463                    } else {
1464                        Some(body.value.span.shrink_to_hi())
1465                    };
1466                    self.update_infer_source(InferSource {
1467                        span: fn_decl_span,
1468                        kind: InferSourceKind::ClosureReturn {
1469                            ty: output,
1470                            data: &fn_decl.output,
1471                            should_wrap_expr,
1472                        },
1473                    })
1474                }
1475            }
1476        }
1477
1478        let has_impl_trait = |def_id| {
1479            iter::successors(Some(tcx.generics_of(def_id)), |generics| {
1480                generics.parent.map(|def_id| tcx.generics_of(def_id))
1481            })
1482            .any(|generics| generics.has_impl_trait())
1483        };
1484        if let ExprKind::MethodCall(path, receiver, method_args, span) = expr.kind
1485            && let Some(args) = self.node_args_opt(expr.hir_id)
1486            && args.iter().any(|arg| self.generic_arg_contains_target(arg))
1487            && let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id)
1488            && self.tecx.tcx.trait_of_assoc(def_id).is_some()
1489            && !has_impl_trait(def_id)
1490            // FIXME(fn_delegation): In delegation item argument spans are equal to last path
1491            // segment. This leads to ICE's when emitting `multipart_suggestion`.
1492            && tcx.hir_opt_delegation_sig_id(expr.hir_id.owner.def_id).is_none()
1493        {
1494            let successor =
1495                method_args.get(0).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo()));
1496            let args = self.tecx.resolve_vars_if_possible(args);
1497            self.update_infer_source(InferSource {
1498                span: path.ident.span,
1499                kind: InferSourceKind::FullyQualifiedMethodCall {
1500                    receiver,
1501                    successor,
1502                    args,
1503                    def_id,
1504                },
1505            })
1506        }
1507    }
1508}