1 // Copyright 2012-2014 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.
12 use rustc::hir::def_id::DefId;
13 use rustc::infer::TransNormalize;
14 use rustc::ty::fold::{TypeFolder, TypeFoldable};
15 use rustc::ty::subst::{Subst, Substs};
16 use rustc::ty::{self, Ty, TyCtxt};
17 use rustc::util::ppaux;
18 use rustc::util::common::MemoizationMap;
21 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
22 pub struct Instance<'tcx> {
24 pub substs: &'tcx Substs<'tcx>,
27 impl<'tcx> fmt::Display for Instance<'tcx> {
28 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
29 ppaux::parameterized(f, &self.substs, self.def, &[])
33 impl<'tcx> Instance<'tcx> {
34 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>)
36 assert!(substs.regions().all(|&r| r == ty::ReErased));
37 Instance { def: def_id, substs: substs }
39 pub fn mono<'a>(scx: &SharedCrateContext<'a, 'tcx>, def_id: DefId) -> Instance<'tcx> {
40 Instance::new(def_id, scx.empty_substs_for_def_id(def_id))
44 /// Monomorphizes a type from the AST by first applying the in-scope
45 /// substitutions and then normalizing any associated types.
46 pub fn apply_param_substs<'a, 'tcx, T>(scx: &SharedCrateContext<'a, 'tcx>,
47 param_substs: &Substs<'tcx>,
50 where T: TransNormalize<'tcx>
53 debug!("apply_param_substs(param_substs={:?}, value={:?})", param_substs, value);
54 let substituted = value.subst(tcx, param_substs);
55 let substituted = scx.tcx().erase_regions(&substituted);
56 AssociatedTypeNormalizer::new(scx).fold(&substituted)
60 /// Returns the normalized type of a struct field
61 pub fn field_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
62 param_substs: &Substs<'tcx>,
63 f: &'tcx ty::FieldDef)
66 tcx.normalize_associated_type(&f.ty(tcx, param_substs))
69 struct AssociatedTypeNormalizer<'a, 'b: 'a, 'gcx: 'b> {
70 shared: &'a SharedCrateContext<'b, 'gcx>,
73 impl<'a, 'b, 'gcx> AssociatedTypeNormalizer<'a, 'b, 'gcx> {
74 fn new(shared: &'a SharedCrateContext<'b, 'gcx>) -> Self {
75 AssociatedTypeNormalizer {
80 fn fold<T:TypeFoldable<'gcx>>(&mut self, value: &T) -> T {
81 if !value.has_projection_types() {
89 impl<'a, 'b, 'gcx> TypeFolder<'gcx, 'gcx> for AssociatedTypeNormalizer<'a, 'b, 'gcx> {
90 fn tcx<'c>(&'c self) -> TyCtxt<'c, 'gcx, 'gcx> {
94 fn fold_ty(&mut self, ty: Ty<'gcx>) -> Ty<'gcx> {
95 if !ty.has_projection_types() {
98 self.shared.project_cache().memoize(ty, || {
99 debug!("AssociatedTypeNormalizer: ty={:?}", ty);
100 self.shared.tcx().normalize_associated_type(&ty)