1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use hir::def_id::DefId;
12 use ty::{self, Ty, TypeFoldable, Substs, TyCtxt};
13 use ty::subst::{Kind, Subst};
20 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
21 pub struct Instance<'tcx> {
22 pub def: InstanceDef<'tcx>,
23 pub substs: &'tcx Substs<'tcx>,
26 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
27 pub enum InstanceDef<'tcx> {
31 /// <fn() as FnTrait>::call_*
32 /// def-id is FnTrait::call_*
33 FnPtrShim(DefId, Ty<'tcx>),
35 /// <Trait as Trait>::fn
36 Virtual(DefId, usize),
38 /// <[mut closure] as FnOnce>::call_once
39 ClosureOnceShim { call_once: DefId },
41 /// drop_in_place::<T>; None for empty drop glue.
42 DropGlue(DefId, Option<Ty<'tcx>>),
44 ///`<T as Clone>::clone` shim.
45 CloneShim(DefId, Ty<'tcx>),
48 impl<'tcx> InstanceDef<'tcx> {
50 pub fn def_id(&self) -> DefId {
52 InstanceDef::Item(def_id) |
53 InstanceDef::FnPtrShim(def_id, _) |
54 InstanceDef::Virtual(def_id, _) |
55 InstanceDef::Intrinsic(def_id, ) |
56 InstanceDef::ClosureOnceShim { call_once: def_id } |
57 InstanceDef::DropGlue(def_id, _) |
58 InstanceDef::CloneShim(def_id, _) => def_id
63 pub fn def_ty<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
64 tcx.type_of(self.def_id())
68 pub fn attrs<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::Attributes<'tcx> {
69 tcx.get_attrs(self.def_id())
73 impl<'tcx> fmt::Display for Instance<'tcx> {
74 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
75 ppaux::parameterized(f, self.substs, self.def_id(), &[])?;
77 InstanceDef::Item(_) => Ok(()),
78 InstanceDef::Intrinsic(_) => {
79 write!(f, " - intrinsic")
81 InstanceDef::Virtual(_, num) => {
82 write!(f, " - shim(#{})", num)
84 InstanceDef::FnPtrShim(_, ty) => {
85 write!(f, " - shim({:?})", ty)
87 InstanceDef::ClosureOnceShim { .. } => {
90 InstanceDef::DropGlue(_, ty) => {
91 write!(f, " - shim({:?})", ty)
93 InstanceDef::CloneShim(_, ty) => {
94 write!(f, " - shim({:?})", ty)
100 impl<'a, 'b, 'tcx> Instance<'tcx> {
101 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>)
103 assert!(!substs.has_escaping_regions(),
104 "substs of instance {:?} not normalized for trans: {:?}",
106 Instance { def: InstanceDef::Item(def_id), substs: substs }
109 pub fn mono(tcx: TyCtxt<'a, 'tcx, 'b>, def_id: DefId) -> Instance<'tcx> {
110 Instance::new(def_id, tcx.global_tcx().empty_substs_for_def_id(def_id))
114 pub fn def_id(&self) -> DefId {
118 /// Resolve a (def_id, substs) pair to an (optional) instance -- most commonly,
119 /// this is used to find the precise code that will run for a trait method invocation,
122 /// Returns `None` if we cannot resolve `Instance` to a specific instance.
123 /// For example, in a context like this,
126 /// fn foo<T: Debug>(t: T) { ... }
129 /// trying to resolve `Debug::fmt` applied to `T` will yield `None`, because we do not
130 /// know what code ought to run. (Note that this setting is also affected by the
131 /// `RevealMode` in the parameter environment.)
133 /// Presuming that coherence and type-check have succeeded, if this method is invoked
134 /// in a monomorphic context (i.e., like during trans), then it is guaranteed to return
136 pub fn resolve(tcx: TyCtxt<'a, 'tcx, 'tcx>,
137 param_env: ty::ParamEnv<'tcx>,
139 substs: &'tcx Substs<'tcx>) -> Option<Instance<'tcx>> {
140 debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
141 let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) {
142 debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
143 let item = tcx.associated_item(def_id);
144 resolve_associated_item(tcx, &item, param_env, trait_def_id, substs)
146 let ty = tcx.type_of(def_id);
147 let item_type = tcx.trans_apply_param_substs_env(substs, param_env, &ty);
149 let def = match item_type.sty {
151 let f = item_type.fn_sig(tcx);
152 f.abi() == Abi::RustIntrinsic ||
153 f.abi() == Abi::PlatformIntrinsic
156 debug!(" => intrinsic");
157 ty::InstanceDef::Intrinsic(def_id)
160 if Some(def_id) == tcx.lang_items().drop_in_place_fn() {
161 let ty = substs.type_at(0);
162 if ty.needs_drop(tcx, ty::ParamEnv::empty(traits::Reveal::All)) {
163 debug!(" => nontrivial drop glue");
164 ty::InstanceDef::DropGlue(def_id, Some(ty))
166 debug!(" => trivial drop glue");
167 ty::InstanceDef::DropGlue(def_id, None)
170 debug!(" => free item");
171 ty::InstanceDef::Item(def_id)
180 debug!("resolve(def_id={:?}, substs={:?}) = {:?}", def_id, substs, result);
185 fn resolve_closure<'a, 'tcx>(
186 tcx: TyCtxt<'a, 'tcx, 'tcx>,
188 substs: ty::ClosureSubsts<'tcx>,
189 requested_kind: ty::ClosureKind)
192 let actual_kind = substs.closure_kind(def_id, tcx);
194 match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
195 Ok(true) => fn_once_adapter_instance(tcx, def_id, substs),
196 _ => Instance::new(def_id, substs.substs)
200 fn resolve_associated_item<'a, 'tcx>(
201 tcx: TyCtxt<'a, 'tcx, 'tcx>,
202 trait_item: &ty::AssociatedItem,
203 param_env: ty::ParamEnv<'tcx>,
205 rcvr_substs: &'tcx Substs<'tcx>
206 ) -> Option<Instance<'tcx>> {
207 let def_id = trait_item.def_id;
208 debug!("resolve_associated_item(trait_item={:?}, \
211 def_id, trait_id, rcvr_substs);
213 let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
214 let vtbl = tcx.trans_fulfill_obligation((param_env, ty::Binder(trait_ref)));
216 // Now that we know which impl is being used, we can dispatch to
217 // the actual function:
219 traits::VtableImpl(impl_data) => {
220 let (def_id, substs) = traits::find_associated_item(
221 tcx, trait_item, rcvr_substs, &impl_data);
222 let substs = tcx.erase_regions(&substs);
223 Some(ty::Instance::new(def_id, substs))
225 traits::VtableGenerator(closure_data) => {
227 def: ty::InstanceDef::Item(closure_data.closure_def_id),
228 substs: closure_data.substs.substs
231 traits::VtableClosure(closure_data) => {
232 let trait_closure_kind = tcx.lang_items().fn_trait_kind(trait_id).unwrap();
233 Some(resolve_closure(tcx, closure_data.closure_def_id, closure_data.substs,
236 traits::VtableFnPointer(ref data) => {
238 def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
242 traits::VtableObject(ref data) => {
243 let index = tcx.get_vtable_index_of_object_method(data, def_id);
245 def: ty::InstanceDef::Virtual(def_id, index),
249 traits::VtableBuiltin(..) => {
250 if let Some(_) = tcx.lang_items().clone_trait() {
252 def: ty::InstanceDef::CloneShim(def_id, trait_ref.self_ty()),
259 traits::VtableAutoImpl(..) | traits::VtableParam(..) => None
263 fn needs_fn_once_adapter_shim<'a, 'tcx>(actual_closure_kind: ty::ClosureKind,
264 trait_closure_kind: ty::ClosureKind)
267 match (actual_closure_kind, trait_closure_kind) {
268 (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
269 (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
270 (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
271 // No adapter needed.
274 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
275 // The closure fn `llfn` is a `fn(&self, ...)`. We want a
276 // `fn(&mut self, ...)`. In fact, at trans time, these are
277 // basically the same thing, so we can just return llfn.
280 (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
281 (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
282 // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
283 // self, ...)`. We want a `fn(self, ...)`. We can produce
284 // this by doing something like:
286 // fn call_once(self, ...) { call_mut(&self, ...) }
287 // fn call_once(mut self, ...) { call_mut(&mut self, ...) }
289 // These are both the same at trans time.
292 (ty::ClosureKind::FnMut, _) |
293 (ty::ClosureKind::FnOnce, _) => Err(())
297 fn fn_once_adapter_instance<'a, 'tcx>(
298 tcx: TyCtxt<'a, 'tcx, 'tcx>,
300 substs: ty::ClosureSubsts<'tcx>,
301 ) -> Instance<'tcx> {
302 debug!("fn_once_adapter_shim({:?}, {:?})",
305 let fn_once = tcx.lang_items().fn_once_trait().unwrap();
306 let call_once = tcx.associated_items(fn_once)
307 .find(|it| it.kind == ty::AssociatedKind::Method)
309 let def = ty::InstanceDef::ClosureOnceShim { call_once };
311 let self_ty = tcx.mk_closure_from_closure_substs(
312 closure_did, substs);
314 let sig = tcx.fn_sig(closure_did).subst(tcx, substs.substs);
315 let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
316 assert_eq!(sig.inputs().len(), 1);
317 let substs = tcx.mk_substs([
319 Kind::from(sig.inputs()[0]),
322 debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
323 Instance { def, substs }