Skip to main content

rustc_ty_utils/
instance.rs

1use rustc_errors::ErrorGuaranteed;
2use rustc_hir::attrs::lang_items::LangItem;
3use rustc_hir::def::DefKind;
4use rustc_hir::def_id::DefId;
5use rustc_infer::infer::TyCtxtInferExt;
6use rustc_middle::query::Providers;
7use rustc_middle::traits::{BuiltinImplSource, CodegenObligationError};
8use rustc_middle::ty::{
9    self, ClosureKind, GenericArgsRef, Instance, PseudoCanonicalInput, TyCtxt, TypeVisitableExt,
10    Unnormalized,
11};
12use rustc_span::{bug, sym};
13use rustc_trait_selection::traits;
14use tracing::debug;
15use traits::translate_args;
16
17fn resolve_instance_raw<'tcx>(
18    tcx: TyCtxt<'tcx>,
19    key: ty::PseudoCanonicalInput<'tcx, (DefId, GenericArgsRef<'tcx>)>,
20) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
21    let PseudoCanonicalInput { typing_env, value: (def_id, args) } = key;
22
23    let result = if let Some(trait_def_id) = tcx.trait_of_assoc(def_id) {
24        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs:24",
                        "rustc_ty_utils::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(24u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" => associated item, attempting to find impl in typing_env {0:#?}",
                                                    typing_env) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(" => associated item, attempting to find impl in typing_env {:#?}", typing_env);
25        resolve_associated_item(
26            tcx,
27            def_id,
28            typing_env,
29            trait_def_id,
30            tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(args)),
31        )
32    } else {
33        let def = if tcx.intrinsic(def_id).is_some() {
34            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs:34",
                        "rustc_ty_utils::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(34u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" => intrinsic")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(" => intrinsic");
35            ty::InstanceKind::Intrinsic(def_id)
36        } else if tcx.is_lang_item(def_id, LangItem::DropGlue) {
37            let ty = args.type_at(0);
38
39            let shim = if ty.needs_drop(tcx, typing_env) {
40                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs:40",
                        "rustc_ty_utils::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(40u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" => nontrivial drop glue")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(" => nontrivial drop glue");
41                match *ty.kind() {
42                    ty::Coroutine(coroutine_def_id, ..) => {
43                        // FIXME: sync drop of coroutine with async drop (generate both versions?)
44                        // Currently just ignored
45                        if tcx.optimized_mir(coroutine_def_id).coroutine_drop_async().is_some() {
46                            ty::ShimKind::DropGlue(def_id, None)
47                        } else {
48                            ty::ShimKind::DropGlue(def_id, Some(ty))
49                        }
50                    }
51                    ty::Closure(..)
52                    | ty::CoroutineClosure(..)
53                    | ty::Tuple(..)
54                    | ty::Adt(..)
55                    | ty::Dynamic(..)
56                    | ty::Array(..)
57                    | ty::Slice(..)
58                    | ty::UnsafeBinder(..) => ty::ShimKind::DropGlue(def_id, Some(ty)),
59                    // Drop shims can only be built from ADTs.
60                    _ => return Ok(None),
61                }
62            } else {
63                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs:63",
                        "rustc_ty_utils::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(63u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" => trivial drop glue")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(" => trivial drop glue");
64                ty::ShimKind::DropGlue(def_id, None)
65            };
66            ty::InstanceKind::Shim(shim)
67        } else if tcx.is_lang_item(def_id, LangItem::AsyncDropInPlace) {
68            let ty = args.type_at(0);
69
70            if ty.needs_async_drop(tcx, typing_env) {
71                match *ty.kind() {
72                    ty::Closure(..)
73                    | ty::CoroutineClosure(..)
74                    | ty::Coroutine(..)
75                    | ty::Tuple(..)
76                    | ty::Adt(..)
77                    | ty::Dynamic(..)
78                    | ty::Array(..)
79                    | ty::Slice(..) => {}
80                    // Async destructor ctor shims can only be built from ADTs.
81                    _ => return Ok(None),
82                }
83                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs:83",
                        "rustc_ty_utils::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(83u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" => nontrivial async drop glue ctor")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(" => nontrivial async drop glue ctor");
84                ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(def_id, ty))
85            } else {
86                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs:86",
                        "rustc_ty_utils::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(86u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" => trivial async drop glue ctor")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(" => trivial async drop glue ctor");
87                ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(def_id, ty))
88            }
89        } else if tcx.is_async_drop_in_place_coroutine(def_id) {
90            let ty = args.type_at(0);
91            ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(def_id, ty))
92        } else if tcx.def_kind(def_id) == DefKind::Fn
93            && let Some(name) = tcx.codegen_fn_attrs(def_id).symbol_name
94            && name.as_str().starts_with("llvm.")
95        {
96            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs:96",
                        "rustc_ty_utils::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(96u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" => LLVM intrinsic")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(" => LLVM intrinsic");
97            ty::InstanceKind::LlvmIntrinsic(def_id)
98        } else {
99            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs:99",
                        "rustc_ty_utils::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(99u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" => free item")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(" => free item");
100            ty::InstanceKind::Item(def_id)
101        };
102
103        Ok(Some(Instance { def, args }))
104    };
105    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs:105",
                        "rustc_ty_utils::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(105u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_instance: result={0:?}",
                                                    result) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_instance: result={:?}", result);
