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, _) if Some(def_id) == tcx.lang_items().count_code_region_fn() => {
39 debug!(" => injected placeholder function to be replaced");
40 ty::InstanceDef::InjectedCode(def_id)
42 ty::FnDef(def_id, substs) if Some(def_id) == tcx.lang_items().drop_in_place_fn() => {
43 let ty = substs.type_at(0);
45 if ty.needs_drop(tcx, param_env) {
46 // `DropGlue` requires a monomorphic aka concrete type.
51 debug!(" => nontrivial drop glue");
52 ty::InstanceDef::DropGlue(def_id, Some(ty))
54 debug!(" => trivial drop glue");
55 ty::InstanceDef::DropGlue(def_id, None)
59 debug!(" => free item");
60 ty::InstanceDef::Item(def_id)
63 Ok(Some(Instance { def, substs }))
65 debug!("resolve(def_id={:?}, substs={:?}) = {:?}", def_id, substs, result);
69 fn resolve_associated_item<'tcx>(
71 trait_item: &ty::AssocItem,
72 param_env: ty::ParamEnv<'tcx>,
74 rcvr_substs: SubstsRef<'tcx>,
75 ) -> Result<Option<Instance<'tcx>>, ErrorReported> {
76 let def_id = trait_item.def_id;
78 "resolve_associated_item(trait_item={:?}, \
82 def_id, param_env, trait_id, rcvr_substs
85 let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
86 let vtbl = tcx.codegen_fulfill_obligation((param_env, ty::Binder::bind(trait_ref)))?;
88 // Now that we know which impl is being used, we can dispatch to
89 // the actual function:
91 traits::ImplSourceUserDefined(impl_data) => {
93 "resolving ImplSourceUserDefined: {:?}, {:?}, {:?}, {:?}",
94 param_env, trait_item, rcvr_substs, impl_data
96 assert!(!rcvr_substs.needs_infer());
97 assert!(!trait_ref.needs_infer());
99 let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap();
100 let trait_def = tcx.trait_def(trait_def_id);
101 let leaf_def = trait_def
102 .ancestors(tcx, impl_data.impl_def_id)?
103 .leaf_def(tcx, trait_item.ident, trait_item.kind)
105 bug!("{:?} not found in {:?}", trait_item, impl_data.impl_def_id);
108 let substs = tcx.infer_ctxt().enter(|infcx| {
109 let param_env = param_env.with_reveal_all();
110 let substs = rcvr_substs.rebase_onto(tcx, trait_def_id, impl_data.substs);
111 let substs = translate_substs(
114 impl_data.impl_def_id,
116 leaf_def.defining_node,
118 infcx.tcx.erase_regions(&substs)
121 // Since this is a trait item, we need to see if the item is either a trait default item
122 // or a specialization because we can't resolve those unless we can `Reveal::All`.
123 // NOTE: This should be kept in sync with the similar code in
124 // `rustc_trait_selection::traits::project::assemble_candidates_from_impls()`.
125 let eligible = if leaf_def.is_final() {
126 // Non-specializable items are always projectable.
129 // Only reveal a specializable default if we're past type-checking
130 // and the obligation is monomorphic, otherwise passes such as
131 // transmute checking and polymorphic MIR optimizations could
132 // get a result which isn't correct for all monomorphizations.
133 if param_env.reveal == Reveal::All {
134 !trait_ref.still_further_specializable()
144 let substs = tcx.erase_regions(&substs);
146 // Check if we just resolved an associated `const` declaration from
147 // a `trait` to an associated `const` definition in an `impl`, where
148 // the definition in the `impl` has the wrong type (for which an
149 // error has already been/will be emitted elsewhere).
151 // NB: this may be expensive, we try to skip it in all the cases where
152 // we know the error would've been caught (e.g. in an upstream crate).
154 // A better approach might be to just introduce a query (returning
155 // `Result<(), ErrorReported>`) for the check that `rustc_typeck`
156 // performs (i.e. that the definition's type in the `impl` matches
157 // the declaration in the `trait`), so that we can cheaply check
158 // here if it failed, instead of approximating it.
159 if trait_item.kind == ty::AssocKind::Const
160 && trait_item.def_id != leaf_def.item.def_id
161 && leaf_def.item.def_id.is_local()
163 let normalized_type_of = |def_id, substs| {
164 tcx.subst_and_normalize_erasing_regions(substs, param_env, &tcx.type_of(def_id))
167 let original_ty = normalized_type_of(trait_item.def_id, rcvr_substs);
168 let resolved_ty = normalized_type_of(leaf_def.item.def_id, substs);
170 if original_ty != resolved_ty {
172 "Instance::resolve: inconsistent associated `const` type: \
173 was `{}: {}` but resolved to `{}: {}`",
174 tcx.def_path_str_with_substs(trait_item.def_id, rcvr_substs),
176 tcx.def_path_str_with_substs(leaf_def.item.def_id, substs),
179 let span = tcx.def_span(leaf_def.item.def_id);
180 tcx.sess.delay_span_bug(span, &msg);
182 return Err(ErrorReported);
186 Some(ty::Instance::new(leaf_def.item.def_id, substs))
188 traits::ImplSourceGenerator(generator_data) => Some(Instance {
189 def: ty::InstanceDef::Item(generator_data.generator_def_id),
190 substs: generator_data.substs,
192 traits::ImplSourceClosure(closure_data) => {
193 let trait_closure_kind = tcx.fn_trait_kind_from_lang_item(trait_id).unwrap();
194 Some(Instance::resolve_closure(
196 closure_data.closure_def_id,
201 traits::ImplSourceFnPointer(ref data) => {
202 // `FnPtrShim` requires a monomorphic aka concrete type.
203 if data.fn_ty.needs_subst() {
208 def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
212 traits::ImplSourceObject(ref data) => {
213 let index = traits::get_vtable_index_of_object_method(tcx, data, def_id);
214 Some(Instance { def: ty::InstanceDef::Virtual(def_id, index), substs: rcvr_substs })
216 traits::ImplSourceBuiltin(..) => {
217 if Some(trait_ref.def_id) == tcx.lang_items().clone_trait() {
218 // FIXME(eddyb) use lang items for methods instead of names.
219 let name = tcx.item_name(def_id);
220 if name == sym::clone {
221 let self_ty = trait_ref.self_ty();
223 // `CloneShim` requires a monomorphic aka concrete type.
224 if self_ty.needs_subst() {
229 def: ty::InstanceDef::CloneShim(def_id, self_ty),
233 assert_eq!(name, sym::clone_from);
235 // Use the default `fn clone_from` from `trait Clone`.
236 let substs = tcx.erase_regions(&rcvr_substs);
237 Some(ty::Instance::new(def_id, substs))
243 traits::ImplSourceAutoImpl(..)
244 | traits::ImplSourceParam(..)
245 | traits::ImplSourceTraitAlias(..)
246 | traits::ImplSourceDiscriminantKind(..) => None,
250 pub fn provide(providers: &mut ty::query::Providers<'_>) {
251 *providers = ty::query::Providers { resolve_instance, ..*providers };