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.subst_and_normalize_erasing_regions(
56 ty::ParamEnv::reveal_all(),
62 impl<'tcx> InstanceDef<'tcx> {
64 pub fn def_id(&self) -> DefId {
66 InstanceDef::Item(def_id) |
67 InstanceDef::FnPtrShim(def_id, _) |
68 InstanceDef::Virtual(def_id, _) |
69 InstanceDef::Intrinsic(def_id, ) |
70 InstanceDef::ClosureOnceShim { call_once: def_id } |
71 InstanceDef::DropGlue(def_id, _) |
72 InstanceDef::CloneShim(def_id, _) => def_id
77 pub fn attrs<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::Attributes<'tcx> {
78 tcx.get_attrs(self.def_id())
83 tcx: TyCtxt<'a, 'tcx, 'tcx>
85 use hir::map::DefPathData;
86 let def_id = match *self {
87 ty::InstanceDef::Item(def_id) => def_id,
88 ty::InstanceDef::DropGlue(_, Some(_)) => return false,
91 match tcx.def_key(def_id).disambiguated_data.data {
92 DefPathData::StructCtor |
93 DefPathData::EnumVariant(..) |
94 DefPathData::ClosureExpr => true,
99 pub fn requires_local<'a>(
101 tcx: TyCtxt<'a, 'tcx, 'tcx>
103 if self.is_inline(tcx) {
106 if let ty::InstanceDef::DropGlue(..) = *self {
107 // Drop glue wants to be instantiated at every translation
108 // unit, but without an #[inline] hint. We should make this
109 // available to normal end-users.
112 let trans_fn_attrs = tcx.trans_fn_attrs(self.def_id());
113 trans_fn_attrs.requests_inline() || tcx.is_const_fn(self.def_id())
117 impl<'tcx> fmt::Display for Instance<'tcx> {
118 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
119 ppaux::parameterized(f, self.substs, self.def_id(), &[])?;
121 InstanceDef::Item(_) => Ok(()),
122 InstanceDef::Intrinsic(_) => {
123 write!(f, " - intrinsic")
125 InstanceDef::Virtual(_, num) => {
126 write!(f, " - shim(#{})", num)
128 InstanceDef::FnPtrShim(_, ty) => {
129 write!(f, " - shim({:?})", ty)
131 InstanceDef::ClosureOnceShim { .. } => {
134 InstanceDef::DropGlue(_, ty) => {
135 write!(f, " - shim({:?})", ty)
137 InstanceDef::CloneShim(_, ty) => {
138 write!(f, " - shim({:?})", ty)
144 impl<'a, 'b, 'tcx> Instance<'tcx> {
145 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>)
147 assert!(!substs.has_escaping_regions(),
148 "substs of instance {:?} not normalized for trans: {:?}",
150 Instance { def: InstanceDef::Item(def_id), substs: substs }
153 pub fn mono(tcx: TyCtxt<'a, 'tcx, 'b>, def_id: DefId) -> Instance<'tcx> {
154 Instance::new(def_id, tcx.global_tcx().empty_substs_for_def_id(def_id))
158 pub fn def_id(&self) -> DefId {
162 /// Resolve a (def_id, substs) pair to an (optional) instance -- most commonly,
163 /// this is used to find the precise code that will run for a trait method invocation,
166 /// Returns `None` if we cannot resolve `Instance` to a specific instance.
167 /// For example, in a context like this,
170 /// fn foo<T: Debug>(t: T) { ... }
173 /// trying to resolve `Debug::fmt` applied to `T` will yield `None`, because we do not
174 /// know what code ought to run. (Note that this setting is also affected by the
175 /// `RevealMode` in the parameter environment.)
177 /// Presuming that coherence and type-check have succeeded, if this method is invoked
178 /// in a monomorphic context (i.e., like during trans), then it is guaranteed to return
180 pub fn resolve(tcx: TyCtxt<'a, 'tcx, 'tcx>,
181 param_env: ty::ParamEnv<'tcx>,
183 substs: &'tcx Substs<'tcx>) -> Option<Instance<'tcx>> {
184 debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
185 let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) {
186 debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
187 let item = tcx.associated_item(def_id);
188 resolve_associated_item(tcx, &item, param_env, trait_def_id, substs)
190 let ty = tcx.type_of(def_id);
191 let item_type = tcx.subst_and_normalize_erasing_regions(
197 let def = match item_type.sty {
199 let f = item_type.fn_sig(tcx);
200 f.abi() == Abi::RustIntrinsic ||
201 f.abi() == Abi::PlatformIntrinsic
204 debug!(" => intrinsic");
205 ty::InstanceDef::Intrinsic(def_id)
208 if Some(def_id) == tcx.lang_items().drop_in_place_fn() {
209 let ty = substs.type_at(0);
210 if ty.needs_drop(tcx, ty::ParamEnv::reveal_all()) {
211 debug!(" => nontrivial drop glue");
212 ty::InstanceDef::DropGlue(def_id, Some(ty))
214 debug!(" => trivial drop glue");
215 ty::InstanceDef::DropGlue(def_id, None)
218 debug!(" => free item");
219 ty::InstanceDef::Item(def_id)
228 debug!("resolve(def_id={:?}, substs={:?}) = {:?}", def_id, substs, result);
232 pub fn resolve_closure(
233 tcx: TyCtxt<'a, 'tcx, 'tcx>,
235 substs: ty::ClosureSubsts<'tcx>,
236 requested_kind: ty::ClosureKind)
239 let actual_kind = substs.closure_kind(def_id, tcx);
241 match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
242 Ok(true) => fn_once_adapter_instance(tcx, def_id, substs),
243 _ => Instance::new(def_id, substs.substs)
248 fn resolve_associated_item<'a, 'tcx>(
249 tcx: TyCtxt<'a, 'tcx, 'tcx>,
250 trait_item: &ty::AssociatedItem,
251 param_env: ty::ParamEnv<'tcx>,
253 rcvr_substs: &'tcx Substs<'tcx>,
254 ) -> Option<Instance<'tcx>> {
255 let def_id = trait_item.def_id;
256 debug!("resolve_associated_item(trait_item={:?}, \
259 def_id, trait_id, rcvr_substs);
261 let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
262 let vtbl = tcx.trans_fulfill_obligation((param_env, ty::Binder(trait_ref)));
264 // Now that we know which impl is being used, we can dispatch to
265 // the actual function:
267 traits::VtableImpl(impl_data) => {
268 let (def_id, substs) = traits::find_associated_item(
269 tcx, trait_item, rcvr_substs, &impl_data);
270 let substs = tcx.erase_regions(&substs);
271 Some(ty::Instance::new(def_id, substs))
273 traits::VtableGenerator(closure_data) => {
275 def: ty::InstanceDef::Item(closure_data.closure_def_id),
276 substs: closure_data.substs.substs
279 traits::VtableClosure(closure_data) => {
280 let trait_closure_kind = tcx.lang_items().fn_trait_kind(trait_id).unwrap();
281 Some(Instance::resolve_closure(tcx, closure_data.closure_def_id, closure_data.substs,
284 traits::VtableFnPointer(ref data) => {
286 def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
290 traits::VtableObject(ref data) => {
291 let index = tcx.get_vtable_index_of_object_method(data, def_id);
293 def: ty::InstanceDef::Virtual(def_id, index),
297 traits::VtableBuiltin(..) => {
298 if let Some(_) = tcx.lang_items().clone_trait() {
300 def: ty::InstanceDef::CloneShim(def_id, trait_ref.self_ty()),
307 traits::VtableAutoImpl(..) | traits::VtableParam(..) => None
311 fn needs_fn_once_adapter_shim<'a, 'tcx>(actual_closure_kind: ty::ClosureKind,
312 trait_closure_kind: ty::ClosureKind)
315 match (actual_closure_kind, trait_closure_kind) {
316 (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
317 (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
318 (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
319 // No adapter needed.
322 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
323 // The closure fn `llfn` is a `fn(&self, ...)`. We want a
324 // `fn(&mut self, ...)`. In fact, at trans time, these are
325 // basically the same thing, so we can just return llfn.
328 (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
329 (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
330 // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
331 // self, ...)`. We want a `fn(self, ...)`. We can produce
332 // this by doing something like:
334 // fn call_once(self, ...) { call_mut(&self, ...) }
335 // fn call_once(mut self, ...) { call_mut(&mut self, ...) }
337 // These are both the same at trans time.
340 (ty::ClosureKind::FnMut, _) |
341 (ty::ClosureKind::FnOnce, _) => Err(())
345 fn fn_once_adapter_instance<'a, 'tcx>(
346 tcx: TyCtxt<'a, 'tcx, 'tcx>,
348 substs: ty::ClosureSubsts<'tcx>,
349 ) -> Instance<'tcx> {
350 debug!("fn_once_adapter_shim({:?}, {:?})",
353 let fn_once = tcx.lang_items().fn_once_trait().unwrap();
354 let call_once = tcx.associated_items(fn_once)
355 .find(|it| it.kind == ty::AssociatedKind::Method)
357 let def = ty::InstanceDef::ClosureOnceShim { call_once };
359 let self_ty = tcx.mk_closure_from_closure_substs(
360 closure_did, substs);
362 let sig = substs.closure_sig(closure_did, tcx);
363 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
364 assert_eq!(sig.inputs().len(), 1);
365 let substs = tcx.mk_substs([Kind::from(self_ty), sig.inputs()[0].into()].iter().cloned());
367 debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
368 Instance { def, substs }