106    result
107}
108
109fn resolve_associated_item<'tcx>(
110    tcx: TyCtxt<'tcx>,
111    trait_item_id: DefId,
112    typing_env: ty::TypingEnv<'tcx>,
113    trait_id: DefId,
114    rcvr_args: GenericArgsRef<'tcx>,
115) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
116    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs:116",
                        "rustc_ty_utils::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(116u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::instance"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("trait_item_id")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("trait_item_id");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("typing_env")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("typing_env");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("trait_id")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("trait_id");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("rcvr_args")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("rcvr_args");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_associated_item")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_item_id)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&typing_env)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_id)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rcvr_args)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?trait_item_id, ?typing_env, ?trait_id, ?rcvr_args, "resolve_associated_item");
117
118    let trait_ref = ty::TraitRef::from_assoc(tcx, trait_id, rcvr_args);
119
120    let input = typing_env.as_query_input(trait_ref);
121    let vtbl = match tcx.codegen_select_candidate(input) {
122        Ok(vtbl) => vtbl,
123        Err(CodegenObligationError::Ambiguity | CodegenObligationError::Unimplemented) => {
124            return Ok(None);
125        }
126        Err(CodegenObligationError::UnconstrainedParam(guar)) => return Err(guar),
127    };
128
129    // Now that we know which impl is being used, we can dispatch to
130    // the actual function:
131    Ok(match vtbl {
132        traits::ImplSource::UserDefined(impl_data) => {
133            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs:133",
                        "rustc_ty_utils::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(133u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolving ImplSource::UserDefined: {0:?}, {1:?}, {2:?}, {3:?}",
                                                    typing_env, trait_item_id, rcvr_args, impl_data) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
134                "resolving ImplSource::UserDefined: {:?}, {:?}, {:?}, {:?}",
135                typing_env, trait_item_id, rcvr_args, impl_data
136            );
137            if !!rcvr_args.has_infer() {
    ::core::panicking::panic("assertion failed: !rcvr_args.has_infer()")
};assert!(!rcvr_args.has_infer());
138            if !!trait_ref.has_infer() {
    ::core::panicking::panic("assertion failed: !trait_ref.has_infer()")
};assert!(!trait_ref.has_infer());
139
140            let trait_def_id = tcx.impl_trait_id(impl_data.impl_def_id);
141            let trait_def = tcx.trait_def(trait_def_id);
142            let leaf_def = trait_def
143                .ancestors(tcx, impl_data.impl_def_id)?
144                .leaf_def(tcx, trait_item_id)
145                .unwrap_or_else(|| {
146                    ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} not found in {1:?}", trait_item_id,
        impl_data.impl_def_id), Location::caller());bug!("{:?} not found in {:?}", trait_item_id, impl_data.impl_def_id);
