]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/cast.rs
forgot about multivariant enum casts
[rust.git] / src / librustc_mir / interpret / cast.rs
1 use rustc::ty::{self, Ty, TypeAndMut};
2 use rustc::ty::layout::{self, TyLayout, Size};
3 use rustc::ty::adjustment::{PointerCast};
4 use syntax::ast::{FloatTy, IntTy, UintTy};
5 use syntax::symbol::sym;
6
7 use rustc_apfloat::ieee::{Single, Double};
8 use rustc_apfloat::{Float, FloatConvert};
9 use rustc::mir::interpret::{
10     Scalar, InterpResult, Pointer, PointerArithmetic, InterpError,
11 };
12 use rustc::mir::CastKind;
13
14 use super::{InterpretCx, Machine, PlaceTy, OpTy, Immediate};
15
16 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> InterpretCx<'a, 'mir, 'tcx, M> {
17     fn type_is_fat_ptr(&self, ty: Ty<'tcx>) -> bool {
18         match ty.sty {
19             ty::RawPtr(ty::TypeAndMut { ty, .. }) |
20             ty::Ref(_, ty, _) => !self.type_is_sized(ty),
21             ty::Adt(def, _) if def.is_box() => !self.type_is_sized(ty.boxed_ty()),
22             _ => false,
23         }
24     }
25
26     pub fn cast(
27         &mut self,
28         src: OpTy<'tcx, M::PointerTag>,
29         kind: CastKind,
30         dest: PlaceTy<'tcx, M::PointerTag>,
31     ) -> InterpResult<'tcx> {
32         use rustc::mir::CastKind::*;
33         match kind {
34             Pointer(PointerCast::Unsize) => {
35                 self.unsize_into(src, dest)?;
36             }
37
38             Misc | Pointer(PointerCast::MutToConstPointer) => {
39                 let src = self.read_immediate(src)?;
40
41                 if self.type_is_fat_ptr(src.layout.ty) {
42                     match (*src, self.type_is_fat_ptr(dest.layout.ty)) {
43                         // pointers to extern types
44                         (Immediate::Scalar(_),_) |
45                         // slices and trait objects to other slices/trait objects
46                         (Immediate::ScalarPair(..), true) => {
47                             // No change to immediate
48                             self.write_immediate(*src, dest)?;
49                         }
50                         // slices and trait objects to thin pointers (dropping the metadata)
51                         (Immediate::ScalarPair(data, _), false) => {
52                             self.write_scalar(data, dest)?;
53                         }
54                     }
55                 } else {
56                     match src.layout.variants {
57                         layout::Variants::Single { index } => {
58                             if let Some(discr) =
59                                 src.layout.ty.discriminant_for_variant(*self.tcx, index)
60                             {
61                                 // Cast from a univariant enum
62                                 assert!(src.layout.is_zst());
63                                 return self.write_scalar(
64                                     Scalar::from_uint(discr.val, dest.layout.size),
65                                     dest);
66                             }
67                         }
68                         layout::Variants::Multiple { .. } => {},
69                     }
70
71                     let dest_val = self.cast_scalar(src.to_scalar()?, src.layout, dest.layout)?;
72                     self.write_scalar(dest_val, dest)?;
73                 }
74             }
75
76             Pointer(PointerCast::ReifyFnPointer) => {
77                 // The src operand does not matter, just its type
78                 match src.layout.ty.sty {
79                     ty::FnDef(def_id, substs) => {
80                         if self.tcx.has_attr(def_id, sym::rustc_args_required_const) {
81                             bug!("reifying a fn ptr that requires const arguments");
82                         }
83                         let instance: InterpResult<'tcx, _> = ty::Instance::resolve(
84                             *self.tcx,
85                             self.param_env,
86                             def_id,
87                             substs,
88                         ).ok_or_else(|| InterpError::TooGeneric.into());
89                         let fn_ptr = self.memory.create_fn_alloc(instance?);
90                         self.write_scalar(Scalar::Ptr(fn_ptr.into()), dest)?;
91                     }
92                     _ => bug!("reify fn pointer on {:?}", src.layout.ty),
93                 }
94             }
95
96             Pointer(PointerCast::UnsafeFnPointer) => {
97                 let src = self.read_immediate(src)?;
98                 match dest.layout.ty.sty {
99                     ty::FnPtr(_) => {
100                         // No change to value
101                         self.write_immediate(*src, dest)?;
102                     }
103                     _ => bug!("fn to unsafe fn cast on {:?}", dest.layout.ty),
104                 }
105             }
106
107             Pointer(PointerCast::ClosureFnPointer(_)) => {
108                 // The src operand does not matter, just its type
109                 match src.layout.ty.sty {
110                     ty::Closure(def_id, substs) => {
111                         let substs = self.subst_and_normalize_erasing_regions(substs)?;
112                         let instance = ty::Instance::resolve_closure(
113                             *self.tcx,
114                             def_id,
115                             substs,
116                             ty::ClosureKind::FnOnce,
117                         );
118                         let fn_ptr = self.memory.create_fn_alloc(instance);
119                         let val = Immediate::Scalar(Scalar::Ptr(fn_ptr.into()).into());
120                         self.write_immediate(val, dest)?;
121                     }
122                     _ => bug!("closure fn pointer on {:?}", src.layout.ty),
123                 }
124             }
125         }
126         Ok(())
127     }
128
129     fn cast_scalar(
130         &self,
131         val: Scalar<M::PointerTag>,
132         src_layout: TyLayout<'tcx>,
133         dest_layout: TyLayout<'tcx>,
134     ) -> InterpResult<'tcx, Scalar<M::PointerTag>> {
135         use rustc::ty::TyKind::*;
136         trace!("Casting {:?}: {:?} to {:?}", val, src_layout.ty, dest_layout.ty);
137
138         match src_layout.ty.sty {
139             // Floating point
140             Float(FloatTy::F32) => self.cast_from_float(val.to_f32()?, dest_layout.ty),
141             Float(FloatTy::F64) => self.cast_from_float(val.to_f64()?, dest_layout.ty),
142             // Integer(-like), including fn ptr casts and casts from enums that
143             // are represented as integers (this excludes univariant enums, which
144             // are handled in `cast` directly).
145             _ => {
146                 assert!(
147                     src_layout.ty.is_bool()       || src_layout.ty.is_char()     ||
148                     src_layout.ty.is_enum()       || src_layout.ty.is_integral() ||
149                     src_layout.ty.is_unsafe_ptr() || src_layout.ty.is_fn_ptr()   ||
150                     src_layout.ty.is_region_ptr(),
151                     "Unexpected cast from type {:?}", src_layout.ty
152                 );
153                 match val.to_bits_or_ptr(src_layout.size, self) {
154                     Err(ptr) => self.cast_from_ptr(ptr, dest_layout.ty),
155                     Ok(data) => self.cast_from_int(data, src_layout, dest_layout),
156                 }
157             }
158         }
159     }
160
161     fn cast_from_int(
162         &self,
163         v: u128, // raw bits
164         src_layout: TyLayout<'tcx>,
165         dest_layout: TyLayout<'tcx>,
166     ) -> InterpResult<'tcx, Scalar<M::PointerTag>> {
167         // Let's make sure v is sign-extended *if* it has a signed type.
168         let signed = src_layout.abi.is_signed();
169         let v = if signed {
170             self.sign_extend(v, src_layout)
171         } else {
172             v
173         };
174         trace!("cast_from_int: {}, {}, {}", v, src_layout.ty, dest_layout.ty);
175         use rustc::ty::TyKind::*;
176         match dest_layout.ty.sty {
177             Int(_) | Uint(_) | RawPtr(_) => {
178                 let v = self.truncate(v, dest_layout);
179                 Ok(Scalar::from_uint(v, dest_layout.size))
180             }
181
182             Float(FloatTy::F32) if signed => Ok(Scalar::from_f32(
183                 Single::from_i128(v as i128).value
184             )),
185             Float(FloatTy::F64) if signed => Ok(Scalar::from_f64(
186                 Double::from_i128(v as i128).value
187             )),
188             Float(FloatTy::F32) => Ok(Scalar::from_f32(
189                 Single::from_u128(v).value
190             )),
191             Float(FloatTy::F64) => Ok(Scalar::from_f64(
192                 Double::from_u128(v).value
193             )),
194
195             Char => {
196                 // `u8` to `char` cast
197                 debug_assert_eq!(v as u8 as u128, v);
198                 Ok(Scalar::from_uint(v, Size::from_bytes(4)))
199             },
200
201             // Casts to bool are not permitted by rustc, no need to handle them here.
202             _ => err!(Unimplemented(format!("int to {:?} cast", dest_layout.ty))),
203         }
204     }
205
206     fn cast_from_float<F>(
207         &self,
208         f: F,
209         dest_ty: Ty<'tcx>
210     ) -> InterpResult<'tcx, Scalar<M::PointerTag>>
211     where F: Float + Into<Scalar<M::PointerTag>> + FloatConvert<Single> + FloatConvert<Double>
212     {
213         use rustc::ty::TyKind::*;
214         match dest_ty.sty {
215             // float -> uint
216             Uint(t) => {
217                 let width = t.bit_width().unwrap_or_else(|| self.pointer_size().bits() as usize);
218                 let v = f.to_u128(width).value;
219                 // This should already fit the bit width
220                 Ok(Scalar::from_uint(v, Size::from_bits(width as u64)))
221             },
222             // float -> int
223             Int(t) => {
224                 let width = t.bit_width().unwrap_or_else(|| self.pointer_size().bits() as usize);
225                 let v = f.to_i128(width).value;
226                 Ok(Scalar::from_int(v, Size::from_bits(width as u64)))
227             },
228             // float -> f32
229             Float(FloatTy::F32) =>
230                 Ok(Scalar::from_f32(f.convert(&mut false).value)),
231             // float -> f64
232             Float(FloatTy::F64) =>
233                 Ok(Scalar::from_f64(f.convert(&mut false).value)),
234             // That's it.
235             _ => bug!("invalid float to {:?} cast", dest_ty),
236         }
237     }
238
239     fn cast_from_ptr(
240         &self,
241         ptr: Pointer<M::PointerTag>,
242         ty: Ty<'tcx>
243     ) -> InterpResult<'tcx, Scalar<M::PointerTag>> {
244         use rustc::ty::TyKind::*;
245         match ty.sty {
246             // Casting to a reference or fn pointer is not permitted by rustc,
247             // no need to support it here.
248             RawPtr(_) |
249             Int(IntTy::Isize) |
250             Uint(UintTy::Usize) => Ok(ptr.into()),
251             Int(_) | Uint(_) => err!(ReadPointerAsBytes),
252             _ => err!(Unimplemented(format!("ptr to {:?} cast", ty))),
253         }
254     }
255
256     fn unsize_into_ptr(
257         &mut self,
258         src: OpTy<'tcx, M::PointerTag>,
259         dest: PlaceTy<'tcx, M::PointerTag>,
260         // The pointee types
261         sty: Ty<'tcx>,
262         dty: Ty<'tcx>,
263     ) -> InterpResult<'tcx> {
264         // A<Struct> -> A<Trait> conversion
265         let (src_pointee_ty, dest_pointee_ty) = self.tcx.struct_lockstep_tails(sty, dty);
266
267         match (&src_pointee_ty.sty, &dest_pointee_ty.sty) {
268             (&ty::Array(_, length), &ty::Slice(_)) => {
269                 let ptr = self.read_immediate(src)?.to_scalar_ptr()?;
270                 // u64 cast is from usize to u64, which is always good
271                 let val = Immediate::new_slice(
272                     ptr,
273                     length.unwrap_usize(self.tcx.tcx),
274                     self,
275                 );
276                 self.write_immediate(val, dest)
277             }
278             (&ty::Dynamic(..), &ty::Dynamic(..)) => {
279                 // For now, upcasts are limited to changes in marker
280                 // traits, and hence never actually require an actual
281                 // change to the vtable.
282                 let val = self.read_immediate(src)?;
283                 self.write_immediate(*val, dest)
284             }
285             (_, &ty::Dynamic(ref data, _)) => {
286                 // Initial cast from sized to dyn trait
287                 let vtable = self.get_vtable(src_pointee_ty, data.principal())?;
288                 let ptr = self.read_immediate(src)?.to_scalar_ptr()?;
289                 let val = Immediate::new_dyn_trait(ptr, vtable);
290                 self.write_immediate(val, dest)
291             }
292
293             _ => bug!("invalid unsizing {:?} -> {:?}", src.layout.ty, dest.layout.ty),
294         }
295     }
296
297     fn unsize_into(
298         &mut self,
299         src: OpTy<'tcx, M::PointerTag>,
300         dest: PlaceTy<'tcx, M::PointerTag>,
301     ) -> InterpResult<'tcx> {
302         trace!("Unsizing {:?} into {:?}", src, dest);
303         match (&src.layout.ty.sty, &dest.layout.ty.sty) {
304             (&ty::Ref(_, s, _), &ty::Ref(_, d, _)) |
305             (&ty::Ref(_, s, _), &ty::RawPtr(TypeAndMut { ty: d, .. })) |
306             (&ty::RawPtr(TypeAndMut { ty: s, .. }),
307              &ty::RawPtr(TypeAndMut { ty: d, .. })) => {
308                 self.unsize_into_ptr(src, dest, s, d)
309             }
310             (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
311                 assert_eq!(def_a, def_b);
312                 if def_a.is_box() || def_b.is_box() {
313                     if !def_a.is_box() || !def_b.is_box() {
314                         bug!("invalid unsizing between {:?} -> {:?}", src.layout, dest.layout);
315                     }
316                     return self.unsize_into_ptr(
317                         src,
318                         dest,
319                         src.layout.ty.boxed_ty(),
320                         dest.layout.ty.boxed_ty(),
321                     );
322                 }
323
324                 // unsizing of generic struct with pointer fields
325                 // Example: `Arc<T>` -> `Arc<Trait>`
326                 // here we need to increase the size of every &T thin ptr field to a fat ptr
327                 for i in 0..src.layout.fields.count() {
328                     let dst_field = self.place_field(dest, i as u64)?;
329                     if dst_field.layout.is_zst() {
330                         continue;
331                     }
332                     let src_field = self.operand_field(src, i as u64)?;
333                     if src_field.layout.ty == dst_field.layout.ty {
334                         self.copy_op(src_field, dst_field)?;
335                     } else {
336                         self.unsize_into(src_field, dst_field)?;
337                     }
338                 }
339                 Ok(())
340             }
341             _ => {
342                 bug!(
343                     "unsize_into: invalid conversion: {:?} -> {:?}",
344                     src.layout,
345                     dest.layout
346                 )
347             }
348         }
349     }
350 }