]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/tcx.rs
Add "Shallow" borrow kind
[rust.git] / src / librustc / mir / tcx.rs
1 // Copyright 2015 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.
4 //
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.
10
11 /*!
12  * Methods for the various MIR types. These are intended for use after
13  * building is complete.
14  */
15
16 use mir::*;
17 use ty::subst::{Subst, Substs};
18 use ty::{self, AdtDef, Ty, TyCtxt};
19 use hir;
20 use ty::util::IntTypeExt;
21
22 #[derive(Copy, Clone, Debug)]
23 pub enum PlaceTy<'tcx> {
24     /// Normal type.
25     Ty { ty: Ty<'tcx> },
26
27     /// Downcast to a particular variant of an enum.
28     Downcast { adt_def: &'tcx AdtDef,
29                substs: &'tcx Substs<'tcx>,
30                variant_index: usize },
31 }
32
33 impl<'a, 'gcx, 'tcx> PlaceTy<'tcx> {
34     pub fn from_ty(ty: Ty<'tcx>) -> PlaceTy<'tcx> {
35         PlaceTy::Ty { ty: ty }
36     }
37
38     pub fn to_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
39         match *self {
40             PlaceTy::Ty { ty } =>
41                 ty,
42             PlaceTy::Downcast { adt_def, substs, variant_index: _ } =>
43                 tcx.mk_adt(adt_def, substs),
44         }
45     }
46
47     pub fn projection_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
48                          elem: &PlaceElem<'tcx>)
49                          -> PlaceTy<'tcx>
50     {
51         match *elem {
52             ProjectionElem::Deref => {
53                 let ty = self.to_ty(tcx)
54                              .builtin_deref(true)
55                              .unwrap_or_else(|| {
56                                  bug!("deref projection of non-dereferencable ty {:?}", self)
57                              })
58                              .ty;
59                 PlaceTy::Ty {
60                     ty,
61                 }
62             }
63             ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } =>
64                 PlaceTy::Ty {
65                     ty: self.to_ty(tcx).builtin_index().unwrap()
66                 },
67             ProjectionElem::Subslice { from, to } => {
68                 let ty = self.to_ty(tcx);
69                 PlaceTy::Ty {
70                     ty: match ty.sty {
71                         ty::Array(inner, size) => {
72                             let size = size.unwrap_usize(tcx);
73                             let len = size - (from as u64) - (to as u64);
74                             tcx.mk_array(inner, len)
75                         }
76                         ty::Slice(..) => ty,
77                         _ => {
78                             bug!("cannot subslice non-array type: `{:?}`", self)
79                         }
80                     }
81                 }
82             }
83             ProjectionElem::Downcast(adt_def1, index) =>
84                 match self.to_ty(tcx).sty {
85                     ty::Adt(adt_def, substs) => {
86                         assert!(adt_def.is_enum());
87                         assert!(index < adt_def.variants.len());
88                         assert_eq!(adt_def, adt_def1);
89                         PlaceTy::Downcast { adt_def,
90                                              substs,
91                                              variant_index: index }
92                     }
93                     _ => {
94                         bug!("cannot downcast non-ADT type: `{:?}`", self)
95                     }
96                 },
97             ProjectionElem::Field(_, fty) => PlaceTy::Ty { ty: fty }
98         }
99     }
100 }
101
102 EnumTypeFoldableImpl! {
103     impl<'tcx> TypeFoldable<'tcx> for PlaceTy<'tcx> {
104         (PlaceTy::Ty) { ty },
105         (PlaceTy::Downcast) { adt_def, substs, variant_index },
106     }
107 }
108
109 impl<'tcx> Place<'tcx> {
110     pub fn ty<'a, 'gcx, D>(&self, local_decls: &D, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PlaceTy<'tcx>
111         where D: HasLocalDecls<'tcx>
112     {
113         match *self {
114             Place::Local(index) =>
115                 PlaceTy::Ty { ty: local_decls.local_decls()[index].ty },
116             Place::Promoted(ref data) => PlaceTy::Ty { ty: data.1 },
117             Place::Static(ref data) =>
118                 PlaceTy::Ty { ty: data.ty },
119             Place::Projection(ref proj) =>
120                 proj.base.ty(local_decls, tcx).projection_ty(tcx, &proj.elem),
121         }
122     }
123
124     /// If this is a field projection, and the field is being projected from a closure type,
125     /// then returns the index of the field being projected. Note that this closure will always
126     /// be `self` in the current MIR, because that is the only time we directly access the fields
127     /// of a closure type.
128     pub fn is_upvar_field_projection<'cx, 'gcx>(&self, mir: &'cx Mir<'tcx>,
129                                                 tcx: &TyCtxt<'cx, 'gcx, 'tcx>) -> Option<Field> {
130         let (place, by_ref) = if let Place::Projection(ref proj) = self {
131             if let ProjectionElem::Deref = proj.elem {
132                 (&proj.base, true)
133             } else {
134                 (self, false)
135             }
136         } else {
137             (self, false)
138         };
139
140         match place {
141             Place::Projection(ref proj) => match proj.elem {
142                 ProjectionElem::Field(field, _ty) => {
143                     let base_ty = proj.base.ty(mir, *tcx).to_ty(*tcx);
144
145                     if (base_ty.is_closure() || base_ty.is_generator()) &&
146                         (!by_ref || mir.upvar_decls[field.index()].by_ref)
147                     {
148                         Some(field)
149                     } else {
150                         None
151                     }
152                 },
153                 _ => None,
154             }\f
155             _ => None,
156         }
157     }
158 }
159
160 pub enum RvalueInitializationState {
161     Shallow,
162     Deep
163 }
164
165 impl<'tcx> Rvalue<'tcx> {
166     pub fn ty<'a, 'gcx, D>(&self, local_decls: &D, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>
167         where D: HasLocalDecls<'tcx>
168     {
169         match *self {
170             Rvalue::Use(ref operand) => operand.ty(local_decls, tcx),
171             Rvalue::Repeat(ref operand, count) => {
172                 tcx.mk_array(operand.ty(local_decls, tcx), count)
173             }
174             Rvalue::Ref(reg, bk, ref place) => {
175                 let place_ty = place.ty(local_decls, tcx).to_ty(tcx);
176                 tcx.mk_ref(reg,
177                     ty::TypeAndMut {
178                         ty: place_ty,
179                         mutbl: bk.to_mutbl_lossy()
180                     }
181                 )
182             }
183             Rvalue::Len(..) => tcx.types.usize,
184             Rvalue::Cast(.., ty) => ty,
185             Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
186                 let lhs_ty = lhs.ty(local_decls, tcx);
187                 let rhs_ty = rhs.ty(local_decls, tcx);
188                 op.ty(tcx, lhs_ty, rhs_ty)
189             }
190             Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
191                 let lhs_ty = lhs.ty(local_decls, tcx);
192                 let rhs_ty = rhs.ty(local_decls, tcx);
193                 let ty = op.ty(tcx, lhs_ty, rhs_ty);
194                 tcx.intern_tup(&[ty, tcx.types.bool])
195             }
196             Rvalue::UnaryOp(UnOp::Not, ref operand) |
197             Rvalue::UnaryOp(UnOp::Neg, ref operand) => {
198                 operand.ty(local_decls, tcx)
199             }
200             Rvalue::Discriminant(ref place) => {
201                 let ty = place.ty(local_decls, tcx).to_ty(tcx);
202                 if let ty::Adt(adt_def, _) = ty.sty {
203                     adt_def.repr.discr_type().to_ty(tcx)
204                 } else {
205                     // This can only be `0`, for now, so `u8` will suffice.
206                     tcx.types.u8
207                 }
208             }
209             Rvalue::NullaryOp(NullOp::Box, t) => tcx.mk_box(t),
210             Rvalue::NullaryOp(NullOp::SizeOf, _) => tcx.types.usize,
211             Rvalue::Aggregate(ref ak, ref ops) => {
212                 match **ak {
213                     AggregateKind::Array(ty) => {
214                         tcx.mk_array(ty, ops.len() as u64)
215                     }
216                     AggregateKind::Tuple => {
217                         tcx.mk_tup(ops.iter().map(|op| op.ty(local_decls, tcx)))
218                     }
219                     AggregateKind::Adt(def, _, substs, _, _) => {
220                         tcx.type_of(def.did).subst(tcx, substs)
221                     }
222                     AggregateKind::Closure(did, substs) => {
223                         tcx.mk_closure(did, substs)
224                     }
225                     AggregateKind::Generator(did, substs, movability) => {
226                         tcx.mk_generator(did, substs, movability)
227                     }
228                 }
229             }
230         }
231     }
232
233     #[inline]
234     /// Returns whether this rvalue is deeply initialized (most rvalues) or
235     /// whether its only shallowly initialized (`Rvalue::Box`).
236     pub fn initialization_state(&self) -> RvalueInitializationState {
237         match *self {
238             Rvalue::NullaryOp(NullOp::Box, _) => RvalueInitializationState::Shallow,
239             _ => RvalueInitializationState::Deep
240         }
241     }
242 }
243
244 impl<'tcx> Operand<'tcx> {
245     pub fn ty<'a, 'gcx, D>(&self, local_decls: &D, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>
246         where D: HasLocalDecls<'tcx>
247     {
248         match self {
249             &Operand::Copy(ref l) |
250             &Operand::Move(ref l) => l.ty(local_decls, tcx).to_ty(tcx),
251             &Operand::Constant(ref c) => c.ty,
252         }
253     }
254 }
255
256 impl<'tcx> BinOp {
257       pub fn ty<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
258                     lhs_ty: Ty<'tcx>,
259                     rhs_ty: Ty<'tcx>)
260                     -> Ty<'tcx> {
261         // FIXME: handle SIMD correctly
262         match self {
263             &BinOp::Add | &BinOp::Sub | &BinOp::Mul | &BinOp::Div | &BinOp::Rem |
264             &BinOp::BitXor | &BinOp::BitAnd | &BinOp::BitOr => {
265                 // these should be integers or floats of the same size.
266                 assert_eq!(lhs_ty, rhs_ty);
267                 lhs_ty
268             }
269             &BinOp::Shl | &BinOp::Shr | &BinOp::Offset => {
270                 lhs_ty // lhs_ty can be != rhs_ty
271             }
272             &BinOp::Eq | &BinOp::Lt | &BinOp::Le |
273             &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
274                 tcx.types.bool
275             }
276         }
277     }
278 }
279
280 impl BorrowKind {
281     pub fn to_mutbl_lossy(self) -> hir::Mutability {
282         match self {
283             BorrowKind::Mut { .. } => hir::MutMutable,
284             BorrowKind::Shared => hir::MutImmutable,
285
286             // We have no type corresponding to a unique imm borrow, so
287             // use `&mut`. It gives all the capabilities of an `&uniq`
288             // and hence is a safe "over approximation".
289             BorrowKind::Unique => hir::MutMutable,
290
291             // We have no type corresponding to a shallow borrow, so use
292             // `&` as an approximation.
293             BorrowKind::Shallow => hir::MutImmutable,
294         }
295     }
296 }
297
298 impl BinOp {
299     pub fn to_hir_binop(self) -> hir::BinOpKind {
300         match self {
301             BinOp::Add => hir::BinOpKind::Add,
302             BinOp::Sub => hir::BinOpKind::Sub,
303             BinOp::Mul => hir::BinOpKind::Mul,
304             BinOp::Div => hir::BinOpKind::Div,
305             BinOp::Rem => hir::BinOpKind::Rem,
306             BinOp::BitXor => hir::BinOpKind::BitXor,
307             BinOp::BitAnd => hir::BinOpKind::BitAnd,
308             BinOp::BitOr => hir::BinOpKind::BitOr,
309             BinOp::Shl => hir::BinOpKind::Shl,
310             BinOp::Shr => hir::BinOpKind::Shr,
311             BinOp::Eq => hir::BinOpKind::Eq,
312             BinOp::Ne => hir::BinOpKind::Ne,
313             BinOp::Lt => hir::BinOpKind::Lt,
314             BinOp::Gt => hir::BinOpKind::Gt,
315             BinOp::Le => hir::BinOpKind::Le,
316             BinOp::Ge => hir::BinOpKind::Ge,
317             BinOp::Offset => unreachable!()
318         }
319     }
320 }