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};
20 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
21 pub struct Instance<'tcx> {
22 pub def: InstanceDef<'tcx>,
23 pub substs: &'tcx Substs<'tcx>,
26 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
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<'a, 'tcx> Instance<'tcx> {
50 tcx: TyCtxt<'a, 'tcx, 'tcx>)
53 let ty = tcx.type_of(self.def.def_id());
54 tcx.trans_apply_param_substs(self.substs, &ty)
58 impl<'tcx> InstanceDef<'tcx> {
60 pub fn def_id(&self) -> DefId {
62 InstanceDef::Item(def_id) |
63 InstanceDef::FnPtrShim(def_id, _) |
64 InstanceDef::Virtual(def_id, _) |
65 InstanceDef::Intrinsic(def_id, ) |
66 InstanceDef::ClosureOnceShim { call_once: def_id } |
67 InstanceDef::DropGlue(def_id, _) |
68 InstanceDef::CloneShim(def_id, _) => def_id
73 pub fn attrs<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::Attributes<'tcx> {
74 tcx.get_attrs(self.def_id())
79 tcx: TyCtxt<'a, 'tcx, 'tcx>
81 use hir::map::DefPathData;
82 let def_id = match *self {
83 ty::InstanceDef::Item(def_id) => def_id,
84 ty::InstanceDef::DropGlue(_, Some(_)) => return false,
87 match tcx.def_key(def_id).disambiguated_data.data {
88 DefPathData::StructCtor |
89 DefPathData::EnumVariant(..) |
90 DefPathData::ClosureExpr => true,
95 pub fn requires_local<'a>(
97 tcx: TyCtxt<'a, 'tcx, 'tcx>
99 if self.is_inline(tcx) {
102 if let ty::InstanceDef::DropGlue(..) = *self {
103 // Drop glue wants to be instantiated at every translation
104 // unit, but without an #[inline] hint. We should make this
105 // available to normal end-users.
108 let trans_fn_attrs = tcx.trans_fn_attrs(self.def_id());
109 trans_fn_attrs.requests_inline() || tcx.is_const_fn(self.def_id())
113 impl<'tcx> fmt::Display for Instance<'tcx> {
114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115 ppaux::parameterized(f, self.substs, self.def_id(), &[])?;
117 InstanceDef::Item(_) => Ok(()),
118 InstanceDef::Intrinsic(_) => {
119 write!(f, " - intrinsic")
121 InstanceDef::Virtual(_, num) => {
122 write!(f, " - shim(#{})", num)
124 InstanceDef::FnPtrShim(_, ty) => {
125 write!(f, " - shim({:?})", ty)
127 InstanceDef::ClosureOnceShim { .. } => {
130 InstanceDef::DropGlue(_, ty) => {
131 write!(f, " - shim({:?})", ty)
133 InstanceDef::CloneShim(_, ty) => {
134 write!(f, " - shim({:?})", ty)
140 impl<'a, 'b, 'tcx> Instance<'tcx> {
141 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>)
143 assert!(!substs.has_escaping_regions(),
144 "substs of instance {:?} not normalized for trans: {:?}",
146 Instance { def: InstanceDef::Item(def_id), substs: substs }
149 pub fn mono(tcx: TyCtxt<'a, 'tcx, 'b>, def_id: DefId) -> Instance<'tcx> {
150 Instance::new(def_id, tcx.global_tcx().empty_substs_for_def_id(def_id))
154 pub fn def_id(&self) -> DefId {
158 /// Resolve a (def_id, substs) pair to an (optional) instance -- most commonly,
159 /// this is used to find the precise code that will run for a trait method invocation,
162 /// Returns `None` if we cannot resolve `Instance` to a specific instance.
163 /// For example, in a context like this,
166 /// fn foo<T: Debug>(t: T) { ... }
169 /// trying to resolve `Debug::fmt` applied to `T` will yield `None`, because we do not
170 /// know what code ought to run. (Note that this setting is also affected by the
171 /// `RevealMode` in the parameter environment.)
173 /// Presuming that coherence and type-check have succeeded, if this method is invoked
174 /// in a monomorphic context (i.e., like during trans), then it is guaranteed to return
176 pub fn resolve(tcx: TyCtxt<'a, 'tcx, 'tcx>,
177 param_env: ty::ParamEnv<'tcx>,
179 substs: &'tcx Substs<'tcx>) -> Option<Instance<'tcx>> {
180 debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
181 let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) {
182 debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
183 let item = tcx.associated_item(def_id);
184 resolve_associated_item(tcx, &item, param_env, trait_def_id, substs)
186 let ty = tcx.type_of(def_id);
187 let item_type = tcx.trans_apply_param_substs_env(substs, param_env, &ty);
189 let def = match item_type.sty {
191 let f = item_type.fn_sig(tcx);
192 f.abi() == Abi::RustIntrinsic ||
193 f.abi() == Abi::PlatformIntrinsic
196 debug!(" => intrinsic");
197 ty::InstanceDef::Intrinsic(def_id)
200 if Some(def_id) == tcx.lang_items().drop_in_place_fn() {
201 let ty = substs.type_at(0);
202 if ty.needs_drop(tcx, ty::ParamEnv::reveal_all()) {
203 debug!(" => nontrivial drop glue");
204 ty::InstanceDef::DropGlue(def_id, Some(ty))
206 debug!(" => trivial drop glue");
207 ty::InstanceDef::DropGlue(def_id, None)
210 debug!(" => free item");
211 ty::InstanceDef::Item(def_id)
220 debug!("resolve(def_id={:?}, substs={:?}) = {:?}", def_id, substs, result);
224 pub fn resolve_closure(
225 tcx: TyCtxt<'a, 'tcx, 'tcx>,
227 substs: ty::ClosureSubsts<'tcx>,
228 requested_kind: ty::ClosureKind)
231 let actual_kind = substs.closure_kind(def_id, tcx);
233 match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
234 Ok(true) => fn_once_adapter_instance(tcx, def_id, substs),
235 _ => Instance::new(def_id, substs.substs)
240 fn resolve_associated_item<'a, 'tcx>(
241 tcx: TyCtxt<'a, 'tcx, 'tcx>,
242 trait_item: &ty::AssociatedItem,
243 param_env: ty::ParamEnv<'tcx>,
245 rcvr_substs: &'tcx Substs<'tcx>,
246 ) -> Option<Instance<'tcx>> {
247 let def_id = trait_item.def_id;
248 debug!("resolve_associated_item(trait_item={:?}, \
251 def_id, trait_id, rcvr_substs);
253 let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
254 let vtbl = tcx.trans_fulfill_obligation((param_env, ty::Binder(trait_ref)));
256 // Now that we know which impl is being used, we can dispatch to
257 // the actual function:
259 traits::VtableImpl(impl_data) => {
260 let (def_id, substs) = traits::find_associated_item(
261 tcx, trait_item, rcvr_substs, &impl_data);
262 let substs = tcx.erase_regions(&substs);
263 Some(ty::Instance::new(def_id, substs))
265 traits::VtableGenerator(closure_data) => {
267 def: ty::InstanceDef::Item(closure_data.closure_def_id),
268 substs: closure_data.substs.substs
271 traits::VtableClosure(closure_data) => {
272 let trait_closure_kind = tcx.lang_items().fn_trait_kind(trait_id).unwrap();
273 Some(Instance::resolve_closure(tcx, closure_data.closure_def_id, closure_data.substs,
276 traits::VtableFnPointer(ref data) => {
278 def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
282 traits::VtableObject(ref data) => {
283 let index = tcx.get_vtable_index_of_object_method(data, def_id);
285 def: ty::InstanceDef::Virtual(def_id, index),
289 traits::VtableBuiltin(..) => {
290 if let Some(_) = tcx.lang_items().clone_trait() {
292 def: ty::InstanceDef::CloneShim(def_id, trait_ref.self_ty()),
299 traits::VtableAutoImpl(..) | traits::VtableParam(..) => None
303 fn needs_fn_once_adapter_shim<'a, 'tcx>(actual_closure_kind: ty::ClosureKind,
304 trait_closure_kind: ty::ClosureKind)
307 match (actual_closure_kind, trait_closure_kind) {
308 (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
309 (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
310 (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
311 // No adapter needed.
314 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
315 // The closure fn `llfn` is a `fn(&self, ...)`. We want a
316 // `fn(&mut self, ...)`. In fact, at trans time, these are
317 // basically the same thing, so we can just return llfn.
320 (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
321 (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
322 // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
323 // self, ...)`. We want a `fn(self, ...)`. We can produce
324 // this by doing something like:
326 // fn call_once(self, ...) { call_mut(&self, ...) }
327 // fn call_once(mut self, ...) { call_mut(&mut self, ...) }
329 // These are both the same at trans time.
332 (ty::ClosureKind::FnMut, _) |
333 (ty::ClosureKind::FnOnce, _) => Err(())
337 fn fn_once_adapter_instance<'a, 'tcx>(
338 tcx: TyCtxt<'a, 'tcx, 'tcx>,
340 substs: ty::ClosureSubsts<'tcx>,
341 ) -> Instance<'tcx> {
342 debug!("fn_once_adapter_shim({:?}, {:?})",
345 let fn_once = tcx.lang_items().fn_once_trait().unwrap();
346 let call_once = tcx.associated_items(fn_once)
347 .find(|it| it.kind == ty::AssociatedKind::Method)
349 let def = ty::InstanceDef::ClosureOnceShim { call_once };
351 let self_ty = tcx.mk_closure_from_closure_substs(
352 closure_did, substs);
354 let sig = substs.closure_sig(closure_did, tcx);
355 let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
356 assert_eq!(sig.inputs().len(), 1);
357 let substs = tcx.mk_substs([Kind::from(self_ty), sig.inputs()[0].into()].iter().cloned());
359 debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
360 Instance { def, substs }