1 use rustc_errors::ErrorGuaranteed;
2 use rustc_hir::def_id::{DefId, LocalDefId};
3 use rustc_infer::infer::TyCtxtInferExt;
4 use rustc_middle::traits::CodegenObligationError;
5 use rustc_middle::ty::subst::SubstsRef;
6 use rustc_middle::ty::{self, Instance, TyCtxt, TypeVisitable};
8 use rustc_trait_selection::traits;
9 use traits::{translate_substs, Reveal};
11 fn resolve_instance<'tcx>(
13 key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)>,
14 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
15 let (param_env, (did, substs)) = key.into_parts();
16 if let Some(did) = did.as_local() {
17 if let Some(param_did) = tcx.opt_const_param_of(did) {
18 return tcx.resolve_instance_of_const_arg(param_env.and((did, param_did, substs)));
22 inner_resolve_instance(tcx, param_env.and((ty::WithOptConstParam::unknown(did), substs)))
25 fn resolve_instance_of_const_arg<'tcx>(
27 key: ty::ParamEnvAnd<'tcx, (LocalDefId, DefId, SubstsRef<'tcx>)>,
28 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
29 let (param_env, (did, const_param_did, substs)) = key.into_parts();
30 inner_resolve_instance(
33 ty::WithOptConstParam { did: did.to_def_id(), const_param_did: Some(const_param_did) },
39 fn inner_resolve_instance<'tcx>(
41 key: ty::ParamEnvAnd<'tcx, (ty::WithOptConstParam<DefId>, SubstsRef<'tcx>)>,
42 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
43 let (param_env, (def, substs)) = key.into_parts();
45 let result = if let Some(trait_def_id) = tcx.trait_of_item(def.did) {
46 debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
47 resolve_associated_item(
52 tcx.normalize_erasing_regions(param_env, substs),
55 let ty = tcx.type_of(def.def_id_for_type_of());
56 let item_type = tcx.subst_and_normalize_erasing_regions(substs, param_env, ty);
58 let def = match *item_type.kind() {
59 ty::FnDef(def_id, ..) if tcx.is_intrinsic(def_id) => {
60 debug!(" => intrinsic");
61 ty::InstanceDef::Intrinsic(def.did)
63 ty::FnDef(def_id, substs) if Some(def_id) == tcx.lang_items().drop_in_place_fn() => {
64 let ty = substs.type_at(0);
66 if ty.needs_drop(tcx, param_env) {
67 debug!(" => nontrivial drop glue");
76 // Drop shims can only be built from ADTs.
80 ty::InstanceDef::DropGlue(def_id, Some(ty))
82 debug!(" => trivial drop glue");
83 ty::InstanceDef::DropGlue(def_id, None)
87 debug!(" => free item");
88 ty::InstanceDef::Item(def)
91 Ok(Some(Instance { def, substs }))
93 debug!("inner_resolve_instance: result={:?}", result);
97 fn resolve_associated_item<'tcx>(
100 param_env: ty::ParamEnv<'tcx>,
102 rcvr_substs: SubstsRef<'tcx>,
103 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
104 debug!(?trait_item_id, ?param_env, ?trait_id, ?rcvr_substs, "resolve_associated_item");
106 let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
108 let vtbl = match tcx.codegen_select_candidate((param_env, ty::Binder::dummy(trait_ref))) {
110 Err(CodegenObligationError::Ambiguity) => {
111 let reported = tcx.sess.delay_span_bug(
112 tcx.def_span(trait_item_id),
114 "encountered ambiguity selecting `{trait_ref:?}` during codegen, presuming due to \
115 overflow or prior type error",
118 return Err(reported);
120 Err(CodegenObligationError::Unimplemented) => return Ok(None),
121 Err(CodegenObligationError::FulfillmentError) => return Ok(None),
124 // Now that we know which impl is being used, we can dispatch to
125 // the actual function:
127 traits::ImplSource::UserDefined(impl_data) => {
129 "resolving ImplSource::UserDefined: {:?}, {:?}, {:?}, {:?}",
130 param_env, trait_item_id, rcvr_substs, impl_data
132 assert!(!rcvr_substs.needs_infer());
133 assert!(!trait_ref.needs_infer());
135 let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
136 let trait_def = tcx.trait_def(trait_def_id);
137 let leaf_def = trait_def
138 .ancestors(tcx, impl_data.impl_def_id)?
139 .leaf_def(tcx, trait_item_id)
141 bug!("{:?} not found in {:?}", trait_item_id, impl_data.impl_def_id);
143 let infcx = tcx.infer_ctxt().build();
144 let param_env = param_env.with_reveal_all_normalized(tcx);
145 let substs = rcvr_substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
146 let substs = translate_substs(
149 impl_data.impl_def_id,
151 leaf_def.defining_node,
153 let substs = infcx.tcx.erase_regions(substs);
155 // Since this is a trait item, we need to see if the item is either a trait default item
156 // or a specialization because we can't resolve those unless we can `Reveal::All`.
157 // NOTE: This should be kept in sync with the similar code in
158 // `rustc_trait_selection::traits::project::assemble_candidates_from_impls()`.
159 let eligible = if leaf_def.is_final() {
160 // Non-specializable items are always projectable.
163 // Only reveal a specializable default if we're past type-checking
164 // and the obligation is monomorphic, otherwise passes such as
165 // transmute checking and polymorphic MIR optimizations could
166 // get a result which isn't correct for all monomorphizations.
167 if param_env.reveal() == Reveal::All {
168 !trait_ref.still_further_specializable()
178 // Any final impl is required to define all associated items.
179 if !leaf_def.item.defaultness(tcx).has_value() {
180 let guard = tcx.sess.delay_span_bug(
181 tcx.def_span(leaf_def.item.def_id),
182 "missing value for assoc item in impl",
187 let substs = tcx.erase_regions(substs);
189 // Check if we just resolved an associated `const` declaration from
190 // a `trait` to an associated `const` definition in an `impl`, where
191 // the definition in the `impl` has the wrong type (for which an
192 // error has already been/will be emitted elsewhere).
193 if leaf_def.item.kind == ty::AssocKind::Const
194 && trait_item_id != leaf_def.item.def_id
195 && let Some(leaf_def_item) = leaf_def.item.def_id.as_local()
197 tcx.compare_assoc_const_impl_item_with_trait_item((
203 Some(ty::Instance::new(leaf_def.item.def_id, substs))
205 traits::ImplSource::Generator(generator_data) => Some(Instance {
206 def: ty::InstanceDef::Item(ty::WithOptConstParam::unknown(
207 generator_data.generator_def_id,
209 substs: generator_data.substs,
211 traits::ImplSource::Future(future_data) => Some(Instance {
212 def: ty::InstanceDef::Item(ty::WithOptConstParam::unknown(
213 future_data.generator_def_id,
215 substs: future_data.substs,
217 traits::ImplSource::Closure(closure_data) => {
218 let trait_closure_kind = tcx.fn_trait_kind_from_def_id(trait_id).unwrap();
219 Instance::resolve_closure(
221 closure_data.closure_def_id,
226 traits::ImplSource::FnPointer(ref data) => match data.fn_ty.kind() {
227 ty::FnDef(..) | ty::FnPtr(..) => Some(Instance {
228 def: ty::InstanceDef::FnPtrShim(trait_item_id, data.fn_ty),
233 traits::ImplSource::Object(ref data) => {
234 if let Some(index) = traits::get_vtable_index_of_object_method(tcx, data, trait_item_id)
237 def: ty::InstanceDef::Virtual(trait_item_id, index),
244 traits::ImplSource::Builtin(..) => {
245 if Some(trait_ref.def_id) == tcx.lang_items().clone_trait() {
246 // FIXME(eddyb) use lang items for methods instead of names.
247 let name = tcx.item_name(trait_item_id);
248 if name == sym::clone {
249 let self_ty = trait_ref.self_ty();
251 let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env);
252 match self_ty.kind() {
255 | ty::GeneratorWitness(..)
257 | ty::Tuple(..) => {}
258 _ => return Ok(None),
262 def: ty::InstanceDef::CloneShim(trait_item_id, self_ty),
266 assert_eq!(name, sym::clone_from);
268 // Use the default `fn clone_from` from `trait Clone`.
269 let substs = tcx.erase_regions(rcvr_substs);
270 Some(ty::Instance::new(trait_item_id, substs))
276 traits::ImplSource::AutoImpl(..)
277 | traits::ImplSource::Param(..)
278 | traits::ImplSource::TraitAlias(..)
279 | traits::ImplSource::TraitUpcasting(_)
280 | traits::ImplSource::ConstDestruct(_) => None,
284 pub fn provide(providers: &mut ty::query::Providers) {
286 ty::query::Providers { resolve_instance, resolve_instance_of_const_arg, ..*providers };