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};
7 use rustc_span::{sym, DUMMY_SP};
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(tcx, def.did, param_env, trait_def_id, substs)
49 let ty = tcx.type_of(def.def_id_for_type_of());
50 let item_type = tcx.subst_and_normalize_erasing_regions(substs, param_env, ty);
52 let def = match *item_type.kind() {
53 ty::FnDef(def_id, ..) if tcx.is_intrinsic(def_id) => {
54 debug!(" => intrinsic");
55 ty::InstanceDef::Intrinsic(def.did)
57 ty::FnDef(def_id, substs) if Some(def_id) == tcx.lang_items().drop_in_place_fn() => {
58 let ty = substs.type_at(0);
60 if ty.needs_drop(tcx, param_env) {
61 debug!(" => nontrivial drop glue");
70 // Drop shims can only be built from ADTs.
74 ty::InstanceDef::DropGlue(def_id, Some(ty))
76 debug!(" => trivial drop glue");
77 ty::InstanceDef::DropGlue(def_id, None)
81 debug!(" => free item");
82 ty::InstanceDef::Item(def)
85 Ok(Some(Instance { def, substs }))
87 debug!("inner_resolve_instance: result={:?}", result);
91 fn resolve_associated_item<'tcx>(
94 param_env: ty::ParamEnv<'tcx>,
96 rcvr_substs: SubstsRef<'tcx>,
97 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
98 debug!(?trait_item_id, ?param_env, ?trait_id, ?rcvr_substs, "resolve_associated_item");
100 let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
102 let vtbl = match tcx.codegen_select_candidate((param_env, ty::Binder::dummy(trait_ref))) {
104 Err(CodegenObligationError::Ambiguity) => {
105 let reported = tcx.sess.delay_span_bug(
106 tcx.def_span(trait_item_id),
108 "encountered ambiguity selecting `{trait_ref:?}` during codegen, presuming due to \
109 overflow or prior type error",
112 return Err(reported);
114 Err(CodegenObligationError::Unimplemented) => return Ok(None),
115 Err(CodegenObligationError::FulfillmentError) => return Ok(None),
118 // Now that we know which impl is being used, we can dispatch to
119 // the actual function:
121 traits::ImplSource::UserDefined(impl_data) => {
123 "resolving ImplSource::UserDefined: {:?}, {:?}, {:?}, {:?}",
124 param_env, trait_item_id, rcvr_substs, impl_data
126 assert!(!rcvr_substs.needs_infer());
127 assert!(!trait_ref.needs_infer());
129 let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
130 let trait_def = tcx.trait_def(trait_def_id);
131 let leaf_def = trait_def
132 .ancestors(tcx, impl_data.impl_def_id)?
133 .leaf_def(tcx, trait_item_id)
135 bug!("{:?} not found in {:?}", trait_item_id, impl_data.impl_def_id);
138 let substs = tcx.infer_ctxt().enter(|infcx| {
139 let param_env = param_env.with_reveal_all_normalized(tcx);
140 let substs = rcvr_substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
141 let substs = translate_substs(
144 impl_data.impl_def_id,
146 leaf_def.defining_node,
148 infcx.tcx.erase_regions(substs)
151 // Since this is a trait item, we need to see if the item is either a trait default item
152 // or a specialization because we can't resolve those unless we can `Reveal::All`.
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.
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 if param_env.reveal() == Reveal::All {
164 !trait_ref.still_further_specializable()
174 // If the item does not have a value, then we cannot return an instance.
175 if !leaf_def.item.defaultness(tcx).has_value() {
179 let substs = tcx.erase_regions(substs);
181 // Check if we just resolved an associated `const` declaration from
182 // a `trait` to an associated `const` definition in an `impl`, where
183 // the definition in the `impl` has the wrong type (for which an
184 // error has already been/will be emitted elsewhere).
186 // NB: this may be expensive, we try to skip it in all the cases where
187 // we know the error would've been caught (e.g. in an upstream crate).
189 // A better approach might be to just introduce a query (returning
190 // `Result<(), ErrorGuaranteed>`) for the check that `rustc_hir_analysis`
191 // performs (i.e. that the definition's type in the `impl` matches
192 // the declaration in the `trait`), so that we can cheaply check
193 // here if it failed, instead of approximating it.
194 if leaf_def.item.kind == ty::AssocKind::Const
195 && trait_item_id != leaf_def.item.def_id
196 && leaf_def.item.def_id.is_local()
198 let normalized_type_of = |def_id, substs| {
199 tcx.subst_and_normalize_erasing_regions(substs, param_env, tcx.type_of(def_id))
202 let original_ty = normalized_type_of(trait_item_id, rcvr_substs);
203 let resolved_ty = normalized_type_of(leaf_def.item.def_id, substs);
205 if original_ty != resolved_ty {
207 "Instance::resolve: inconsistent associated `const` type: \
208 was `{}: {}` but resolved to `{}: {}`",
209 tcx.def_path_str_with_substs(trait_item_id, rcvr_substs),
211 tcx.def_path_str_with_substs(leaf_def.item.def_id, substs),
214 let span = tcx.def_span(leaf_def.item.def_id);
215 let reported = tcx.sess.delay_span_bug(span, &msg);
217 return Err(reported);
221 Some(ty::Instance::new(leaf_def.item.def_id, substs))
223 traits::ImplSource::Generator(generator_data) => Some(Instance {
224 def: ty::InstanceDef::Item(ty::WithOptConstParam::unknown(
225 generator_data.generator_def_id,
227 substs: generator_data.substs,
229 traits::ImplSource::Closure(closure_data) => {
230 let trait_closure_kind = tcx.fn_trait_kind_from_lang_item(trait_id).unwrap();
231 Instance::resolve_closure(
233 closure_data.closure_def_id,
238 traits::ImplSource::FnPointer(ref data) => match data.fn_ty.kind() {
239 ty::FnDef(..) | ty::FnPtr(..) => Some(Instance {
240 def: ty::InstanceDef::FnPtrShim(trait_item_id, data.fn_ty),
245 traits::ImplSource::Object(ref data) => {
246 if let Some(index) = traits::get_vtable_index_of_object_method(tcx, data, trait_item_id)
249 def: ty::InstanceDef::Virtual(trait_item_id, index),
256 traits::ImplSource::Builtin(..) => {
257 if Some(trait_ref.def_id) == tcx.lang_items().clone_trait() {
258 // FIXME(eddyb) use lang items for methods instead of names.
259 let name = tcx.item_name(trait_item_id);
260 if name == sym::clone {
261 let self_ty = trait_ref.self_ty();
263 let is_copy = self_ty.is_copy_modulo_regions(tcx.at(DUMMY_SP), param_env);
264 match self_ty.kind() {
267 | ty::GeneratorWitness(..)
269 | ty::Tuple(..) => {}
270 _ => return Ok(None),
274 def: ty::InstanceDef::CloneShim(trait_item_id, self_ty),
278 assert_eq!(name, sym::clone_from);
280 // Use the default `fn clone_from` from `trait Clone`.
281 let substs = tcx.erase_regions(rcvr_substs);
282 Some(ty::Instance::new(trait_item_id, substs))
288 traits::ImplSource::AutoImpl(..)
289 | traits::ImplSource::Param(..)
290 | traits::ImplSource::TraitAlias(..)
291 | traits::ImplSource::DiscriminantKind(..)
292 | traits::ImplSource::Pointee(..)
293 | traits::ImplSource::TraitUpcasting(_)
294 | traits::ImplSource::ConstDestruct(_)
295 | traits::ImplSource::Tuple => None,
299 pub fn provide(providers: &mut ty::query::Providers) {
301 ty::query::Providers { resolve_instance, resolve_instance_of_const_arg, ..*providers };