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_span::{BytePos, DUMMY_SP, Ident, Span, sym};
23use tracing::{debug, instrument, warn};
24
25use super::nice_region_error::placeholder_error::Highlighted;
26use crate::diagnostics::{
27    AmbiguousImpl, AmbiguousReturn, AnnotationRequired, InferenceBadError, SourceKindSubdiag,
28    SpecifyGenericParamsSuggestion,
29};
30use crate::error_reporting::TypeErrCtxt;
31use crate::infer::{InferCtxt, TyOrConstInferVar};
32
33pub enum TypeAnnotationNeeded {
34    /// ```compile_fail,E0282
35    /// let x;
36    /// ```
37    E0282,
38    /// An implementation cannot be chosen unambiguously because of lack of information.
39    /// ```compile_fail,E0790
40    /// let _ = Default::default();
41    /// ```
42    E0283,
43    /// ```compile_fail,E0284
44    /// let mut d: u64 = 2;
45    /// d = d % 1u32.into();
46    /// ```
47    E0284,
48}
49
50impl From<TypeAnnotationNeeded> for ErrCode {
51    fn from(val: TypeAnnotationNeeded) -> Self {
52        match val {
53            TypeAnnotationNeeded::E0282 => E0282,
54            TypeAnnotationNeeded::E0283 => E0283,
55            TypeAnnotationNeeded::E0284 => E0284,
56        }
57    }
58}
59
60/// Information about a constant or a type containing inference variables.
61pub struct InferenceDiagnosticsData {
62    pub name: String,
63    pub span: Option<Span>,
64    pub kind: UnderspecifiedArgKind,
65    pub parent: Option<InferenceDiagnosticsParentData>,
66}
67
68/// Data on the parent definition where a generic argument was declared.
69pub struct InferenceDiagnosticsParentData {
70    prefix: &'static str,
71    name: String,
72}
73
74#[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)]
75pub enum UnderspecifiedArgKind {
76    Type { prefix: Cow<'static, str> },
77    Const { is_parameter: bool },
78}
79
80impl InferenceDiagnosticsData {
81    fn can_add_more_info(&self) -> bool {
82        !(self.name == "_" && #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    UnderspecifiedArgKind::Type { .. } => true,
    _ => false,
}matches!(self.kind, UnderspecifiedArgKind::Type { .. }))
83    }
84
85    fn where_x_is_kind<'tcx>(&self, infcx: &InferCtxt<'tcx>, in_type: Ty<'tcx>) -> &'static str {
86        if in_type.is_ty_or_numeric_infer() {
87            ""
88        } else if self.name == "_" {
89            let displayed_ty = infcx
90                .resolve_vars_if_possible(in_type)
91                .fold_with(&mut ClosureEraser { infcx, depth: 0 });
92            if displayed_ty.is_ty_or_numeric_infer() {
93                ""
94            } else {
95                match displayed_ty
96                    .walk()
97                    .filter_map(TyOrConstInferVar::maybe_from_generic_arg)
98                    .take(2)
99                    .count()
100                {
101                    0 => "",
102                    1 => "underscore_single",
103                    _ => "underscore_multiple",
104                }
105            }
106        } else {
107            "has_name"
108        }
109    }
110
111    /// Generate a label for a generic argument which can't be inferred. When not
112    /// much is known about the argument, `use_diag` may be used to describe the
113    /// labeled value.
114    fn make_bad_error(&self, span: Span) -> InferenceBadError<'_> {
115        let has_parent = self.parent.is_some();
116        let bad_kind = if self.can_add_more_info() { "more_info" } else { "other" };
117        let (parent_prefix, parent_name) = self
118            .parent
119            .as_ref()
120            .map(|parent| (parent.prefix, parent.name.clone()))
121            .unwrap_or_default();
122        InferenceBadError {
123            span,
124            bad_kind,
125            prefix_kind: self.kind.clone(),
126            prefix: self.kind.try_get_prefix().unwrap_or_default(),
127            name: self.name.clone(),
128            has_parent,
129            parent_prefix,
130            parent_name,
131        }
132    }
133}
134
135impl InferenceDiagnosticsParentData {
136    fn for_parent_def_id(
137        tcx: TyCtxt<'_>,
138        parent_def_id: DefId,
139    ) -> Option<InferenceDiagnosticsParentData> {
140        let parent_name =
141            tcx.def_key(parent_def_id).disambiguated_data.data.get_opt_name()?.to_string();
142
143        Some(InferenceDiagnosticsParentData {
144            prefix: tcx.def_descr(parent_def_id),
145            name: parent_name,
146        })
147    }
148
149    fn for_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<InferenceDiagnosticsParentData> {
150        Self::for_parent_def_id(tcx, tcx.parent(def_id))
151    }
152}
153
154impl IntoDiagArg for UnderspecifiedArgKind {
155    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
156        let kind = match self {
157            Self::Type { .. } => "type",
158            Self::Const { is_parameter: true } => "const_with_param",
159            Self::Const { is_parameter: false } => "const",
160        };
161        rustc_errors::DiagArgValue::Str(kind.into())
162    }
163}
164
165impl UnderspecifiedArgKind {
166    fn try_get_prefix(&self) -> Option<&str> {
167        match self {
168            Self::Type { prefix } => Some(prefix.as_ref()),
169            Self::Const { .. } => None,
170        }
171    }
172}
173
174struct ClosureEraser<'a, 'tcx> {
175    infcx: &'a InferCtxt<'tcx>,
176    depth: usize,
177}
178
179impl<'a, 'tcx> ClosureEraser<'a, 'tcx> {
180    fn new_infer(&mut self) -> Ty<'tcx> {
181        self.infcx.next_ty_var(DUMMY_SP)
182    }
183}
184
185impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ClosureEraser<'a, 'tcx> {
186    fn cx(&self) -> TyCtxt<'tcx> {
187        self.infcx.tcx
188    }
189
190    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
191        self.depth += 1;
192        let ty = match ty.kind() {
193            ty::Closure(_, args) => {
194                // For a closure type, we turn it into a function pointer so that it gets rendered
195                // as `fn(args) -> Ret`.
196                let closure_sig = args.as_closure().sig();
197                Ty::new_fn_ptr(
198                    self.cx(),
199                    self.cx().signature_unclosure(closure_sig, hir::Safety::Safe),
200                )
201            }
202            ty::Adt(_, args) if !args.iter().any(|a| a.has_infer()) => {
203                // We have a type that doesn't have any inference variables, so we replace
204                // the whole thing with `_`. The type system already knows about this type in
205                // its entirety and it is redundant to specify it for the user. The user only
206                // needs to specify the type parameters that we *couldn't* figure out.
207                self.new_infer()
208            }
209            ty::Adt(def, args) => {
210                let generics = self.cx().generics_of(def.did());
211                let generics: Vec<bool> = generics
212                    .own_params
213                    .iter()
214                    .map(|param| param.default_value(self.cx()).is_some())
215                    .collect();
216                let ty = Ty::new_adt(
217                    self.cx(),
218                    *def,
219                    self.cx().mk_args_from_iter(generics.into_iter().zip(args.iter()).map(
220                        |(has_default, arg)| {
221                            if arg.has_infer() {
222                                // This param has an unsubstituted type variable, meaning that this
223                                // type has a (potentially deeply nested) type parameter from the
224                                // corresponding type's definition. We have explicitly asked this
225                                // type to not be hidden. In either case, we keep the type and don't
226                                // substitute with `_` just yet.
227                                arg.fold_with(self)
228                            } else if has_default {
229                                // We have a type param that has a default type, like the allocator
230                                // in Vec. We decided to show `Vec` itself, because it hasn't yet
231                                // been replaced by an `_` `Infer`, but we want to ensure that the
232                                // type parameter with default types does *not* get replaced with
233                                // `_` because then we'd end up with `Vec<_, _>`, instead of
234                                // `Vec<_>`.
235                                arg
236                            } else if let GenericArgKind::Type(_) = arg.kind() {
237                                // We don't replace lifetime or const params, only type params.
238                                self.new_infer().into()
239                            } else {
240                                arg.fold_with(self)
241                            }
242                        },
243                    )),
244                );
245                ty
246            }
247            _ if ty.has_infer() => {
248                // This type has a (potentially nested) type parameter that we couldn't figure out.
249                // We will print this depth of type, so at least the type name and at least one of
250                // its type parameters.
251                ty.super_fold_with(self)
252            }
253            // We are in the top-level type, not one of its type parameters. Name it with its
254            // parameters replaced.
255            _ if self.depth == 1 => ty.super_fold_with(self),
256            // We don't have an unknown type parameter anywhere, and we are in a type parameter.
257            // Replace with `_`.
258            _ => self.new_infer(),
259        };
260        self.depth -= 1;
261        ty
262    }
263
264    fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
265        // Avoid accidentally erasing the type of the const.
266        c
267    }
268}
269
270fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'tcx>, ns: Namespace) -> FmtPrinter<'a, 'tcx> {
271    let mut p = FmtPrinter::new(infcx.tcx, ns);
272    let ty_getter = move |ty_vid| {
273        if infcx.try_resolve_ty_var(ty_vid).is_ok() {
274            {
    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:274",
                        "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(274u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolved ty var in error message")
                                            as &dyn Value))])
            });
    } else { ; }
};warn!("resolved ty var in error message");
275        }
276
277        let var_origin = infcx.type_var_origin(ty_vid);
278        if let Some(def_id) = var_origin.param_def_id
279            // The `Self` param of a trait has the def-id of the trait,
280            // since it's a synthetic parameter.
281            && infcx.tcx.def_kind(def_id) == DefKind::TyParam
282            && let name = infcx.tcx.item_name(def_id)
283            && !var_origin.span.from_expansion()
284        {
285            let generics = infcx.tcx.generics_of(infcx.tcx.parent(def_id));
286            let idx = generics.param_def_id_to_index(infcx.tcx, def_id).unwrap();
287            let generic_param_def = generics.param_at(idx as usize, infcx.tcx);
288            if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param_def.kind {
289                None
290            } else {
291                Some(name)
292            }
293        } else {
294            None
295        }
296    };
297    p.ty_infer_name_resolver = Some(Box::new(ty_getter));
298    let const_getter =
299        move |ct_vid| Some(infcx.tcx.item_name(infcx.const_var_origin(ct_vid)?.param_def_id?));
300    p.const_infer_name_resolver = Some(Box::new(const_getter));
301    p
302}
303
304fn ty_to_string<'tcx>(
305    infcx: &InferCtxt<'tcx>,
306    ty: Ty<'tcx>,
307    called_method_def_id: Option<DefId>,
308) -> String {
309    let mut p = fmt_printer(infcx, Namespace::TypeNS);
310    let ty = infcx.resolve_vars_if_possible(ty);
311    // We use `fn` ptr syntax for closures, but this only works when the closure does not capture
312    // anything. We also remove all type parameters that are fully known to the type system.
313    let ty = ty.fold_with(&mut ClosureEraser { infcx, depth: 0 });
314
315    match (ty.kind(), called_method_def_id) {
316        // We don't want the regular output for `fn`s because it includes its path in
317        // invalid pseudo-syntax, we want the `fn`-pointer output instead.
318        (ty::FnDef(..), _) => {
319            ty.fn_sig(infcx.tcx).print(&mut p).unwrap();
320            p.into_buffer()
321        }
322        (_, Some(def_id))
323            if ty.is_ty_or_numeric_infer()
324                && infcx.tcx.get_diagnostic_item(sym::iterator_collect_fn) == Some(def_id) =>
325        {
326            "Vec<_>".to_string()
327        }
328        _ if ty.is_ty_or_numeric_infer() => "/* Type */".to_string(),
329        _ => {
330            ty.print(&mut p).unwrap();
331            p.into_buffer()
332        }
333    }
334}
335
336/// We don't want to directly use `ty_to_string` for closures as their type isn't really
337/// something users are familiar with. Directly printing the `fn_sig` of closures also
338/// doesn't work as they actually use the "rust-call" API.
339fn closure_as_fn_str<'tcx>(infcx: &InferCtxt<'tcx>, ty: Ty<'tcx>) -> String {
340    let ty::Closure(_, args) = ty.kind() else {
341        ::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`")
342    };
343    let fn_sig = args.as_closure().sig();
344    let args = fn_sig
345        .inputs()
346        .skip_binder()
347        .iter()
348        .next()
349        .map(|args| {
350            args.tuple_fields()
351                .iter()
352                .map(|arg| ty_to_string(infcx, arg, None))
353                .collect::<Vec<_>>()
354                .join(", ")
355        })
356        .unwrap_or_default();
357    let ret = if fn_sig.output().skip_binder().is_unit() {
358        String::new()
359    } else {
360        ::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))
361    };
362    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("fn({0}){1}", args, ret))
    })format!("fn({args}){ret}")
363}
364
365impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
366    /// Extracts data used by diagnostic for either types or constants
367    /// which were stuck during inference.
368    pub fn extract_inference_diagnostics_data(
369        &self,
370        term: Term<'tcx>,
371        highlight: ty::print::RegionHighlightMode<'tcx>,
372    ) -> InferenceDiagnosticsData {
373        let tcx = self.tcx;
374        match term.kind() {
375            TermKind::Ty(ty) => {
376                if let ty::Infer(ty::TyVar(ty_vid)) = *ty.kind() {
377                    let var_origin = self.infcx.type_var_origin(ty_vid);
378                    if let Some(def_id) = var_origin.param_def_id
379                        // The `Self` param of a trait has the def-id of the trait,
380                        // since it's a synthetic parameter.
381                        && self.tcx.def_kind(def_id) == DefKind::TyParam
382                        && !var_origin.span.from_expansion()
383                    {
384                        return InferenceDiagnosticsData {
385                            name: self.tcx.item_name(def_id).to_string(),
386                            span: Some(var_origin.span),
387                            kind: UnderspecifiedArgKind::Type { prefix: "type parameter".into() },
388                            parent: InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id),
389                        };
390                    }
391                }
392
393                InferenceDiagnosticsData {
394                    name: Highlighted { highlight, ns: Namespace::TypeNS, tcx, value: ty }
395                        .to_string(),
396                    span: None,
397                    kind: UnderspecifiedArgKind::Type { prefix: ty.prefix_string(self.tcx) },
398                    parent: None,
399                }
400            }
401            TermKind::Const(ct) => {
402                if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
403                    let origin = self.const_var_origin(vid).expect("expected unresolved const var");
404                    if let Some(def_id) = origin.param_def_id {
405                        return InferenceDiagnosticsData {
406                            name: self.tcx.item_name(def_id).to_string(),
407                            span: Some(origin.span),
408                            kind: UnderspecifiedArgKind::Const { is_parameter: true },
409                            parent: InferenceDiagnosticsParentData::for_def_id(self.tcx, def_id),
410                        };
411                    }
412
413                    if true {
    if !!origin.span.is_dummy() {
        ::core::panicking::panic("assertion failed: !origin.span.is_dummy()")
    };
};debug_assert!(!origin.span.is_dummy());
414                    InferenceDiagnosticsData {
415                        name: Highlighted { highlight, ns: Namespace::ValueNS, tcx, value: ct }
416                            .to_string(),
417                        span: Some(origin.span),
418                        kind: UnderspecifiedArgKind::Const { is_parameter: false },
419                        parent: None,
420                    }
421                } else {
422                    // If we end up here the `FindInferSourceVisitor`
423                    // won't work, as its expected argument isn't an inference variable.
424                    //
425                    // FIXME: Ideally we should look into the generic constant
426                    // to figure out which inference var is actually unresolved so that
427                    // this path is unreachable.
428                    InferenceDiagnosticsData {
429                        name: Highlighted { highlight, ns: Namespace::ValueNS, tcx, value: ct }
430                            .to_string(),
431                        span: None,
432                        kind: UnderspecifiedArgKind::Const { is_parameter: false },
433                        parent: None,
434                    }
435                }
436            }
437        }
438    }
439
440    /// Used as a fallback in [TypeErrCtxt::emit_inference_failure_err]
441    /// in case we weren't able to get a better error.
442    fn bad_inference_failure_err(
443        &self,
444        span: Span,
445        arg_data: InferenceDiagnosticsData,
446        error_code: TypeAnnotationNeeded,
447    ) -> Diag<'a> {
448        let source_kind = "other";
449        let source_name = "";
450        let failure_span = None;
451        let subdiagnostic = None;
452        let bad_label = Some(arg_data.make_bad_error(span));
453        match error_code {
454            TypeAnnotationNeeded::E0282 => self.dcx().create_err(AnnotationRequired {
455                span,
456                source_kind,
457                source_name,
458                failure_span,
459                subdiagnostic,
460                bad_label,
461            }),
462            TypeAnnotationNeeded::E0283 => self.dcx().create_err(AmbiguousImpl {
463                span,
464                source_kind,
465                source_name,
466                failure_span,
467                subdiagnostic,
468                bad_label,
469            }),
470            TypeAnnotationNeeded::E0284 => self.dcx().create_err(AmbiguousReturn {
471                span,
472                source_kind,
473                source_name,
474                failure_span,
475                subdiagnostic,
476                bad_label,
477            }),
478        }
479    }
480
481    #[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(481u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                                    ::tracing_core::field::FieldSet::new(&["body_def_id",
                                                    "failure_span", "term", "should_label_span"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&failure_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&term)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&should_label_span
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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))]
482    pub fn emit_inference_failure_err(
483        &self,
484        body_def_id: LocalDefId,
485        failure_span: Span,
486        term: Term<'tcx>,
487        error_code: TypeAnnotationNeeded,
488        should_label_span: bool,
489    ) -> Diag<'a> {
490        self.emit_inference_failure_err_with_type_hint(
491            body_def_id,
492            failure_span,
493            term,
494            error_code,
495            should_label_span,
496            None,
497        )
498    }
499
500    pub fn emit_inference_failure_err_with_type_hint(
501        &self,
502        body_def_id: LocalDefId,
503        failure_span: Span,
504        term: Term<'tcx>,
505        error_code: TypeAnnotationNeeded,
506        should_label_span: bool,
507        ty: Option<Ty<'tcx>>,
508    ) -> Diag<'a> {
509        let term = self.resolve_vars_if_possible(term);
510        let arg_data = self
511            .extract_inference_diagnostics_data(term, ty::print::RegionHighlightMode::default());
512
513        let Some(typeck_results) = &self.typeck_results else {
514            // If we don't have any typeck results we're outside
515            // of a body, so we won't be able to get better info
516            // here.
517            return self.bad_inference_failure_err(failure_span, arg_data, error_code);
518        };
519
520        let mut local_visitor = FindInferSourceVisitor::new(self, typeck_results, term, ty);
521        if let Some(body) =
522            self.tcx.hir_maybe_body_owned_by(self.tcx.typeck_root_def_id_local(body_def_id))
523        {
524            let expr = body.value;
525            local_visitor.visit_expr(expr);
526        }
527
528        let Some(InferSource { span, kind }) = local_visitor.infer_source else {
529            let silence = if let DefKind::AssocFn = self.tcx.def_kind(body_def_id)
530                && let parent = self.tcx.local_parent(body_def_id)
531                && self.tcx.is_automatically_derived(parent.to_def_id())
532                && let hir::Node::Item(item) = self.tcx.hir_node_by_def_id(parent)
533                && let hir::ItemKind::Impl(imp) = item.kind
534                && let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = imp.self_ty.kind
535                && let Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, def_id) = path.res
536                && let Some(def_id) = def_id.as_local()
537                && let hir::Node::Item(item) = self.tcx.hir_node_by_def_id(def_id)
538            {
539                // We have encountered an inference error within an automatically derived `impl`,
540                // from a `#[derive(..)]` on an item that had a parse error. Because the parse
541                // error might have caused the expanded code to be malformed, we silence the
542                // inference error.
543                item.kind.recovered()
544            } else {
545                false
546            };
547            let mut err = self.bad_inference_failure_err(failure_span, arg_data, error_code);
548            if silence {
549                err.downgrade_to_delayed_bug();
550            }
551            return err;
552        };
553
554        let (source_kind, name, long_ty_path) = kind.ty_localized_msg(self);
555        let failure_span = if should_label_span && !failure_span.overlaps(span) {
556            Some(failure_span)
557        } else {
558            None
559        };
560
561        let subdiagnostic = kind.suggestion(
562            self.tcx,
563            self.infcx,
564            body_def_id,
565            term,
566            &arg_data,
567            typeck_results,
568            span,
569        );
570
571        let mut err = match error_code {
572            TypeAnnotationNeeded::E0282 => self.dcx().create_err(AnnotationRequired {
573                span,
574                source_kind,
575                source_name: &name,
576                failure_span,
577                subdiagnostic,
578                bad_label: None,
579            }),
580            TypeAnnotationNeeded::E0283 => self.dcx().create_err(AmbiguousImpl {
581                span,
582                source_kind,
583                source_name: &name,
584                failure_span,
585                subdiagnostic,
586                bad_label: None,
587            }),
588            TypeAnnotationNeeded::E0284 => self.dcx().create_err(AmbiguousReturn {
589                span,
590                source_kind,
591                source_name: &name,
592                failure_span,
593                subdiagnostic,
594                bad_label: None,
595            }),
596        };
597        *err.long_ty_path() = long_ty_path;
598        if let InferSourceKind::ClosureArg { kind: PatKind::Err(_), .. } = kind {
599            // We will have already emitted an error about this pattern.
600            err.downgrade_to_delayed_bug();
601        }
602        err
603    }
604}
605
606#[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)]
607struct InferSource<'tcx> {
608    span: Span,
609    kind: InferSourceKind<'tcx>,
610}
611
612#[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)]
613enum InferSourceKind<'tcx> {
614    LetBinding {
615        insert_span: Span,
616        pattern_name: Option<Ident>,
617        ty: Ty<'tcx>,
618        def_id: Option<DefId>,
619    },
620    ClosureArg {
621        insert_span: Span,
622        ty: Ty<'tcx>,
623        kind: PatKind<'tcx>,
624    },
625    GenericArg {
626        insert_span: Span,
627        argument_index: usize,
628        generics_def_id: DefId,
629        def_id: DefId,
630        generic_args: &'tcx [GenericArg<'tcx>],
631        have_turbofish: bool,
632        hir_id: HirId,
633    },
634    FullyQualifiedMethodCall {
635        receiver: &'tcx Expr<'tcx>,
636        /// If the method has other arguments, this is ", " and the start of the first argument,
637        /// while for methods without arguments this is ")" and the end of the method call.
638        successor: (&'static str, BytePos),
639        args: GenericArgsRef<'tcx>,
640        def_id: DefId,
641    },
642    ClosureReturn {
643        ty: Ty<'tcx>,
644        data: &'tcx FnRetTy<'tcx>,
645        should_wrap_expr: Option<Span>,
646    },
647}
648
649impl<'tcx> InferSource<'tcx> {
650    fn from_expansion(&self) -> bool {
651        let source_from_expansion = match self.kind {
652            InferSourceKind::LetBinding { insert_span, .. }
653            | InferSourceKind::ClosureArg { insert_span, .. }
654            | InferSourceKind::GenericArg { insert_span, .. } => insert_span.from_expansion(),
655            InferSourceKind::FullyQualifiedMethodCall { receiver, .. } => {
656                receiver.span.from_expansion()
657            }
658            InferSourceKind::ClosureReturn { data, should_wrap_expr, .. } => {
659                data.span().from_expansion() || should_wrap_expr.is_some_and(Span::from_expansion)
660            }
661        };
662        source_from_expansion || self.span.from_expansion()
663    }
664}
665
666impl<'tcx> InferSourceKind<'tcx> {
667    fn ty_localized_msg(&self, infcx: &InferCtxt<'tcx>) -> (&'static str, String, Option<PathBuf>) {
668        let mut long_ty_path = None;
669        match *self {
670            InferSourceKind::LetBinding { ty, .. }
671            | InferSourceKind::ClosureArg { ty, .. }
672            | InferSourceKind::ClosureReturn { ty, .. } => {
673                if ty.is_closure() {
674                    ("closure", closure_as_fn_str(infcx, ty), long_ty_path)
675                } else if ty.is_ty_or_numeric_infer()
676                    || ty.is_primitive()
677                    || #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Adt(_, args) if
        args.types().count() == 0 && args.consts().count() == 0 => true,
    _ => false,
}matches!(
678                        ty.kind(),
679                        ty::Adt(_, args)
680                        if args.types().count() == 0 && args.consts().count() == 0
681                    )
682                {
683                    // `ty` is either `_`, a primitive type like `u32` or a type with no type or
684                    // const parameters. We will not mention the type in the main inference error
685                    // message.
686                    ("other", String::new(), long_ty_path)
687                } else {
688                    ("normal", infcx.tcx.short_string(ty, &mut long_ty_path), long_ty_path)
689                }
690            }
691            // FIXME: We should be able to add some additional info here.
692            InferSourceKind::GenericArg { .. }
693            | InferSourceKind::FullyQualifiedMethodCall { .. } => {
694                ("other", String::new(), long_ty_path)
695            }
696        }
697    }
698
699    fn suggestion<'local>(
700        &self,
701        tcx: TyCtxt<'tcx>,
702        infcx: &InferCtxt<'tcx>,
703        body_def_id: LocalDefId,
704        term: Term<'tcx>,
705        arg_data: &'local InferenceDiagnosticsData,
706        typeck_results: &TypeckResults<'tcx>,
707        span: Span,
708    ) -> Option<SourceKindSubdiag<'local>>
709    where
710        'tcx: 'local,
711    {
712        let subdiag = match *self {
713            InferSourceKind::LetBinding { insert_span, pattern_name, ty, def_id } => {
714                SourceKindSubdiag::LetLike {
715                    span: insert_span,
716                    name: pattern_name.map(|name| name.to_string()).unwrap_or_else(String::new),
717                    x_kind: arg_data.where_x_is_kind(infcx, ty),
718                    prefix_kind: arg_data.kind.clone(),
719                    prefix: arg_data.kind.try_get_prefix().unwrap_or_default(),
720                    arg_name: &arg_data.name,
721                    kind: if pattern_name.is_some() { "with_pattern" } else { "other" },
722                    type_name: ty_to_string(infcx, ty, def_id),
723                }
724            }
725            InferSourceKind::ClosureArg { insert_span, ty, .. } => SourceKindSubdiag::LetLike {
726                span: insert_span,
727                name: String::new(),
728                x_kind: arg_data.where_x_is_kind(infcx, ty),
729                prefix_kind: arg_data.kind.clone(),
730                prefix: arg_data.kind.try_get_prefix().unwrap_or_default(),
731                arg_name: &arg_data.name,
732                kind: "closure",
733                type_name: ty_to_string(infcx, ty, None),
734            },
735            InferSourceKind::GenericArg {
736                insert_span,
737                argument_index,
738                generics_def_id,
739                def_id: _,
740                generic_args,
741                have_turbofish,
742                hir_id,
743            } => {
744                let generics = tcx.generics_of(generics_def_id);
745                let is_type = term.as_type().is_some();
746
747                let (parent_exists, parent_prefix, parent_name) =
748                    InferenceDiagnosticsParentData::for_parent_def_id(tcx, generics_def_id)
749                        .map_or((false, String::new(), String::new()), |parent| {
750                            (true, parent.prefix.to_string(), parent.name)
751                        });
752
753                let param = &generics.own_params[argument_index];
754                let param_name = param.name.to_string();
755
756                let mut used_fallback = false;
757                let args = if tcx.get_diagnostic_item(sym::iterator_collect_fn)
758                    == Some(generics_def_id)
759                {
760                    if let hir::Node::Expr(expr) = tcx.parent_hir_node(hir_id)
761                        && let hir::ExprKind::Call(expr, _args) = expr.kind
762                        && let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind
763                        && let Res::Def(DefKind::AssocFn, def_id) = path.res
764                        && let Some(try_trait) = tcx.lang_items().try_trait()
765                        && try_trait == tcx.parent(def_id)
766                        && let DefKind::Fn | DefKind::AssocFn =
767                            tcx.def_kind(body_def_id.to_def_id())
768                        && let ret = tcx
769                            .fn_sig(body_def_id.to_def_id())
770                            .instantiate_identity()
771                            .skip_binder()
772                            .output()
773                        && let ty::Adt(adt, _args) = ret.kind()
774                        && let Some(sym::Option | sym::Result) = tcx.get_diagnostic_name(adt.did())
775                    {
776                        if let Some(sym::Option) = tcx.get_diagnostic_name(adt.did()) {
777                            "Option<_>".to_string()
778                        } else {
779                            "Result<_, _>".to_string()
780                        }
781                    } else {
782                        "Vec<_>".to_string()
783                    }
784                } else {
785                    let mut p = fmt_printer(infcx, Namespace::TypeNS);
786                    p.comma_sep(generic_args.iter().copied().map(|arg| {
787                        if arg.is_suggestable(tcx, true) {
788                            used_fallback = true;
789                            return arg;
790                        }
791                        match arg.kind() {
792                            GenericArgKind::Lifetime(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected lifetime"))bug!("unexpected lifetime"),
793                            GenericArgKind::Type(_) => infcx.next_ty_var(DUMMY_SP).into(),
794                            GenericArgKind::Const(_) => infcx.next_const_var(DUMMY_SP).into(),
795                        }
796                    }))
797                    .unwrap();
798                    p.into_buffer()
799                };
800
801                let suggestion = if have_turbofish {
802                    None
803                } else if generic_args.len() == 1 && used_fallback {
804                    match param.kind {
805                        GenericParamDefKind::Type { .. } => {
806                            Some(SpecifyGenericParamsSuggestion::GenericTypeSuggestion {
807                                span: insert_span,
808                                param: param_name.clone(),
809                            })
810                        }
811                        GenericParamDefKind::Const { .. } => {
812                            Some(SpecifyGenericParamsSuggestion::ConstGenericSuggestion {
813                                span: insert_span,
814                                param: param_name.clone(),
815                            })
816                        }
817                        GenericParamDefKind::Lifetime => {
818                            ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected lifetime"))bug!("unexpected lifetime")
819                        }
820                    }
821                } else {
822                    Some(SpecifyGenericParamsSuggestion::GenericSuggestion {
823                        span: insert_span,
824                        arg_count: generic_args.len(),
825                        args,
826                    })
827                };
828
829                SourceKindSubdiag::Generic {
830                    span,
831                    is_type,
832                    param_name,
833                    parent_exists,
834                    parent_prefix,
835                    parent_name,
836                    suggestion,
837                }
838            }
839            InferSourceKind::FullyQualifiedMethodCall { receiver, successor, args, def_id } => {
840                let placeholder = Some(infcx.next_ty_var(DUMMY_SP));
841                let args = args.make_suggestable(tcx, true, placeholder)?;
842
843                let mut p = fmt_printer(infcx, Namespace::ValueNS);
844                p.print_def_path(def_id, args).unwrap();
845                let def_path = p.into_buffer();
846
847                // We only care about whether we have to add `&` or `&mut ` for now.
848                // This is the case if the last adjustment is a borrow and the
849                // first adjustment was not a builtin deref.
850                let adjustment = match typeck_results.expr_adjustments(receiver) {
851                    [
852                        Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: _ },
853                        ..,
854                        Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), target: _ },
855                    ] => "",
856                    [.., Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mut_)), target: _ }] => {
857                        hir::Mutability::from(*mut_).ref_prefix_str()
858                    }
859                    _ => "",
860                };
861
862                SourceKindSubdiag::new_fully_qualified(
863                    receiver.span,
864                    def_path,
865                    adjustment,
866                    successor,
867                )
868            }
869            InferSourceKind::ClosureReturn { ty, data, should_wrap_expr } => {
870                let placeholder = Some(infcx.next_ty_var(DUMMY_SP));
871
872                let ty = ty.make_suggestable(tcx, true, placeholder)?;
873                let ty_info = ty_to_string(infcx, ty, None);
874                SourceKindSubdiag::new_closure_return(ty_info, data, should_wrap_expr)
875            }
876        };
877
878        Some(subdiag)
879    }
880}
881
882#[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)]
883struct InsertableGenericArgs<'tcx> {
884    insert_span: Span,
885    args: GenericArgsRef<'tcx>,
886    generics_def_id: DefId,
887    def_id: DefId,
888    have_turbofish: bool,
889}
890
891/// A visitor which searches for the "best" spot to use in the inference error.
892///
893/// For this it walks over the hir body and tries to check all places where
894/// inference variables could be bound.
895///
896/// While doing so, the currently best spot is stored in `infer_source`.
897/// For details on how we rank spots, see [Self::source_cost]
898struct FindInferSourceVisitor<'a, 'tcx> {
899    tecx: &'a TypeErrCtxt<'a, 'tcx>,
900    typeck_results: &'a TypeckResults<'tcx>,
901
902    target: Term<'tcx>,
903    ty: Option<Ty<'tcx>>,
904
905    attempt: usize,
906    infer_source_cost: usize,
907    infer_source: Option<InferSource<'tcx>>,
908}
909
910impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> {
911    fn new(
912        tecx: &'a TypeErrCtxt<'a, 'tcx>,
913        typeck_results: &'a TypeckResults<'tcx>,
914        target: Term<'tcx>,
915        ty: Option<Ty<'tcx>>,
916    ) -> Self {
917        FindInferSourceVisitor {
918            tecx,
919            typeck_results,
920
921            target,
922            ty,
923
924            attempt: 0,
925            infer_source_cost: usize::MAX,
926            infer_source: None,
927        }
928    }
929
930    /// Computes cost for the given source.
931    ///
932    /// Sources with a small cost are prefer and should result
933    /// in a clearer and idiomatic suggestion.
934    fn source_cost(&self, source: &InferSource<'tcx>) -> usize {
935        #[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)]
936        struct CostCtxt<'tcx> {
937            tcx: TyCtxt<'tcx>,
938        }
939        impl<'tcx> CostCtxt<'tcx> {
940            fn arg_cost(self, arg: GenericArg<'tcx>) -> usize {
941                match arg.kind() {
942                    GenericArgKind::Lifetime(_) => 0, // erased
943                    GenericArgKind::Type(ty) => self.ty_cost(ty),
944                    GenericArgKind::Const(_) => 3, // some non-zero value
945                }
946            }
947            fn ty_cost(self, ty: Ty<'tcx>) -> usize {
948                match *ty.kind() {
949                    ty::Closure(..) => 1000,
950                    ty::FnDef(..) => 150,
951                    ty::FnPtr(..) => 30,
952                    ty::Adt(def, args) => {
953                        5 + self
954                            .tcx
955                            .generics_of(def.did())
956                            .own_args_no_defaults(self.tcx, args)
957                            .iter()
958                            .map(|&arg| self.arg_cost(arg))
959                            .sum::<usize>()
960                    }
961                    ty::Tuple(args) => 5 + args.iter().map(|arg| self.ty_cost(arg)).sum::<usize>(),
962                    ty::Ref(_, ty, _) => 2 + self.ty_cost(ty),
963                    ty::Infer(..) => 0,
964                    _ => 1,
965                }
966            }
967        }
968
969        // The sources are listed in order of preference here.
970        let tcx = self.tecx.tcx;
971        let ctx = CostCtxt { tcx };
972        match source.kind {
973            InferSourceKind::LetBinding { ty, .. } => ctx.ty_cost(ty),
974            InferSourceKind::ClosureArg { ty, .. } => ctx.ty_cost(ty),
975            InferSourceKind::GenericArg { def_id, generic_args, .. } => {
976                let variant_cost = match tcx.def_kind(def_id) {
977                    // `None::<u32>` and friends are ugly.
978                    DefKind::Variant | DefKind::Ctor(CtorOf::Variant, _) => 15,
979                    _ => 10,
980                };
981                variant_cost + generic_args.iter().map(|&arg| ctx.arg_cost(arg)).sum::<usize>()
982            }
983            InferSourceKind::FullyQualifiedMethodCall { args, .. } => {
984                20 + args.iter().map(|arg| ctx.arg_cost(arg)).sum::<usize>()
985            }
986            InferSourceKind::ClosureReturn { ty, should_wrap_expr, .. } => {
987                30 + ctx.ty_cost(ty) + if should_wrap_expr.is_some() { 10 } else { 0 }
988            }
989        }
990    }
991
992    /// Uses `fn source_cost` to determine whether this inference source is preferable to
993    /// previous sources. We generally prefer earlier sources.
994    #[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(994u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                                    ::tracing_core::field::FieldSet::new(&["new_source"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&new_source)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if 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:1001",
                                    "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(1001u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                                    ::tracing_core::field::FieldSet::new(&["cost"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&cost) as
                                                        &dyn 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))]
