]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/instance.rs
rustc_typeck to rustc_hir_analysis
[rust.git] / compiler / rustc_ty_utils / src / instance.rs
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};
10
11 fn resolve_instance<'tcx>(
12     tcx: TyCtxt<'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)));
19         }
20     }
21
22     inner_resolve_instance(tcx, param_env.and((ty::WithOptConstParam::unknown(did), substs)))
23 }
24
25 fn resolve_instance_of_const_arg<'tcx>(
26     tcx: TyCtxt<'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(
31         tcx,
32         param_env.and((
33             ty::WithOptConstParam { did: did.to_def_id(), const_param_did: Some(const_param_did) },
34             substs,
35         )),
36     )
37 }
38
39 fn inner_resolve_instance<'tcx>(
40     tcx: TyCtxt<'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();
44
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)
48     } else {
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);
51
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)
56             }
57             ty::FnDef(def_id, substs) if Some(def_id) == tcx.lang_items().drop_in_place_fn() => {
58                 let ty = substs.type_at(0);
59
60                 if ty.needs_drop(tcx, param_env) {
61                     debug!(" => nontrivial drop glue");
62                     match *ty.kind() {
63                         ty::Closure(..)
64                         | ty::Generator(..)
65                         | ty::Tuple(..)
66                         | ty::Adt(..)
67                         | ty::Dynamic(..)
68                         | ty::Array(..)
69                         | ty::Slice(..) => {}
70                         // Drop shims can only be built from ADTs.
71                         _ => return Ok(None),
72                     }
73
74                     ty::InstanceDef::DropGlue(def_id, Some(ty))
75                 } else {
76                     debug!(" => trivial drop glue");
77                     ty::InstanceDef::DropGlue(def_id, None)
78                 }
79             }
80             _ => {
81                 debug!(" => free item");
82                 ty::InstanceDef::Item(def)
83             }
84         };
85         Ok(Some(Instance { def, substs }))
86     };
87     debug!("inner_resolve_instance: result={:?}", result);
88     result
89 }
90
91 fn resolve_associated_item<'tcx>(
92     tcx: TyCtxt<'tcx>,
93     trait_item_id: DefId,
94     param_env: ty::ParamEnv<'tcx>,
95     trait_id: DefId,
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");
99
100     let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
101
102     let vtbl = match tcx.codegen_select_candidate((param_env, ty::Binder::dummy(trait_ref))) {
103         Ok(vtbl) => vtbl,
104         Err(CodegenObligationError::Ambiguity) => {
105             let reported = tcx.sess.delay_span_bug(
106                 tcx.def_span(trait_item_id),
107                 &format!(
108                     "encountered ambiguity selecting `{trait_ref:?}` during codegen, presuming due to \
109                      overflow or prior type error",
110                 ),
111             );
112             return Err(reported);
113         }
114         Err(CodegenObligationError::Unimplemented) => return Ok(None),
115         Err(CodegenObligationError::FulfillmentError) => return Ok(None),
116     };
117
118     // Now that we know which impl is being used, we can dispatch to
119     // the actual function:
120     Ok(match vtbl {
121         traits::ImplSource::UserDefined(impl_data) => {
122             debug!(
123                 "resolving ImplSource::UserDefined: {:?}, {:?}, {:?}, {:?}",
124                 param_env, trait_item_id, rcvr_substs, impl_data
125             );
126             assert!(!rcvr_substs.needs_infer());
127             assert!(!trait_ref.needs_infer());
128
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)
134                 .unwrap_or_else(|| {
135                     bug!("{:?} not found in {:?}", trait_item_id, impl_data.impl_def_id);
136                 });
137
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(
142                     &infcx,
143                     param_env,
144                     impl_data.impl_def_id,
145                     substs,
146                     leaf_def.defining_node,
147                 );
148                 infcx.tcx.erase_regions(substs)
149             });
150
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.
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                 if param_env.reveal() == Reveal::All {
164                     !trait_ref.still_further_specializable()
165                 } else {
166                     false
167                 }
168             };
169
170             if !eligible {
171                 return Ok(None);
172             }
173
174             // If the item does not have a value, then we cannot return an instance.
175             if !leaf_def.item.defaultness(tcx).has_value() {
176                 return Ok(None);
177             }
178
179             let substs = tcx.erase_regions(substs);
180
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).
185             //
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).
188             //
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()
197             {
198                 let normalized_type_of = |def_id, substs| {
199                     tcx.subst_and_normalize_erasing_regions(substs, param_env, tcx.type_of(def_id))
200                 };
201
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);
204
205                 if original_ty != resolved_ty {
206                     let msg = format!(
207                         "Instance::resolve: inconsistent associated `const` type: \
208                          was `{}: {}` but resolved to `{}: {}`",
209                         tcx.def_path_str_with_substs(trait_item_id, rcvr_substs),
210                         original_ty,
211                         tcx.def_path_str_with_substs(leaf_def.item.def_id, substs),
212                         resolved_ty,
213                     );
214                     let span = tcx.def_span(leaf_def.item.def_id);
215                     let reported = tcx.sess.delay_span_bug(span, &msg);
216
217                     return Err(reported);
218                 }
219             }
220
221             Some(ty::Instance::new(leaf_def.item.def_id, substs))
222         }
223         traits::ImplSource::Generator(generator_data) => Some(Instance {
224             def: ty::InstanceDef::Item(ty::WithOptConstParam::unknown(
225                 generator_data.generator_def_id,
226             )),
227             substs: generator_data.substs,
228         }),
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(
232                 tcx,
233                 closure_data.closure_def_id,
234                 closure_data.substs,
235                 trait_closure_kind,
236             )
237         }
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),
241                 substs: rcvr_substs,
242             }),
243             _ => None,
244         },
245         traits::ImplSource::Object(ref data) => {
246             if let Some(index) = traits::get_vtable_index_of_object_method(tcx, data, trait_item_id)
247             {
248                 Some(Instance {
249                     def: ty::InstanceDef::Virtual(trait_item_id, index),
250                     substs: rcvr_substs,
251                 })
252             } else {
253                 None
254             }
255         }
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();
262
263                     let is_copy = self_ty.is_copy_modulo_regions(tcx.at(DUMMY_SP), param_env);
264                     match self_ty.kind() {
265                         _ if is_copy => (),
266                         ty::Generator(..)
267                         | ty::GeneratorWitness(..)
268                         | ty::Closure(..)
269                         | ty::Tuple(..) => {}
270                         _ => return Ok(None),
271                     };
272
273                     Some(Instance {
274                         def: ty::InstanceDef::CloneShim(trait_item_id, self_ty),
275                         substs: rcvr_substs,
276                     })
277                 } else {
278                     assert_eq!(name, sym::clone_from);
279
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))
283                 }
284             } else {
285                 None
286             }
287         }
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,
296     })
297 }
298
299 pub fn provide(providers: &mut ty::query::Providers) {
300     *providers =
301         ty::query::Providers { resolve_instance, resolve_instance_of_const_arg, ..*providers };
302 }