]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/instance.rs
clean ClosureSubsts in rustc::ty
[rust.git] / src / librustc / ty / instance.rs
1 use crate::hir::Unsafety;
2 use crate::hir::def::Namespace;
3 use crate::hir::def_id::DefId;
4 use crate::ty::{self, Ty, PolyFnSig, TypeFoldable, SubstsRef, TyCtxt};
5 use crate::ty::print::{FmtPrinter, Printer};
6 use crate::traits;
7 use crate::middle::lang_items::DropInPlaceFnLangItem;
8 use rustc_target::spec::abi::Abi;
9 use rustc_macros::HashStable;
10
11 use std::fmt;
12 use std::iter;
13
14 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
15 pub struct Instance<'tcx> {
16     pub def: InstanceDef<'tcx>,
17     pub substs: SubstsRef<'tcx>,
18 }
19
20 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, HashStable)]
21 pub enum InstanceDef<'tcx> {
22     Item(DefId),
23     Intrinsic(DefId),
24
25     /// `<T as Trait>::method` where `method` receives unsizeable `self: Self`.
26     VtableShim(DefId),
27
28     /// `<fn() as FnTrait>::call_*`
29     /// `DefId` is `FnTrait::call_*`
30     FnPtrShim(DefId, Ty<'tcx>),
31
32     /// `<Trait as Trait>::fn`
33     Virtual(DefId, usize),
34
35     /// `<[mut closure] as FnOnce>::call_once`
36     ClosureOnceShim { call_once: DefId },
37
38     /// `drop_in_place::<T>; None` for empty drop glue.
39     DropGlue(DefId, Option<Ty<'tcx>>),
40
41     ///`<T as Clone>::clone` shim.
42     CloneShim(DefId, Ty<'tcx>),
43 }
44
45 impl<'tcx> Instance<'tcx> {
46     pub fn ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
47         let ty = tcx.type_of(self.def.def_id());
48         tcx.subst_and_normalize_erasing_regions(
49             self.substs,
50             ty::ParamEnv::reveal_all(),
51             &ty,
52         )
53     }
54
55     fn fn_sig_noadjust(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
56         let ty = self.ty(tcx);
57         match ty.kind {
58             ty::FnDef(..) |
59             // Shims currently have type FnPtr. Not sure this should remain.
60             ty::FnPtr(_) => ty.fn_sig(tcx),
61             ty::Closure(def_id, substs) => {
62                 let sig = substs.closure_sig(def_id, tcx);
63
64                 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
65                 sig.map_bound(|sig| tcx.mk_fn_sig(
66                     iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
67                     sig.output(),
68                     sig.c_variadic,
69                     sig.unsafety,
70                     sig.abi
71                 ))
72             }
73             ty::Generator(def_id, substs, _) => {
74                 let sig = substs.poly_sig(def_id, tcx);
75
76                 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
77                 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
78
79                 let pin_did = tcx.lang_items().pin_type().unwrap();
80                 let pin_adt_ref = tcx.adt_def(pin_did);
81                 let pin_substs = tcx.intern_substs(&[env_ty.into()]);
82                 let env_ty = tcx.mk_adt(pin_adt_ref, pin_substs);
83
84                 sig.map_bound(|sig| {
85                     let state_did = tcx.lang_items().gen_state().unwrap();
86                     let state_adt_ref = tcx.adt_def(state_did);
87                     let state_substs = tcx.intern_substs(&[
88                         sig.yield_ty.into(),
89                         sig.return_ty.into(),
90                     ]);
91                     let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
92
93                     tcx.mk_fn_sig(iter::once(env_ty),
94                         ret_ty,
95                         false,
96                         Unsafety::Normal,
97                         Abi::Rust
98                     )
99                 })
100             }
101             _ => bug!("unexpected type {:?} in Instance::fn_sig_noadjust", ty)
102         }
103     }
104
105     pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
106         let mut fn_sig = self.fn_sig_noadjust(tcx);
107         if let InstanceDef::VtableShim(..) = self.def {
108             // Modify fn(self, ...) to fn(self: *mut Self, ...)
109             fn_sig = fn_sig.map_bound(|mut fn_sig| {
110                 let mut inputs_and_output = fn_sig.inputs_and_output.to_vec();
111                 inputs_and_output[0] = tcx.mk_mut_ptr(inputs_and_output[0]);
112                 fn_sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
113                 fn_sig
114             });
115         }
116         fn_sig
117     }
118 }
119
120 impl<'tcx> InstanceDef<'tcx> {
121     #[inline]
122     pub fn def_id(&self) -> DefId {
123         match *self {
124             InstanceDef::Item(def_id) |
125             InstanceDef::VtableShim(def_id) |
126             InstanceDef::FnPtrShim(def_id, _) |
127             InstanceDef::Virtual(def_id, _) |
128             InstanceDef::Intrinsic(def_id, ) |
129             InstanceDef::ClosureOnceShim { call_once: def_id } |
130             InstanceDef::DropGlue(def_id, _) |
131             InstanceDef::CloneShim(def_id, _) => def_id
132         }
133     }
134
135     #[inline]
136     pub fn attrs(&self, tcx: TyCtxt<'tcx>) -> ty::Attributes<'tcx> {
137         tcx.get_attrs(self.def_id())
138     }
139
140     pub fn is_inline(&self, tcx: TyCtxt<'tcx>) -> bool {
141         use crate::hir::map::DefPathData;
142         let def_id = match *self {
143             ty::InstanceDef::Item(def_id) => def_id,
144             ty::InstanceDef::DropGlue(_, Some(_)) => return false,
145             _ => return true
146         };
147         match tcx.def_key(def_id).disambiguated_data.data {
148             DefPathData::Ctor | DefPathData::ClosureExpr => true,
149             _ => false
150         }
151     }
152
153     pub fn requires_local(&self, tcx: TyCtxt<'tcx>) -> bool {
154         if self.is_inline(tcx) {
155             return true
156         }
157         if let ty::InstanceDef::DropGlue(..) = *self {
158             // Drop glue wants to be instantiated at every codegen
159             // unit, but without an #[inline] hint. We should make this
160             // available to normal end-users.
161             return true
162         }
163         tcx.codegen_fn_attrs(self.def_id()).requests_inline()
164     }
165 }
166
167 impl<'tcx> fmt::Display for Instance<'tcx> {
168     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169         ty::tls::with(|tcx| {
170             let substs = tcx.lift(&self.substs).expect("could not lift for printing");
171             FmtPrinter::new(tcx, &mut *f, Namespace::ValueNS)
172                 .print_def_path(self.def_id(), substs)?;
173             Ok(())
174         })?;
175
176         match self.def {
177             InstanceDef::Item(_) => Ok(()),
178             InstanceDef::VtableShim(_) => {
179                 write!(f, " - shim(vtable)")
180             }
181             InstanceDef::Intrinsic(_) => {
182                 write!(f, " - intrinsic")
183             }
184             InstanceDef::Virtual(_, num) => {
185                 write!(f, " - shim(#{})", num)
186             }
187             InstanceDef::FnPtrShim(_, ty) => {
188                 write!(f, " - shim({:?})", ty)
189             }
190             InstanceDef::ClosureOnceShim { .. } => {
191                 write!(f, " - shim")
192             }
193             InstanceDef::DropGlue(_, ty) => {
194                 write!(f, " - shim({:?})", ty)
195             }
196             InstanceDef::CloneShim(_, ty) => {
197                 write!(f, " - shim({:?})", ty)
198             }
199         }
200     }
201 }
202
203 impl<'tcx> Instance<'tcx> {
204     pub fn new(def_id: DefId, substs: SubstsRef<'tcx>)
205                -> Instance<'tcx> {
206         assert!(!substs.has_escaping_bound_vars(),
207                 "substs of instance {:?} not normalized for codegen: {:?}",
208                 def_id, substs);
209         Instance { def: InstanceDef::Item(def_id), substs: substs }
210     }
211
212     pub fn mono(tcx: TyCtxt<'tcx>, def_id: DefId) -> Instance<'tcx> {
213         Instance::new(def_id, tcx.empty_substs_for_def_id(def_id))
214     }
215
216     #[inline]
217     pub fn def_id(&self) -> DefId {
218         self.def.def_id()
219     }
220
221     /// Resolves a `(def_id, substs)` pair to an (optional) instance -- most commonly,
222     /// this is used to find the precise code that will run for a trait method invocation,
223     /// if known.
224     ///
225     /// Returns `None` if we cannot resolve `Instance` to a specific instance.
226     /// For example, in a context like this,
227     ///
228     /// ```
229     /// fn foo<T: Debug>(t: T) { ... }
230     /// ```
231     ///
232     /// trying to resolve `Debug::fmt` applied to `T` will yield `None`, because we do not
233     /// know what code ought to run. (Note that this setting is also affected by the
234     /// `RevealMode` in the parameter environment.)
235     ///
236     /// Presuming that coherence and type-check have succeeded, if this method is invoked
237     /// in a monomorphic context (i.e., like during codegen), then it is guaranteed to return
238     /// `Some`.
239     pub fn resolve(
240         tcx: TyCtxt<'tcx>,
241         param_env: ty::ParamEnv<'tcx>,
242         def_id: DefId,
243         substs: SubstsRef<'tcx>,
244     ) -> Option<Instance<'tcx>> {
245         debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
246         let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) {
247             debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
248             let item = tcx.associated_item(def_id);
249             resolve_associated_item(tcx, &item, param_env, trait_def_id, substs)
250         } else {
251             let ty = tcx.type_of(def_id);
252             let item_type = tcx.subst_and_normalize_erasing_regions(
253                 substs,
254                 param_env,
255                 &ty,
256             );
257
258             let def = match item_type.kind {
259                 ty::FnDef(..) if {
260                     let f = item_type.fn_sig(tcx);
261                     f.abi() == Abi::RustIntrinsic ||
262                         f.abi() == Abi::PlatformIntrinsic
263                 } =>
264                 {
265                     debug!(" => intrinsic");
266                     ty::InstanceDef::Intrinsic(def_id)
267                 }
268                 _ => {
269                     if Some(def_id) == tcx.lang_items().drop_in_place_fn() {
270                         let ty = substs.type_at(0);
271                         if ty.needs_drop(tcx, ty::ParamEnv::reveal_all()) {
272                             debug!(" => nontrivial drop glue");
273                             ty::InstanceDef::DropGlue(def_id, Some(ty))
274                         } else {
275                             debug!(" => trivial drop glue");
276                             ty::InstanceDef::DropGlue(def_id, None)
277                         }
278                     } else {
279                         debug!(" => free item");
280                         ty::InstanceDef::Item(def_id)
281                     }
282                 }
283             };
284             Some(Instance {
285                 def: def,
286                 substs: substs
287             })
288         };
289         debug!("resolve(def_id={:?}, substs={:?}) = {:?}", def_id, substs, result);
290         result
291     }
292
293     pub fn resolve_for_vtable(
294         tcx: TyCtxt<'tcx>,
295         param_env: ty::ParamEnv<'tcx>,
296         def_id: DefId,
297         substs: SubstsRef<'tcx>,
298     ) -> Option<Instance<'tcx>> {
299         debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
300         let fn_sig = tcx.fn_sig(def_id);
301         let is_vtable_shim = fn_sig.inputs().skip_binder().len() > 0
302             && fn_sig.input(0).skip_binder().is_param(0)
303             && tcx.generics_of(def_id).has_self;
304         if is_vtable_shim {
305             debug!(" => associated item with unsizeable self: Self");
306             Some(Instance {
307                 def: InstanceDef::VtableShim(def_id),
308                 substs,
309             })
310         } else {
311             Instance::resolve(tcx, param_env, def_id, substs)
312         }
313     }
314
315     pub fn resolve_closure(
316         tcx: TyCtxt<'tcx>,
317         def_id: DefId,
318         substs: ty::ClosureSubsts<'tcx>,
319         requested_kind: ty::ClosureKind,
320     ) -> Instance<'tcx> {
321         let actual_kind = substs.closure_kind(def_id, tcx);
322
323         match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
324             Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, substs.substs),
325             _ => Instance::new(def_id, substs.substs)
326         }
327     }
328
329     pub fn resolve_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> {
330         let def_id = tcx.require_lang_item(DropInPlaceFnLangItem, None);
331         let substs = tcx.intern_substs(&[ty.into()]);
332         Instance::resolve(tcx, ty::ParamEnv::reveal_all(), def_id, substs).unwrap()
333     }
334
335     pub fn fn_once_adapter_instance(
336         tcx: TyCtxt<'tcx>,
337         closure_did: DefId,
338         substs: ty::SubstsRef<'tcx>,
339     ) -> Instance<'tcx> {
340         debug!("fn_once_adapter_shim({:?}, {:?})",
341                closure_did,
342                substs);
343         let fn_once = tcx.lang_items().fn_once_trait().unwrap();
344         let call_once = tcx.associated_items(fn_once)
345             .find(|it| it.kind == ty::AssocKind::Method)
346             .unwrap().def_id;
347         let def = ty::InstanceDef::ClosureOnceShim { call_once };
348
349         let self_ty = tcx.mk_closure(closure_did, substs);
350
351         let sig = substs.closure_sig(closure_did, tcx);
352         let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
353         assert_eq!(sig.inputs().len(), 1);
354         let substs = tcx.mk_substs_trait(self_ty, &[sig.inputs()[0].into()]);
355
356         debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
357         Instance { def, substs }
358     }
359
360     pub fn is_vtable_shim(&self) -> bool {
361         if let InstanceDef::VtableShim(..) = self.def {
362             true
363         } else {
364             false
365         }
366     }
367 }
368
369 fn resolve_associated_item<'tcx>(
370     tcx: TyCtxt<'tcx>,
371     trait_item: &ty::AssocItem,
372     param_env: ty::ParamEnv<'tcx>,
373     trait_id: DefId,
374     rcvr_substs: SubstsRef<'tcx>,
375 ) -> Option<Instance<'tcx>> {
376     let def_id = trait_item.def_id;
377     debug!("resolve_associated_item(trait_item={:?}, \
378             param_env={:?}, \
379             trait_id={:?}, \
380             rcvr_substs={:?})",
381             def_id, param_env, trait_id, rcvr_substs);
382
383     let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
384     let vtbl = tcx.codegen_fulfill_obligation((param_env, ty::Binder::bind(trait_ref)));
385
386     // Now that we know which impl is being used, we can dispatch to
387     // the actual function:
388     match vtbl {
389         traits::VtableImpl(impl_data) => {
390             let (def_id, substs) = traits::find_associated_item(
391                 tcx, param_env, trait_item, rcvr_substs, &impl_data);
392             let substs = tcx.erase_regions(&substs);
393             Some(ty::Instance::new(def_id, substs))
394         }
395         traits::VtableGenerator(generator_data) => {
396             Some(Instance {
397                 def: ty::InstanceDef::Item(generator_data.generator_def_id),
398                 substs: generator_data.substs.substs
399             })
400         }
401         traits::VtableClosure(closure_data) => {
402             let trait_closure_kind = tcx.lang_items().fn_trait_kind(trait_id).unwrap();
403             Some(Instance::resolve_closure(tcx, closure_data.closure_def_id, closure_data.substs,
404                                            trait_closure_kind))
405         }
406         traits::VtableFnPointer(ref data) => {
407             Some(Instance {
408                 def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
409                 substs: rcvr_substs
410             })
411         }
412         traits::VtableObject(ref data) => {
413             let index = tcx.get_vtable_index_of_object_method(data, def_id);
414             Some(Instance {
415                 def: ty::InstanceDef::Virtual(def_id, index),
416                 substs: rcvr_substs
417             })
418         }
419         traits::VtableBuiltin(..) => {
420             if tcx.lang_items().clone_trait().is_some() {
421                 Some(Instance {
422                     def: ty::InstanceDef::CloneShim(def_id, trait_ref.self_ty()),
423                     substs: rcvr_substs
424                 })
425             } else {
426                 None
427             }
428         }
429         traits::VtableAutoImpl(..) |
430         traits::VtableParam(..) |
431         traits::VtableTraitAlias(..) => None
432     }
433 }
434
435 fn needs_fn_once_adapter_shim(
436     actual_closure_kind: ty::ClosureKind,
437     trait_closure_kind: ty::ClosureKind,
438 ) -> Result<bool, ()> {
439     match (actual_closure_kind, trait_closure_kind) {
440         (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
441             (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
442             (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
443                 // No adapter needed.
444                 Ok(false)
445             }
446         (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
447             // The closure fn `llfn` is a `fn(&self, ...)`.  We want a
448             // `fn(&mut self, ...)`. In fact, at codegen time, these are
449             // basically the same thing, so we can just return llfn.
450             Ok(false)
451         }
452         (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
453             (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
454                 // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
455                 // self, ...)`.  We want a `fn(self, ...)`. We can produce
456                 // this by doing something like:
457                 //
458                 //     fn call_once(self, ...) { call_mut(&self, ...) }
459                 //     fn call_once(mut self, ...) { call_mut(&mut self, ...) }
460                 //
461                 // These are both the same at codegen time.
462                 Ok(true)
463         }
464         (ty::ClosureKind::FnMut, _) |
465         (ty::ClosureKind::FnOnce, _) => Err(())
466     }
467 }