995    fn update_infer_source(&mut self, mut new_source: InferSource<'tcx>) {
996        if new_source.from_expansion() {
997            return;
998        }
999
1000        let cost = self.source_cost(&new_source) + self.attempt;
1001        debug!(?cost);
1002        self.attempt += 1;
1003        if let Some(InferSource { kind: InferSourceKind::GenericArg { def_id: did, .. }, .. }) =
1004            self.infer_source
1005            && let InferSourceKind::LetBinding { ref ty, ref mut def_id, .. } = new_source.kind
1006            && ty.is_ty_or_numeric_infer()
1007        {
1008            // Customize the output so we talk about `let x: Vec<_> = iter.collect();` instead of
1009            // `let x: _ = iter.collect();`, as this is a very common case.
1010            *def_id = Some(did);
1011        }
1012
1013        if cost < self.infer_source_cost {
1014            self.infer_source_cost = cost;
1015            self.infer_source = Some(new_source);
1016        }
1017    }
1018
1019    fn node_args_opt(&self, hir_id: HirId) -> Option<GenericArgsRef<'tcx>> {
1020        let args = self.typeck_results.node_args_opt(hir_id);
1021        self.tecx.resolve_vars_if_possible(args)
1022    }
1023
1024    fn opt_node_type(&self, hir_id: HirId) -> Option<Ty<'tcx>> {
1025        let ty = self.typeck_results.node_type_opt(hir_id);
1026        self.tecx.resolve_vars_if_possible(ty)
1027    }
1028
1029    // Check whether this generic argument is the inference variable we
1030    // are looking for.
1031    fn generic_arg_is_target(&self, arg: GenericArg<'tcx>) -> bool {
1032        if arg == self.target.into() {
1033            return true;
1034        }
1035
1036        match (arg.kind(), self.target.kind()) {
1037            (GenericArgKind::Type(inner_ty), TermKind::Ty(target_ty)) => {
1038                use ty::{Infer, TyVar};
1039                match (inner_ty.kind(), target_ty.kind()) {
1040                    (&Infer(TyVar(a_vid)), &Infer(TyVar(b_vid))) => {
1041                        self.tecx.sub_unification_table_root_var(a_vid)
1042                            == self.tecx.sub_unification_table_root_var(b_vid)
1043                    }
1044                    _ => false,
1045                }
1046            }
1047            (GenericArgKind::Const(inner_ct), TermKind::Const(target_ct)) => {
1048                match (inner_ct.kind(), target_ct.kind()) {
1049                    (
1050                        ty::ConstKind::Infer(ty::InferConst::Var(a_vid)),
1051                        ty::ConstKind::Infer(ty::InferConst::Var(b_vid)),
1052                    ) => self.tecx.root_const_var(a_vid) == self.tecx.root_const_var(b_vid),
1053                    _ => false,
1054                }
1055            }
1056            _ => false,
1057        }
1058    }
1059
1060    /// Does this generic argument contain our target inference variable
1061    /// in a way which can be written by the user.
1062    fn generic_arg_contains_target(&self, arg: GenericArg<'tcx>) -> bool {
1063        let mut walker = arg.walk();
1064        while let Some(inner) = walker.next() {
1065            if self.generic_arg_is_target(inner) {
1066                return true;
1067            }
1068            match inner.kind() {
1069                GenericArgKind::Lifetime(_) => {}
1070                GenericArgKind::Type(ty) => {
1071                    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!(
1072                        ty.kind(),
1073                        ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. })
1074                            | ty::Closure(..)
1075                            | ty::CoroutineClosure(..)
1076                            | ty::Coroutine(..)
1077                    ) {
1078                        // Opaque types can't be named by the user right now.
1079                        //
1080                        // Both the generic arguments of closures and coroutines can
1081                        // also not be named. We may want to only look into the closure
1082                        // signature in case it has no captures, as that can be represented
1083                        // using `fn(T) -> R`.
1084
1085                        // FIXME(type_alias_impl_trait): These opaque types
1086                        // can actually be named, so it would make sense to
1087                        // adjust this case and add a test for it.
1088                        walker.skip_current_subtree();
1089                    }
1090                }
1091                GenericArgKind::Const(ct) => {
1092                    if #[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
    ty::ConstKind::Alias(..) => true,
    _ => false,
}matches!(ct.kind(), ty::ConstKind::Alias(..)) {
1093                        // You can't write the generic arguments for
1094                        // alias constants.
1095                        walker.skip_current_subtree();
1096                    }
1097                }
1098            }
1099        }
1100        false
1101    }
1102
1103    fn expr_inferred_arg_iter(
1104        &self,
1105        expr: &'tcx hir::Expr<'tcx>,
1106    ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
1107        let tcx = self.tecx.tcx;
1108        match expr.kind {
1109            hir::ExprKind::Path(ref path) => {
1110                if let Some(args) = self.node_args_opt(expr.hir_id) {
1111                    return self.path_inferred_arg_iter(expr.hir_id, args, path);
1112                }
1113            }
1114            // FIXME(#98711): Ideally we would also deal with type relative
1115            // paths here, even if that is quite rare.
1116            //
1117            // See the `need_type_info/expr-struct-type-relative-gat.rs` test
1118            // for an example where that would be needed.
1119            //
1120            // However, the `type_dependent_def_id` for `Self::Output` in an
1121            // impl is currently the `DefId` of `Output` in the trait definition
1122            // which makes this somewhat difficult and prevents us from just
1123            // using `self.path_inferred_arg_iter` here.
1124            hir::ExprKind::Struct(&hir::QPath::Resolved(_self_ty, path), _, _)
1125            // FIXME(TaKO8Ki): Ideally we should support other kinds,
1126            // such as `TyAlias` or `AssocTy`. For that we have to map
1127            // back from the self type to the type alias though. That's difficult.
1128            //
1129            // See the `need_type_info/issue-103053.rs` test for
1130            // a example.
1131            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, _)) => {
1132                if let Some(ty) = self.opt_node_type(expr.hir_id)
1133                    && let ty::Adt(_, args) = ty.kind()
1134                {
1135                    return Box::new(self.resolved_path_inferred_arg_iter(path, args));
1136                }
1137            }
1138            hir::ExprKind::MethodCall(segment, ..) => {
1139                if let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) {
1140                    let generics = tcx.generics_of(def_id);
1141                    let insertable = try {
1142                        if generics.has_impl_trait() {
1143                            None?
1144                        }
1145                        let args = self.node_args_opt(expr.hir_id)?;
1146                        let span = tcx.hir_span(segment.hir_id);
1147                        let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1148                        let have_turbofish = segment.args.is_some_and(|args| {
1149                            args.args.iter().any(|arg| arg.is_ty_or_const())
1150                        });
1151                        InsertableGenericArgs {
1152                            insert_span,
1153                            args,
1154                            generics_def_id: def_id,
1155                            def_id,
1156                            have_turbofish,
1157                        }
1158                    };
1159                    return Box::new(insertable.into_iter());
1160                }
1161            }
1162            _ => {}
1163        }
1164
1165        Box::new(iter::empty())
1166    }
1167
1168    fn resolved_path_inferred_arg_iter(
1169        &self,
1170        path: &'tcx hir::Path<'tcx>,
1171        args: GenericArgsRef<'tcx>,
1172    ) -> impl Iterator<Item = InsertableGenericArgs<'tcx>> + 'tcx {
1173        let tcx = self.tecx.tcx;
1174        let have_turbofish = path.segments.iter().any(|segment| {
1175            segment.args.is_some_and(|args| args.args.iter().any(|arg| arg.is_ty_or_const()))
1176        });
1177        // The last segment of a path often has `Res::Err` and the
1178        // correct `Res` is the one of the whole path.
1179        //
1180        // FIXME: We deal with that one separately for now,
1181        // would be good to remove this special case.
1182        let last_segment_using_path_data = try {
1183            let generics_def_id = tcx.res_generics_def_id(path.res)?;
1184            let generics = tcx.generics_of(generics_def_id);
1185            if generics.has_impl_trait() {
1186                do yeet ();
1187            }
1188            let insert_span =
1189                path.segments.last().unwrap().ident.span.shrink_to_hi().with_hi(path.span.hi());
1190            InsertableGenericArgs {
1191                insert_span,
1192                args,
1193                generics_def_id,
1194                def_id: path.res.def_id(),
1195                have_turbofish,
1196            }
1197        };
1198
1199        path.segments
1200            .iter()
1201            .filter_map(move |segment| {
1202                let res = segment.res;
1203                let generics_def_id = tcx.res_generics_def_id(res)?;
1204                let generics = tcx.generics_of(generics_def_id);
1205                if generics.has_impl_trait() {
1206                    return None;
1207                }
1208                let span = tcx.hir_span(segment.hir_id);
1209                let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1210                Some(InsertableGenericArgs {
1211                    insert_span,
1212                    args,
1213                    generics_def_id,
1214                    def_id: res.def_id(),
1215                    have_turbofish,
1216                })
1217            })
1218            .chain(last_segment_using_path_data)
1219    }
1220
1221    fn path_inferred_arg_iter(
1222        &self,
1223        hir_id: HirId,
1224        args: GenericArgsRef<'tcx>,
1225        qpath: &'tcx hir::QPath<'tcx>,
1226    ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> {
1227        let tcx = self.tecx.tcx;
1228        match qpath {
1229            hir::QPath::Resolved(_self_ty, path) => {
1230                Box::new(self.resolved_path_inferred_arg_iter(path, args))
1231            }
1232            hir::QPath::TypeRelative(ty, segment) => {
1233                let Some(def_id) = self.typeck_results.type_dependent_def_id(hir_id) else {
1234                    return Box::new(iter::empty());
1235                };
1236
1237                let generics = tcx.generics_of(def_id);
1238                let segment = if !segment.infer_args || generics.has_impl_trait() {
1239                    None
1240                } else {
1241                    let span = tcx.hir_span(segment.hir_id);
1242                    let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi());
1243                    Some(InsertableGenericArgs {
1244                        insert_span,
1245                        args,
1246                        generics_def_id: def_id,
1247                        def_id,
1248                        have_turbofish: false,
1249                    })
1250                };
1251
1252                let parent_def_id = generics.parent.unwrap();
1253                if let DefKind::Impl { .. } = tcx.def_kind(parent_def_id) {
1254                    let parent_ty =
1255                        tcx.type_of(parent_def_id).instantiate(tcx, args).skip_norm_wip();
1256                    match (parent_ty.kind(), &ty.kind) {
1257                        (
1258                            ty::Adt(def, args),
1259                            hir::TyKind::Path(hir::QPath::Resolved(_self_ty, path)),
1260                        ) => {
1261                            if tcx.res_generics_def_id(path.res) != Some(def.did()) {
1262                                match path.res {
1263                                    Res::Def(DefKind::TyAlias, _) => {
1264                                        // FIXME: Ideally we should support this. For that
1265                                        // we have to map back from the self type to the
1266                                        // type alias though. That's difficult.
1267                                        //
1268                                        // See the `need_type_info/type-alias.rs` test for
1269                                        // some examples.
1270                                    }
1271                                    // There cannot be inference variables in the self type,
1272                                    // so there's nothing for us to do here.
1273                                    Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {}
1274                                    _ => {
    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:1274",
                        "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(1274u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("unexpected path: def={0:?} args={1:?} path={2:?}",
                                                    def, args, path) as &dyn Value))])
            });
    } else { ; }
}warn!(
1275                                        "unexpected path: def={:?} args={:?} path={:?}",
1276                                        def, args, path,
1277                                    ),
1278                                }
1279                            } else {
1280                                return Box::new(
1281                                    self.resolved_path_inferred_arg_iter(path, args).chain(segment),
1282                                );
1283                            }
1284                        }
1285                        _ => (),
1286                    }
1287                }
1288
1289                Box::new(segment.into_iter())
1290            }
1291        }
1292    }
1293}
1294
1295impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> {
1296    type NestedFilter = nested_filter::OnlyBodies;
1297
1298    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1299        self.tecx.tcx
1300    }
1301
1302    fn visit_local(&mut self, local: &'tcx LetStmt<'tcx>) {
1303        intravisit::walk_local(self, local);
1304
1305        if let Some(mut ty) = self.opt_node_type(local.hir_id) {
1306            if self.generic_arg_contains_target(ty.into()) {
1307                fn get_did(
1308                    typeck_results: &TypeckResults<'_>,
1309                    expr: &hir::Expr<'_>,
1310                ) -> Option<DefId> {
1311                    match expr.kind {
1312                        hir::ExprKind::Match(expr, _, hir::MatchSource::TryDesugar(_))
1313                            if let hir::ExprKind::Call(_, [expr]) = expr.kind =>
1314                        {
1315                            get_did(typeck_results, expr)
1316                        }
1317                        hir::ExprKind::Call(base, _args)
1318                            if let hir::ExprKind::Path(path) = base.kind
1319                                && let hir::QPath::Resolved(_, path) = path
1320                                && let Res::Def(_, did) = path.res =>
1321                        {
1322                            Some(did)
1323                        }
1324                        hir::ExprKind::MethodCall(..)
1325                            if let Some(did) =
1326                                typeck_results.type_dependent_def_id(expr.hir_id) =>
1327                        {
1328                            Some(did)
1329                        }
1330                        _ => None,
1331                    }
1332                }
1333                if let Some(t) = self.ty
1334                    && ty.has_infer()
1335                {
1336                    ty = t;
1337                }
1338                if let LocalSource::Normal = local.source
1339                    && local.ty.is_none()
1340                {
1341                    self.update_infer_source(InferSource {
1342                        span: local.pat.span,
1343                        kind: InferSourceKind::LetBinding {
1344                            insert_span: local.pat.span.shrink_to_hi(),
1345                            pattern_name: local.pat.simple_ident(),
1346                            ty,
1347                            def_id: local.init.and_then(|expr| get_did(self.typeck_results, expr)),
1348                        },
1349                    });
1350                }
1351            }
1352        }
1353    }
1354
1355    /// For closures, we first visit the parameters and then the content,
1356    /// as we prefer those.
1357    fn visit_body(&mut self, body: &Body<'tcx>) {
1358        for param in body.params {
1359            {
    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:1359",
                        "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(1359u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("param: span {0:?}, ty_span {1:?}, pat.span {2:?}",
                                                    param.span, param.ty_span, param.pat.span) as &dyn Value))])
            });
    } else { ; }
};debug!(
1360                "param: span {:?}, ty_span {:?}, pat.span {:?}",
1361                param.span, param.ty_span, param.pat.span
1362            );
1363            if param.ty_span != param.pat.span {
1364                {
    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:1364",
                        "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(1364u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("skipping param: has explicit type")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("skipping param: has explicit type");
1365                continue;
1366            }
1367
1368            let Some(param_ty) = self.opt_node_type(param.hir_id) else { continue };
1369
1370            if self.generic_arg_contains_target(param_ty.into()) {
1371                self.update_infer_source(InferSource {
1372                    span: param.pat.span,
1373                    kind: InferSourceKind::ClosureArg {
1374                        insert_span: param.pat.span.shrink_to_hi(),
1375                        ty: param_ty,
1376                        kind: param.pat.kind,
1377                    },
1378                })
1379            }
1380        }
1381        intravisit::walk_body(self, body);
1382    }
1383
1384    #[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(1384u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                                    ::tracing_core::field::FieldSet::new(&["expr"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn Value))])
                            })
                } 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:1400",
                                        "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(1400u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::need_type_info"),
                                        ::tracing_core::field::FieldSet::new(&["args"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&args) as
                                                            &dyn 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))]