147                });
148
149            // Since this is a trait item, we need to see if the item is either a trait
150            // default item or a specialization because we can't resolve those until we're
151            // in `TypingMode::PostAnalysis`.
152            //
153            // NOTE: This should be kept in sync with the similar code in
154            // `rustc_trait_selection::traits::project::assemble_candidates_from_impls()`.
155            let eligible = if leaf_def.is_final() {
156                // Non-specializable items are always projectable.
157                true
158            } else {
159                // Only reveal a specializable default if we're past type-checking
160                // and the obligation is monomorphic, otherwise passes such as
161                // transmute checking and polymorphic MIR optimizations could
162                // get a result which isn't correct for all monomorphizations.
163                match typing_env.typing_mode().assert_not_erased() {
164                    ty::TypingMode::Coherence
165                    | ty::TypingMode::Typeck { .. }
166                    | ty::TypingMode::PostTypeckUntilBorrowck { .. }
167                    | ty::TypingMode::Reflection
168                    | ty::TypingMode::PostBorrowck { .. } => false,
169                    ty::TypingMode::PostAnalysis | ty::TypingMode::Codegen => {
170                        !trait_ref.still_further_specializable()
171                    }
172                }
173            };
174            if !eligible {
175                return Ok(None);
176            }
177
178            let typing_env = typing_env.with_post_analysis_normalized(tcx);
179            let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
180            let args = rcvr_args.rebase_onto(tcx, trait_def_id, impl_data.args);
181            let args = translate_args(
182                &infcx,
183                param_env,
184                impl_data.impl_def_id,
185                args,
186                leaf_def.defining_node,
187            );
188            let args = infcx.tcx.erase_and_anonymize_regions(args);
189
190            // HACK: We may have overlapping `dyn Trait` built-in impls and
191            // user-provided blanket impls. Detect that case here, and return
192            // ambiguity.
193            //
194            // This should not affect totally monomorphized contexts, only
195            // resolve calls that happen polymorphically, such as the mir-inliner
196            // and const-prop (and also some lints).
197            let self_ty = rcvr_args.type_at(0);
198            if !self_ty.is_known_rigid() {
199                let clauses =
200                    tcx.clauses_of(impl_data.impl_def_id).instantiate(tcx, impl_data.args).clauses;
201                let sized_def_id = tcx.lang_items().sized_trait();
202                // If we find a `Self: Sized` bound on the item, then we know
203                // that `dyn Trait` can certainly never apply here.
204                if !clauses.into_iter().filter_map(|p| p.as_trait_clause()).any(|clause| {
205                    Some(clause.def_id()) == sized_def_id
206                        && clause.skip_binder().self_ty() == self_ty
207                }) {
208                    return Ok(None);
209                }
210            }
211
212            // Any final impl is required to define all associated items.
213            if !leaf_def.item.defaultness(tcx).has_value() {
214                let guar = tcx.dcx().span_delayed_bug(
215                    tcx.def_span(leaf_def.item.def_id),
216                    "missing value for assoc item in impl",
217                );
218                return Err(guar);
219            }
220
221            // Make sure that we're projecting to an item that has compatible args.
222            // This may happen if we are resolving an instance before codegen, such
223            // as during inlining. This check is also done in projection.
224            if !tcx.check_args_compatible(leaf_def.item.def_id, args) {
225                let guar = tcx.dcx().span_delayed_bug(
226                    tcx.def_span(leaf_def.item.def_id),
227                    "missing value for assoc item in impl",
228                );
229                return Err(guar);
230            }
231
232            // We check that the impl item is compatible with the trait item
233            // because otherwise we may ICE in const eval due to type mismatches,
234            // signature incompatibilities, etc.
235            // NOTE: We could also only enforce this in `PostAnalysis`, which
236            // is what CTFE and MIR inlining would care about anyways.
237            if trait_item_id != leaf_def.item.def_id
238                && let Some(leaf_def_item) = leaf_def.item.def_id.as_local()
239            {
240                tcx.ensure_result().compare_impl_item(leaf_def_item)?;
241            }
242
243            Some(ty::Instance::new_raw(leaf_def.item.def_id, args))
244        }
245        traits::ImplSource::Builtin(BuiltinImplSource::Object(_), _) => {
246            let trait_ref = ty::TraitRef::from_assoc(tcx, trait_id, rcvr_args);
247
248            // `final` methods should be called directly.
249            if tcx.defaultness(trait_item_id).is_final() {
250                return Ok(Some(ty::Instance::new_raw(trait_item_id, rcvr_args)));
251            }
252
253            if trait_ref.has_non_region_infer() || trait_ref.has_non_region_param() {
254                // We only resolve totally substituted vtable entries.
255                None
256            } else {
257                let vtable_base = tcx.first_method_vtable_slot(trait_ref);
258                let offset = tcx
259                    .own_existential_vtable_entries(trait_id)
260                    .iter()
261                    .copied()
262                    .position(|def_id| def_id == trait_item_id);
263                offset.map(|offset| Instance {
264                    def: ty::InstanceKind::Virtual(trait_item_id, vtable_base + offset),
265                    args: rcvr_args,
266                })
267            }
268        }
269        traits::ImplSource::Builtin(BuiltinImplSource::Misc | BuiltinImplSource::Trivial, _) => {
270            if tcx.is_lang_item(trait_ref.def_id, LangItem::Clone) {
271                // FIXME(eddyb) use lang items for methods instead of names.
272                let name = tcx.item_name(trait_item_id);
273                if name == sym::clone {
274                    let self_ty = trait_ref.self_ty();
275                    match self_ty.kind() {
276                        ty::FnDef(..) | ty::FnPtr(..) => (),
277                        ty::Coroutine(..)
278                        | ty::CoroutineWitness(..)
279                        | ty::Closure(..)
280                        | ty::CoroutineClosure(..)
281                        | ty::Tuple(..) => {}
282                        _ => return Ok(None),
283                    };
284
285                    Some(Instance {
286                        def: ty::InstanceKind::Shim(ty::ShimKind::Clone(trait_item_id, self_ty)),
287                        args: rcvr_args,
288                    })
289                } else {
290                    {
    match (&name, &sym::clone_from) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(name, sym::clone_from);
291
292                    // Use the default `fn clone_from` from `trait Clone`.
293                    let args = tcx.erase_and_anonymize_regions(rcvr_args);
294                    Some(ty::Instance::new_raw(trait_item_id, args))
295                }
296            } else if tcx.is_lang_item(trait_ref.def_id, LangItem::FnPtrTrait) {
297                let self_ty = trait_ref.self_ty();
298                if !#[allow(non_exhaustive_omitted_patterns)] match self_ty.kind() {
    ty::FnPtr(..) => true,
    _ => false,
}matches!(self_ty.kind(), ty::FnPtr(..)) {
299                    return Ok(None);
300                }
301                if tcx.is_lang_item(trait_item_id, LangItem::FnPtrAsPtr) {
302                    Some(Instance {
303                        def: ty::InstanceKind::Shim(ty::ShimKind::FnPtrAsPtr(
304                            trait_item_id,
305                            self_ty,
306                        )),
307                        args: rcvr_args,
308                    })
309                } else if tcx.is_lang_item(trait_item_id, LangItem::FnPtrFromPtr) {
310                    Some(Instance {
311                        def: ty::InstanceKind::Shim(ty::ShimKind::FnPtrFromPtr(
312                            trait_item_id,
313                            self_ty,
314                        )),
315                        args: rcvr_args,
316                    })
317                } else {
318                    Some(Instance { def: ty::InstanceKind::Item(trait_item_id), args: rcvr_args })
319                }
320            } else if let Some(target_kind) = tcx.fn_trait_kind_from_def_id(trait_ref.def_id) {
321                // FIXME: This doesn't check for malformed libcore that defines, e.g.,
322                // `trait Fn { fn call_once(&self) { .. } }`. This is mostly for extension
323                // methods.
324                if truecfg!(debug_assertions)
325                    && ![sym::call, sym::call_mut, sym::call_once]
326                        .contains(&tcx.item_name(trait_item_id))
327                {
328                    // For compiler developers who'd like to add new items to `Fn`/`FnMut`/`FnOnce`,
329                    // you either need to generate a shim body, or perhaps return
330                    // `InstanceKind::Item` pointing to a trait default method body if
331                    // it is given a default implementation by the trait.
332                    ::rustc_span::macros::bug_impl(None,
    format_args!("no definition for `{1}::{0}` for built-in callable type",
        tcx.item_name(trait_item_id), trait_ref), Location::caller())bug!(
333                        "no definition for `{trait_ref}::{}` for built-in callable type",
334                        tcx.item_name(trait_item_id)
335                    )
336                }
337                match *rcvr_args.type_at(0).kind() {
338                    ty::Closure(closure_def_id, args) => {
339                        Some(Instance::resolve_closure(tcx, closure_def_id, args, target_kind))
340                    }
341                    ty::FnDef(..) | ty::FnPtr(..) => Some(Instance {
342                        def: ty::InstanceKind::Shim(ty::ShimKind::FnPtr(
343                            trait_item_id,
344                            rcvr_args.type_at(0),
345                        )),
346                        args: rcvr_args,
347                    }),
348                    ty::CoroutineClosure(coroutine_closure_def_id, args) => {
349                        // When a coroutine-closure implements the `Fn` traits, then it
350                        // always dispatches to the `FnOnce` implementation. This is to
351                        // ensure that the `closure_kind` of the resulting closure is in
352                        // sync with the built-in trait implementations (since all of the
353                        // implementations return `FnOnce::Output`).
354                        if ty::ClosureKind::FnOnce == args.as_coroutine_closure().kind() {
355                            Some(Instance::new_raw(coroutine_closure_def_id, args))
356                        } else {
357                            Some(Instance {
358                                def: ty::InstanceKind::Shim(
359                                    ty::ShimKind::ConstructCoroutineInClosure {
360                                        coroutine_closure_def_id,
361                                        receiver_by_ref: target_kind != ty::ClosureKind::FnOnce,
362                                    },
363                                ),
364                                args,
365                            })
366                        }
367                    }
368                    _ => ::rustc_span::macros::bug_impl(None,
    format_args!("no built-in definition for `{1}::{0}` for non-fn type",
        tcx.item_name(trait_item_id), trait_ref), Location::caller())bug!(
369                        "no built-in definition for `{trait_ref}::{}` for non-fn type",
370                        tcx.item_name(trait_item_id)
371                    ),
372                }
373            } else if let Some(target_kind) = tcx.async_fn_trait_kind_from_def_id(trait_ref.def_id)
374            {
375                match *rcvr_args.type_at(0).kind() {
376                    ty::CoroutineClosure(coroutine_closure_def_id, args) => {
377                        if target_kind == ClosureKind::FnOnce
378                            && args.as_coroutine_closure().kind() != ClosureKind::FnOnce
379                        {
380                            // If we're computing `AsyncFnOnce` for a by-ref closure then
381                            // construct a new body that has the right return types.
382                            Some(Instance {
383                                def: ty::InstanceKind::Shim(
384                                    ty::ShimKind::ConstructCoroutineInClosure {
385                                        coroutine_closure_def_id,
386                                        receiver_by_ref: false,
387                                    },
388                                ),
389                                args,
390                            })
391                        } else {
392                            Some(Instance::new_raw(coroutine_closure_def_id, args))
393                        }
394                    }
395                    ty::Closure(closure_def_id, args) => {
396                        Some(Instance::resolve_closure(tcx, closure_def_id, args, target_kind))
397                    }
398                    ty::FnDef(..) | ty::FnPtr(..) => Some(Instance {
399                        def: ty::InstanceKind::Shim(ty::ShimKind::FnPtr(
400                            trait_item_id,
401                            rcvr_args.type_at(0),
402                        )),
403                        args: rcvr_args,
404                    }),
405                    _ => ::rustc_span::macros::bug_impl(None,
    format_args!("no built-in definition for `{1}::{0}` for non-lending-closure type",
        tcx.item_name(trait_item_id), trait_ref), Location::caller())bug!(
406                        "no built-in definition for `{trait_ref}::{}` for non-lending-closure type",
407                        tcx.item_name(trait_item_id)
408                    ),
409                }
410            } else if tcx.is_lang_item(trait_ref.def_id, LangItem::TransmuteTrait) {
411                let name = tcx.item_name(trait_item_id);
412                {
    match (&name, &sym::transmute) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(name, sym::transmute);
413                let args = tcx.erase_and_anonymize_regions(rcvr_args);
414                Some(ty::Instance::new_raw(trait_item_id, args))
415            } else if tcx.is_lang_item(trait_ref.def_id, LangItem::Field) {
416                if tcx.is_lang_item(trait_item_id, LangItem::FieldOffset) {
417                    let self_ty = trait_ref.self_ty();
418                    match self_ty.kind() {
419                        ty::Adt(def, _) if def.is_field_representing_type() => {}
420                        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("expected field representing type, found {0}", self_ty),
    Location::caller())bug!("expected field representing type, found {self_ty}"),
421                    }
422                    Some(Instance {
423                        def: ty::InstanceKind::Item(
424                            tcx.lang_items().get(LangItem::FieldOffset).unwrap(),
425                        ),
426                        args: rcvr_args,
427                    })
428                } else {
429                    ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected associated associated item"), Location::caller())bug!("unexpected associated associated item")
430                }
431            } else {
432                Instance::try_resolve_item_for_coroutine(tcx, trait_item_id, trait_id, rcvr_args)
433            }
434        }
435        traits::ImplSource::Param(..)
436        | traits::ImplSource::Builtin(BuiltinImplSource::TraitUpcasting { .. }, _) => None,
437    })
438}
439
440pub(crate) fn provide(providers: &mut Providers) {
441    *providers = Providers { resolve_instance_raw, ..*providers };
442}