1 use rustc_errors::ErrorReported;
2 use rustc_hir::def_id::DefId;
3 use rustc_infer::infer::TyCtxtInferExt;
4 use rustc_middle::ty::subst::SubstsRef;
5 use rustc_middle::ty::{self, Instance, TyCtxt, TypeFoldable};
7 use rustc_target::spec::abi::Abi;
8 use rustc_trait_selection::traits;
9 use traits::{translate_substs, Reveal};
13 fn resolve_instance<'tcx>(
15 key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)>,
16 ) -> Result<Option<Instance<'tcx>>, ErrorReported> {
17 let (param_env, (def_id, substs)) = key.into_parts();
19 debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
20 let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) {
21 debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
22 let item = tcx.associated_item(def_id);
23 resolve_associated_item(tcx, &item, param_env, trait_def_id, substs)
25 let ty = tcx.type_of(def_id);
26 let item_type = tcx.subst_and_normalize_erasing_regions(substs, param_env, &ty);
28 let def = match item_type.kind {
31 let f = item_type.fn_sig(tcx);
32 f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic
35 debug!(" => intrinsic");
36 ty::InstanceDef::Intrinsic(def_id)
38 ty::FnDef(def_id, substs) if Some(def_id) == tcx.lang_items().drop_in_place_fn() => {
39 let ty = substs.type_at(0);
41 if ty.needs_drop(tcx, param_env) {
42 // `DropGlue` requires a monomorphic aka concrete type.
47 debug!(" => nontrivial drop glue");
48 ty::InstanceDef::DropGlue(def_id, Some(ty))
50 debug!(" => trivial drop glue");
51 ty::InstanceDef::DropGlue(def_id, None)
55 debug!(" => free item");
56 ty::InstanceDef::Item(def_id)
59 Ok(Some(Instance { def, substs }))
61 debug!("resolve(def_id={:?}, substs={:?}) = {:?}", def_id, substs, result);
65 fn resolve_associated_item<'tcx>(
67 trait_item: &ty::AssocItem,
68 param_env: ty::ParamEnv<'tcx>,
70 rcvr_substs: SubstsRef<'tcx>,
71 ) -> Result<Option<Instance<'tcx>>, ErrorReported> {
72 let def_id = trait_item.def_id;
74 "resolve_associated_item(trait_item={:?}, \
78 def_id, param_env, trait_id, rcvr_substs
81 let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
82 let vtbl = tcx.codegen_fulfill_obligation((param_env, ty::Binder::bind(trait_ref)))?;
84 // Now that we know which impl is being used, we can dispatch to
85 // the actual function:
87 traits::VtableImpl(impl_data) => {
89 "resolving VtableImpl: {:?}, {:?}, {:?}, {:?}",
90 param_env, trait_item, rcvr_substs, impl_data
92 assert!(!rcvr_substs.needs_infer());
93 assert!(!trait_ref.needs_infer());
95 let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
96 let trait_def = tcx.trait_def(trait_def_id);
97 let leaf_def = trait_def
98 .ancestors(tcx, impl_data.impl_def_id)?
99 .leaf_def(tcx, trait_item.ident, trait_item.kind)
101 bug!("{:?} not found in {:?}", trait_item, impl_data.impl_def_id);
104 let substs = tcx.infer_ctxt().enter(|infcx| {
105 let param_env = param_env.with_reveal_all();
106 let substs = rcvr_substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
107 let substs = translate_substs(
110 impl_data.impl_def_id,
112 leaf_def.defining_node,
114 infcx.tcx.erase_regions(&substs)
117 // Since this is a trait item, we need to see if the item is either a trait default item
118 // or a specialization because we can't resolve those unless we can `Reveal::All`.
119 // NOTE: This should be kept in sync with the similar code in
120 // `rustc_trait_selection::traits::project::assemble_candidates_from_impls()`.
121 let eligible = if leaf_def.is_final() {
122 // Non-specializable items are always projectable.
125 // Only reveal a specializable default if we're past type-checking
126 // and the obligation is monomorphic, otherwise passes such as
127 // transmute checking and polymorphic MIR optimizations could
128 // get a result which isn't correct for all monomorphizations.
129 if param_env.reveal == Reveal::All {
130 !trait_ref.still_further_specializable()
140 let substs = tcx.erase_regions(&substs);
142 // Check if we just resolved an associated `const` declaration from
143 // a `trait` to an associated `const` definition in an `impl`, where
144 // the definition in the `impl` has the wrong type (for which an
145 // error has already been/will be emitted elsewhere).
147 // NB: this may be expensive, we try to skip it in all the cases where
148 // we know the error would've been caught (e.g. in an upstream crate).
150 // A better approach might be to just introduce a query (returning
151 // `Result<(), ErrorReported>`) for the check that `rustc_typeck`
152 // performs (i.e. that the definition's type in the `impl` matches
153 // the declaration in the `trait`), so that we can cheaply check
154 // here if it failed, instead of approximating it.
155 if trait_item.kind == ty::AssocKind::Const
156 && trait_item.def_id != leaf_def.item.def_id
157 && leaf_def.item.def_id.is_local()
159 let normalized_type_of = |def_id, substs| {
160 tcx.subst_and_normalize_erasing_regions(substs, param_env, &tcx.type_of(def_id))
163 let original_ty = normalized_type_of(trait_item.def_id, rcvr_substs);
164 let resolved_ty = normalized_type_of(leaf_def.item.def_id, substs);
166 if original_ty != resolved_ty {
168 "Instance::resolve: inconsistent associated `const` type: \
169 was `{}: {}` but resolved to `{}: {}`",
170 tcx.def_path_str_with_substs(trait_item.def_id, rcvr_substs),
172 tcx.def_path_str_with_substs(leaf_def.item.def_id, substs),
175 let span = tcx.def_span(leaf_def.item.def_id);
176 tcx.sess.delay_span_bug(span, &msg);
178 return Err(ErrorReported);
182 Some(ty::Instance::new(leaf_def.item.def_id, substs))
184 traits::VtableGenerator(generator_data) => Some(Instance {
185 def: ty::InstanceDef::Item(generator_data.generator_def_id),
186 substs: generator_data.substs,
188 traits::VtableClosure(closure_data) => {
189 let trait_closure_kind = tcx.fn_trait_kind_from_lang_item(trait_id).unwrap();
190 Some(Instance::resolve_closure(
192 closure_data.closure_def_id,
197 traits::VtableFnPointer(ref data) => {
198 // `FnPtrShim` requires a monomorphic aka concrete type.
199 if data.fn_ty.needs_subst() {
204 def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
208 traits::VtableObject(ref data) => {
209 let index = traits::get_vtable_index_of_object_method(tcx, data, def_id);
210 Some(Instance { def: ty::InstanceDef::Virtual(def_id, index), substs: rcvr_substs })
212 traits::VtableBuiltin(..) => {
213 if Some(trait_ref.def_id) == tcx.lang_items().clone_trait() {
214 // FIXME(eddyb) use lang items for methods instead of names.
215 let name = tcx.item_name(def_id);
216 if name == sym::clone {
217 let self_ty = trait_ref.self_ty();
219 // `CloneShim` requires a monomorphic aka concrete type.
220 if self_ty.needs_subst() {
225 def: ty::InstanceDef::CloneShim(def_id, self_ty),
229 assert_eq!(name, sym::clone_from);
231 // Use the default `fn clone_from` from `trait Clone`.
232 let substs = tcx.erase_regions(&rcvr_substs);
233 Some(ty::Instance::new(def_id, substs))
239 traits::VtableAutoImpl(..) | traits::VtableParam(..) | traits::VtableTraitAlias(..) => None,
243 pub fn provide(providers: &mut ty::query::Providers<'_>) {
244 *providers = ty::query::Providers { resolve_instance, ..*providers };