1385    fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1386        let tcx = self.tecx.tcx;
1387        match expr.kind {
1388            // When encountering `func(arg)` first look into `arg` and then `func`,
1389            // as `arg` is "more specific".
1390            ExprKind::Call(func, args) => {
1391                for arg in args {
1392                    self.visit_expr(arg);
1393                }
1394                self.visit_expr(func);
1395            }
1396            _ => intravisit::walk_expr(self, expr),
1397        }
1398
1399        for args in self.expr_inferred_arg_iter(expr) {
1400            debug!(?args);
1401            let InsertableGenericArgs {
1402                insert_span,
1403                args,
1404                generics_def_id,
1405                def_id,
1406                have_turbofish,
1407            } = args;
1408            let generics = tcx.generics_of(generics_def_id);
1409            if let Some(argument_index) = generics
1410                .own_args(args)
1411                .iter()
1412                .position(|&arg| self.generic_arg_contains_target(arg))
1413            {
1414                let args = self.tecx.resolve_vars_if_possible(args);
1415                let generic_args =
1416                    &generics.own_args_no_defaults(tcx, args)[generics.own_counts().lifetimes..];
1417                let span = match expr.kind {
1418                    ExprKind::MethodCall(segment, ..)
1419                        if have_turbofish
1420                            && let Some(hir_args) = segment.args
1421                            && let Some(idx) =
1422                                argument_index.checked_sub(generics.own_counts().lifetimes)
1423                            && let Some(arg) =
1424                                hir_args.args.get(hir_args.num_lifetime_args() + idx) =>
1425                    {
1426                        arg.span()
1427                    }
1428                    ExprKind::MethodCall(segment, ..) => segment.ident.span,
1429                    _ => expr.span,
1430                };
1431                let mut argument_index = argument_index;
1432                if generics.has_own_self() {
1433                    argument_index += 1;
1434                }
1435
1436                self.update_infer_source(InferSource {
1437                    span,
1438                    kind: InferSourceKind::GenericArg {
1439                        insert_span,
1440                        argument_index,
1441                        generics_def_id,
1442                        def_id,
1443                        generic_args,
1444                        have_turbofish,
1445                        hir_id: expr.hir_id,
1446                    },
1447                });
1448            }
1449        }
1450
1451        if let Some(node_ty) = self.opt_node_type(expr.hir_id) {
1452            if let (
1453                &ExprKind::Closure(&Closure { fn_decl, body, fn_decl_span, .. }),
1454                ty::Closure(_, args),
1455            ) = (&expr.kind, node_ty.kind())
1456            {
1457                let output = args.as_closure().sig().output().skip_binder();
1458                if self.generic_arg_contains_target(output.into()) {
1459                    let body = self.tecx.tcx.hir_body(body);
1460                    let should_wrap_expr = if matches!(body.value.kind, ExprKind::Block(..)) {
1461                        None
1462                    } else {
1463                        Some(body.value.span.shrink_to_hi())
1464                    };
1465                    self.update_infer_source(InferSource {
1466                        span: fn_decl_span,
1467                        kind: InferSourceKind::ClosureReturn {
1468                            ty: output,
1469                            data: &fn_decl.output,
1470                            should_wrap_expr,
1471                        },
1472                    })
1473                }
1474            }
1475        }
1476
1477        let has_impl_trait = |def_id| {
1478            iter::successors(Some(tcx.generics_of(def_id)), |generics| {
1479                generics.parent.map(|def_id| tcx.generics_of(def_id))
1480            })
1481            .any(|generics| generics.has_impl_trait())
1482        };
1483        if let ExprKind::MethodCall(path, receiver, method_args, span) = expr.kind
1484            && let Some(args) = self.node_args_opt(expr.hir_id)
1485            && args.iter().any(|arg| self.generic_arg_contains_target(arg))
1486            && let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id)
1487            && self.tecx.tcx.trait_of_assoc(def_id).is_some()
1488            && !has_impl_trait(def_id)
1489            // FIXME(fn_delegation): In delegation item argument spans are equal to last path
1490            // segment. This leads to ICE's when emitting `multipart_suggestion`.
1491            && tcx.hir_opt_delegation_sig_id(expr.hir_id.owner.def_id).is_none()
1492        {
1493            let successor =
1494                method_args.get(0).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo()));
1495            let args = self.tecx.resolve_vars_if_possible(args);
1496            self.update_infer_source(InferSource {
1497                span: path.ident.span,
1498                kind: InferSourceKind::FullyQualifiedMethodCall {
1499                    receiver,
1500                    successor,
1501                    args,
1502                    def_id,
1503                },
1504            })
1505        }
1506    }
1507}