]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/instance.rs
normalize receiver substs and erase the regions
[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;
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(
48             tcx,
49             def.did,
50             param_env,
51             trait_def_id,
52             tcx.normalize_erasing_regions(param_env, substs),
53         )
54     } else {
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);
57
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)
62             }
63             ty::FnDef(def_id, substs) if Some(def_id) == tcx.lang_items().drop_in_place_fn() => {
64                 let ty = substs.type_at(0);
65
66                 if ty.needs_drop(tcx, param_env) {
67                     debug!(" => nontrivial drop glue");
68                     match *ty.kind() {
69                         ty::Closure(..)
70                         | ty::Generator(..)
71                         | ty::Tuple(..)
72                         | ty::Adt(..)
73                         | ty::Dynamic(..)
74                         | ty::Array(..)
75                         | ty::Slice(..) => {}
76                         // Drop shims can only be built from ADTs.
77                         _ => return Ok(None),
78                     }
79
80                     ty::InstanceDef::DropGlue(def_id, Some(ty))
81                 } else {
82                     debug!(" => trivial drop glue");
83                     ty::InstanceDef::DropGlue(def_id, None)
84                 }
85             }
86             _ => {
87                 debug!(" => free item");
88                 ty::InstanceDef::Item(def)
89             }
90         };
91         Ok(Some(Instance { def, substs }))
92     };
93     debug!("inner_resolve_instance: result={:?}", result);
94     result
95 }
96
97 fn resolve_associated_item<'tcx>(
98     tcx: TyCtxt<'tcx>,
99     trait_item_id: DefId,
100     param_env: ty::ParamEnv<'tcx>,
101     trait_id: DefId,
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");
105
106     let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
107
108     let vtbl = match tcx.codegen_select_candidate((param_env, ty::Binder::dummy(trait_ref))) {
109         Ok(vtbl) => vtbl,
110         Err(CodegenObligationError::Ambiguity) => {
111             let reported = tcx.sess.delay_span_bug(
112                 tcx.def_span(trait_item_id),
113                 &format!(
114                     "encountered ambiguity selecting `{trait_ref:?}` during codegen, presuming due to \
115                      overflow or prior type error",
116                 ),
117             );
118             return Err(reported);
119         }
120         Err(CodegenObligationError::Unimplemented) => return Ok(None),
121         Err(CodegenObligationError::FulfillmentError) => return Ok(None),
122     };
123
124     // Now that we know which impl is being used, we can dispatch to
125     // the actual function:
126     Ok(match vtbl {
127         traits::ImplSource::UserDefined(impl_data) => {
128             debug!(
129                 "resolving ImplSource::UserDefined: {:?}, {:?}, {:?}, {:?}",
130                 param_env, trait_item_id, rcvr_substs, impl_data
131             );
132             assert!(!rcvr_substs.needs_infer());
133             assert!(!trait_ref.needs_infer());
134
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)
140                 .unwrap_or_else(|| {
141                     bug!("{:?} not found in {:?}", trait_item_id, impl_data.impl_def_id);
142                 });
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(
147                 &infcx,
148                 param_env,
149                 impl_data.impl_def_id,
150                 substs,
151                 leaf_def.defining_node,
152             );
153             let substs = infcx.tcx.erase_regions(substs);
154
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.
161                 true
162             } else {
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()
169                 } else {
170                     false
171                 }
172             };
173
174             if !eligible {
175                 return Ok(None);
176             }
177
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",
183                 );
184                 return Err(guard);
185             }
186
187             let substs = tcx.erase_regions(substs);
188
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()
196             {
197                 tcx.compare_assoc_const_impl_item_with_trait_item((
198                     leaf_def_item,
199                     trait_item_id,
200                 ))?;
201             }
202
203             Some(ty::Instance::new(leaf_def.item.def_id, substs))
204         }
205         traits::ImplSource::Generator(generator_data) => Some(Instance {
206             def: ty::InstanceDef::Item(ty::WithOptConstParam::unknown(
207                 generator_data.generator_def_id,
208             )),
209             substs: generator_data.substs,
210         }),
211         traits::ImplSource::Future(future_data) => Some(Instance {
212             def: ty::InstanceDef::Item(ty::WithOptConstParam::unknown(
213                 future_data.generator_def_id,
214             )),
215             substs: future_data.substs,
216         }),
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(
220                 tcx,
221                 closure_data.closure_def_id,
222                 closure_data.substs,
223                 trait_closure_kind,
224             )
225         }
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),
229                 substs: rcvr_substs,
230             }),
231             _ => None,
232         },
233         traits::ImplSource::Object(ref data) => {
234             if let Some(index) = traits::get_vtable_index_of_object_method(tcx, data, trait_item_id)
235             {
236                 Some(Instance {
237                     def: ty::InstanceDef::Virtual(trait_item_id, index),
238                     substs: rcvr_substs,
239                 })
240             } else {
241                 None
242             }
243         }
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();
250
251                     let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env);
252                     match self_ty.kind() {
253                         _ if is_copy => (),
254                         ty::Generator(..)
255                         | ty::GeneratorWitness(..)
256                         | ty::Closure(..)
257                         | ty::Tuple(..) => {}
258                         _ => return Ok(None),
259                     };
260
261                     Some(Instance {
262                         def: ty::InstanceDef::CloneShim(trait_item_id, self_ty),
263                         substs: rcvr_substs,
264                     })
265                 } else {
266                     assert_eq!(name, sym::clone_from);
267
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))
271                 }
272             } else {
273                 None
274             }
275         }
276         traits::ImplSource::AutoImpl(..)
277         | traits::ImplSource::Param(..)
278         | traits::ImplSource::TraitAlias(..)
279         | traits::ImplSource::TraitUpcasting(_)
280         | traits::ImplSource::ConstDestruct(_) => None,
281     })
282 }
283
284 pub fn provide(providers: &mut ty::query::Providers) {
285     *providers =
286         ty::query::Providers { resolve_instance, resolve_instance_of_const_arg, ..*providers };
287 }