]> git.lizzy.rs Git - rust.git/blob - src/interpreter.rs
a7a1ffb27b6032465b581922a3d21d81f0fea73f
[rust.git] / src / interpreter.rs
1 use rustc::infer;
2 use rustc::middle::const_val;
3 use rustc::hir::def_id::DefId;
4 use rustc::mir::mir_map::MirMap;
5 use rustc::mir::repr as mir;
6 use rustc::traits::{self, ProjectionMode};
7 use rustc::ty::fold::TypeFoldable;
8 use rustc::ty::layout::{self, Layout, Size};
9 use rustc::ty::subst::{self, Subst, Substs};
10 use rustc::ty::{self, TyCtxt};
11 use rustc::util::nodemap::DefIdMap;
12 use std::cell::RefCell;
13 use std::ops::{Deref, DerefMut};
14 use std::rc::Rc;
15 use std::{iter, mem};
16 use syntax::ast;
17 use syntax::attr;
18 use syntax::codemap::{self, DUMMY_SP};
19
20 use error::{EvalError, EvalResult};
21 use memory::{Memory, Pointer};
22 use primval::{self, PrimVal};
23
24 const TRACE_EXECUTION: bool = false;
25
26 struct GlobalEvalContext<'a, 'tcx: 'a> {
27     /// The results of the type checker, from rustc.
28     tcx: &'a TyCtxt<'tcx>,
29
30     /// A mapping from NodeIds to Mir, from rustc. Only contains MIR for crate-local items.
31     mir_map: &'a MirMap<'tcx>,
32
33     /// A local cache from DefIds to Mir for non-crate-local items.
34     mir_cache: RefCell<DefIdMap<Rc<mir::Mir<'tcx>>>>,
35
36     /// The virtual memory system.
37     memory: Memory,
38
39     /// Another stack containing the type substitutions for the current function invocation. It
40     /// exists separately from `stack` because it must contain the `Substs` for a function while
41     /// *creating* the `Frame` for that same function.
42     substs_stack: Vec<&'tcx Substs<'tcx>>,
43
44     // TODO(tsion): Merge with `substs_stack`. Also try restructuring `Frame` to accomodate.
45     /// A stack of the things necessary to print good strack traces:
46     ///   * Function DefIds and Substs to print proper substituted function names.
47     ///   * Spans pointing to specific function calls in the source.
48     name_stack: Vec<(DefId, &'tcx Substs<'tcx>, codemap::Span)>,
49 }
50
51 struct FnEvalContext<'a, 'b: 'a + 'mir, 'mir, 'tcx: 'b> {
52     gecx: &'a mut GlobalEvalContext<'b, 'tcx>,
53
54     /// The virtual call stack.
55     stack: Vec<Frame<'mir, 'tcx>>,
56 }
57
58 impl<'a, 'b, 'mir, 'tcx> Deref for FnEvalContext<'a, 'b, 'mir, 'tcx> {
59     type Target = GlobalEvalContext<'b, 'tcx>;
60     fn deref(&self) -> &Self::Target {
61         self.gecx
62     }
63 }
64
65 impl<'a, 'b, 'mir, 'tcx> DerefMut for FnEvalContext<'a, 'b, 'mir, 'tcx> {
66     fn deref_mut(&mut self) -> &mut Self::Target {
67         self.gecx
68     }
69 }
70
71 /// A stack frame.
72 struct Frame<'a, 'tcx: 'a> {
73     /// The MIR for the function called on this frame.
74     mir: CachedMir<'a, 'tcx>,
75
76     /// The block this frame will execute when a function call returns back to this frame.
77     next_block: mir::BasicBlock,
78
79     /// A pointer for writing the return value of the current call if it's not a diverging call.
80     return_ptr: Option<Pointer>,
81
82     /// The list of locals for the current function, stored in order as
83     /// `[arguments..., variables..., temporaries...]`. The variables begin at `self.var_offset`
84     /// and the temporaries at `self.temp_offset`.
85     locals: Vec<Pointer>,
86
87     /// The offset of the first variable in `self.locals`.
88     var_offset: usize,
89
90     /// The offset of the first temporary in `self.locals`.
91     temp_offset: usize,
92 }
93
94 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
95 struct Lvalue {
96     ptr: Pointer,
97     extra: LvalueExtra,
98 }
99
100 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
101 enum LvalueExtra {
102     None,
103     Length(u64),
104     // TODO(tsion): Vtable(memory::AllocId),
105     DowncastVariant(usize),
106 }
107
108 #[derive(Clone)]
109 enum CachedMir<'mir, 'tcx: 'mir> {
110     Ref(&'mir mir::Mir<'tcx>),
111     Owned(Rc<mir::Mir<'tcx>>)
112 }
113
114 /// Represents the action to be taken in the main loop as a result of executing a terminator.
115 enum TerminatorTarget {
116     /// Make a local jump to the given block.
117     Block(mir::BasicBlock),
118
119     /// Start executing from the new current frame. (For function calls.)
120     Call,
121
122     /// Stop executing the current frame and resume the previous frame.
123     Return,
124 }
125
126 impl<'a, 'tcx> GlobalEvalContext<'a, 'tcx> {
127     fn new(tcx: &'a TyCtxt<'tcx>, mir_map: &'a MirMap<'tcx>) -> Self {
128         GlobalEvalContext {
129             tcx: tcx,
130             mir_map: mir_map,
131             mir_cache: RefCell::new(DefIdMap()),
132             memory: Memory::new(),
133             substs_stack: Vec::new(),
134             name_stack: Vec::new(),
135         }
136     }
137 }
138
139 impl<'a, 'b, 'mir, 'tcx> FnEvalContext<'a, 'b, 'mir, 'tcx> {
140     fn new(gecx: &'a mut GlobalEvalContext<'b, 'tcx>) -> Self {
141         FnEvalContext {
142             gecx: gecx,
143             stack: Vec::new(),
144         }
145     }
146
147     fn maybe_report<T>(&self, span: codemap::Span, r: EvalResult<T>) -> EvalResult<T> {
148         if let Err(ref e) = r {
149             let mut err = self.tcx.sess.struct_span_err(span, &e.to_string());
150             for &(def_id, substs, span) in self.name_stack.iter().rev() {
151                 // FIXME(tsion): Find a way to do this without this Display impl hack.
152                 use rustc::util::ppaux;
153                 use std::fmt;
154                 struct Instance<'tcx>(DefId, &'tcx Substs<'tcx>);
155                 impl<'tcx> fmt::Display for Instance<'tcx> {
156                     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157                         ppaux::parameterized(f, self.1, self.0, ppaux::Ns::Value, &[],
158                             |tcx| tcx.lookup_item_type(self.0).generics)
159                     }
160                 }
161                 err.span_note(span, &format!("inside call to {}", Instance(def_id, substs)));
162             }
163             err.emit();
164         }
165         r
166     }
167
168     fn log<F>(&self, extra_indent: usize, f: F) where F: FnOnce() {
169         let indent = self.stack.len() + extra_indent;
170         if !TRACE_EXECUTION { return; }
171         for _ in 0..indent { print!("    "); }
172         f();
173         println!("");
174     }
175
176     fn run(&mut self) -> EvalResult<()> {
177         'outer: while !self.stack.is_empty() {
178             let mut current_block = self.frame().next_block;
179
180             loop {
181                 self.log(0, || print!("// {:?}", current_block));
182                 let current_mir = self.mir().clone(); // Cloning a reference.
183                 let block_data = current_mir.basic_block_data(current_block);
184
185                 for stmt in &block_data.statements {
186                     self.log(0, || print!("{:?}", stmt));
187                     let mir::StatementKind::Assign(ref lvalue, ref rvalue) = stmt.kind;
188                     let result = self.eval_assignment(lvalue, rvalue);
189                     try!(self.maybe_report(stmt.span, result));
190                 }
191
192                 let terminator = block_data.terminator();
193                 self.log(0, || print!("{:?}", terminator.kind));
194
195                 let result = self.eval_terminator(terminator);
196                 match try!(self.maybe_report(terminator.span, result)) {
197                     TerminatorTarget::Block(block) => current_block = block,
198                     TerminatorTarget::Return => {
199                         self.pop_stack_frame();
200                         self.name_stack.pop();
201                         continue 'outer;
202                     }
203                     TerminatorTarget::Call => continue 'outer,
204                 }
205             }
206         }
207
208         Ok(())
209     }
210
211     fn call_nested(&mut self, mir: &mir::Mir<'tcx>) -> EvalResult<Option<Pointer>> {
212         let mut nested_fecx = FnEvalContext::new(self.gecx);
213
214         let return_ptr = match mir.return_ty {
215             ty::FnConverging(ty) => {
216                 let size = nested_fecx.type_size(ty);
217                 Some(nested_fecx.memory.allocate(size))
218             }
219             ty::FnDiverging => None,
220         };
221
222         let substs = nested_fecx.substs();
223         nested_fecx.push_stack_frame(CachedMir::Ref(mir), substs, return_ptr);
224         try!(nested_fecx.run());
225         Ok(return_ptr)
226     }
227
228     fn push_stack_frame(&mut self, mir: CachedMir<'mir, 'tcx>, substs: &'tcx Substs<'tcx>,
229         return_ptr: Option<Pointer>)
230     {
231         self.substs_stack.push(substs);
232
233         let arg_tys = mir.arg_decls.iter().map(|a| a.ty);
234         let var_tys = mir.var_decls.iter().map(|v| v.ty);
235         let temp_tys = mir.temp_decls.iter().map(|t| t.ty);
236
237         let locals: Vec<Pointer> = arg_tys.chain(var_tys).chain(temp_tys).map(|ty| {
238             let size = self.type_size(ty);
239             self.memory.allocate(size)
240         }).collect();
241
242         let num_args = mir.arg_decls.len();
243         let num_vars = mir.var_decls.len();
244
245         self.stack.push(Frame {
246             mir: mir.clone(),
247             next_block: mir::START_BLOCK,
248             return_ptr: return_ptr,
249             locals: locals,
250             var_offset: num_args,
251             temp_offset: num_args + num_vars,
252         });
253     }
254
255     fn pop_stack_frame(&mut self) {
256         let _frame = self.stack.pop().expect("tried to pop a stack frame, but there were none");
257         // TODO(tsion): Deallocate local variables.
258         self.substs_stack.pop();
259     }
260
261     fn eval_terminator(&mut self, terminator: &mir::Terminator<'tcx>)
262             -> EvalResult<TerminatorTarget> {
263         use rustc::mir::repr::TerminatorKind::*;
264         let target = match terminator.kind {
265             Return => TerminatorTarget::Return,
266
267             Goto { target } => TerminatorTarget::Block(target),
268
269             If { ref cond, targets: (then_target, else_target) } => {
270                 let cond_ptr = try!(self.eval_operand(cond));
271                 let cond_val = try!(self.memory.read_bool(cond_ptr));
272                 TerminatorTarget::Block(if cond_val { then_target } else { else_target })
273             }
274
275             SwitchInt { ref discr, ref values, ref targets, .. } => {
276                 let discr_ptr = try!(self.eval_lvalue(discr)).to_ptr();
277                 let discr_size = self
278                     .type_layout(self.lvalue_ty(discr))
279                     .size(&self.tcx.data_layout)
280                     .bytes() as usize;
281                 let discr_val = try!(self.memory.read_uint(discr_ptr, discr_size));
282
283                 // Branch to the `otherwise` case by default, if no match is found.
284                 let mut target_block = targets[targets.len() - 1];
285
286                 for (index, val_const) in values.iter().enumerate() {
287                     let ptr = try!(self.const_to_ptr(val_const));
288                     let val = try!(self.memory.read_uint(ptr, discr_size));
289                     if discr_val == val {
290                         target_block = targets[index];
291                         break;
292                     }
293                 }
294
295                 TerminatorTarget::Block(target_block)
296             }
297
298             Switch { ref discr, ref targets, adt_def } => {
299                 let adt_ptr = try!(self.eval_lvalue(discr)).to_ptr();
300                 let adt_layout = self.type_layout(self.lvalue_ty(discr));
301
302                  match *adt_layout {
303                     Layout::General { discr, .. } | Layout::CEnum { discr, .. } => {
304                         let discr_size = discr.size().bytes();
305                         let discr_val = try!(self.memory.read_uint(adt_ptr, discr_size as usize));
306
307                         let matching = adt_def.variants.iter()
308                             .position(|v| discr_val == v.disr_val.to_u64_unchecked());
309
310                         match matching {
311                             Some(i) => TerminatorTarget::Block(targets[i]),
312                             None => return Err(EvalError::InvalidDiscriminant),
313                         }
314                     }
315
316                     Layout::RawNullablePointer { nndiscr, .. } => {
317                         let is_null = match self.memory.read_usize(adt_ptr) {
318                             Ok(0) => true,
319                             Ok(_) | Err(EvalError::ReadPointerAsBytes) => false,
320                             Err(e) => return Err(e),
321                         };
322
323                         assert!(nndiscr == 0 || nndiscr == 1);
324                         let target = if is_null { 1 - nndiscr } else { nndiscr };
325                         TerminatorTarget::Block(targets[target as usize])
326                     }
327
328                     _ => panic!("attempted to switch on non-aggregate type"),
329                 }
330             }
331
332             Call { ref func, ref args, ref destination, .. } => {
333                 let mut return_ptr = None;
334                 if let Some((ref lv, target)) = *destination {
335                     self.frame_mut().next_block = target;
336                     return_ptr = Some(try!(self.eval_lvalue(lv)).to_ptr());
337                 }
338
339                 let func_ty = self.operand_ty(func);
340                 match func_ty.sty {
341                     ty::TyFnDef(def_id, substs, fn_ty) => {
342                         use syntax::abi::Abi;
343                         match fn_ty.abi {
344                             Abi::RustIntrinsic => {
345                                 let name = self.tcx.item_name(def_id).as_str();
346                                 match fn_ty.sig.0.output {
347                                     ty::FnConverging(ty) => {
348                                         let size = self.type_size(ty);
349                                         try!(self.call_intrinsic(&name, substs, args,
350                                             return_ptr.unwrap(), size))
351                                     }
352                                     ty::FnDiverging => unimplemented!(),
353                                 }
354                             }
355
356                             Abi::C =>
357                                 try!(self.call_c_abi(def_id, args, return_ptr.unwrap())),
358
359                             Abi::Rust | Abi::RustCall => {
360                                 // TODO(tsion): Adjust the first argument when calling a Fn or
361                                 // FnMut closure via FnOnce::call_once.
362
363                                 // Only trait methods can have a Self parameter.
364                                 let (resolved_def_id, resolved_substs) = if substs.self_ty().is_some() {
365                                     self.trait_method(def_id, substs)
366                                 } else {
367                                     (def_id, substs)
368                                 };
369
370                                 let mut arg_srcs = Vec::new();
371                                 for arg in args {
372                                     let src = try!(self.eval_operand(arg));
373                                     let src_ty = self.operand_ty(arg);
374                                     arg_srcs.push((src, src_ty));
375                                 }
376
377                                 if fn_ty.abi == Abi::RustCall && !args.is_empty() {
378                                     arg_srcs.pop();
379                                     let last_arg = args.last().unwrap();
380                                     let last = try!(self.eval_operand(last_arg));
381                                     let last_ty = self.operand_ty(last_arg);
382                                     let last_layout = self.type_layout(last_ty);
383                                     match (&last_ty.sty, last_layout) {
384                                         (&ty::TyTuple(ref fields),
385                                          &Layout::Univariant { ref variant, .. }) => {
386                                             let offsets = iter::once(0)
387                                                 .chain(variant.offset_after_field.iter()
388                                                     .map(|s| s.bytes()));
389                                             for (offset, ty) in offsets.zip(fields) {
390                                                 let src = last.offset(offset as isize);
391                                                 arg_srcs.push((src, ty));
392                                             }
393                                         }
394                                         ty => panic!("expected tuple as last argument in function with 'rust-call' ABI, got {:?}", ty),
395                                     }
396                                 }
397
398                                 let mir = self.load_mir(resolved_def_id);
399                                 self.name_stack.push((def_id, substs, terminator.span));
400                                 self.push_stack_frame(mir, resolved_substs, return_ptr);
401
402                                 for (i, (src, src_ty)) in arg_srcs.into_iter().enumerate() {
403                                     let dest = self.frame().locals[i];
404                                     try!(self.move_(src, dest, src_ty));
405                                 }
406
407                                 TerminatorTarget::Call
408                             }
409
410                             abi => panic!("can't handle function with {:?} ABI", abi),
411                         }
412                     }
413
414                     _ => panic!("can't handle callee of type {:?}", func_ty),
415                 }
416             }
417
418             Drop { ref value, target, .. } => {
419                 let ptr = try!(self.eval_lvalue(value)).to_ptr();
420                 let ty = self.lvalue_ty(value);
421                 try!(self.drop(ptr, ty));
422                 TerminatorTarget::Block(target)
423             }
424
425             Resume => unimplemented!(),
426         };
427
428         Ok(target)
429     }
430
431     fn drop(&mut self, ptr: Pointer, ty: ty::Ty<'tcx>) -> EvalResult<()> {
432         if !self.type_needs_drop(ty) {
433             self.log(1, || print!("no need to drop {:?}", ty));
434             return Ok(());
435         }
436         self.log(1, || print!("need to drop {:?}", ty));
437
438         // TODO(tsion): Call user-defined Drop::drop impls.
439
440         match ty.sty {
441             ty::TyBox(contents_ty) => {
442                 match self.memory.read_ptr(ptr) {
443                     Ok(contents_ptr) => {
444                         try!(self.drop(contents_ptr, contents_ty));
445                         self.log(1, || print!("deallocating box"));
446                         try!(self.memory.deallocate(contents_ptr));
447                     }
448                     Err(EvalError::ReadBytesAsPointer) => {
449                         let size = self.memory.pointer_size;
450                         let possible_drop_fill = try!(self.memory.read_bytes(ptr, size));
451                         if possible_drop_fill.iter().all(|&b| b == mem::POST_DROP_U8) {
452                             return Ok(());
453                         } else {
454                             return Err(EvalError::ReadBytesAsPointer);
455                         }
456                     }
457                     Err(e) => return Err(e),
458                 }
459             }
460
461             // TODO(tsion): Implement drop for other relevant types (e.g. aggregates).
462             _ => {}
463         }
464
465         // Filling drop.
466         // FIXME(tsion): Trait objects (with no static size) probably get filled, too.
467         let size = self.type_size(ty);
468         try!(self.memory.drop_fill(ptr, size));
469
470         Ok(())
471     }
472
473     fn call_intrinsic(
474         &mut self,
475         name: &str,
476         substs: &'tcx Substs<'tcx>,
477         args: &[mir::Operand<'tcx>],
478         dest: Pointer,
479         dest_size: usize
480     ) -> EvalResult<TerminatorTarget> {
481         let args_res: EvalResult<Vec<Pointer>> = args.iter()
482             .map(|arg| self.eval_operand(arg))
483             .collect();
484         let args = try!(args_res);
485
486         match name {
487             "assume" => {}
488
489             "copy_nonoverlapping" => {
490                 let elem_ty = *substs.types.get(subst::FnSpace, 0);
491                 let elem_size = self.type_size(elem_ty);
492                 let src = try!(self.memory.read_ptr(args[0]));
493                 let dest = try!(self.memory.read_ptr(args[1]));
494                 let count = try!(self.memory.read_isize(args[2]));
495                 try!(self.memory.copy(src, dest, count as usize * elem_size));
496             }
497
498             "forget" => {
499                 let arg_ty = *substs.types.get(subst::FnSpace, 0);
500                 let arg_size = self.type_size(arg_ty);
501                 try!(self.memory.drop_fill(args[0], arg_size));
502             }
503
504             "init" => try!(self.memory.write_repeat(dest, 0, dest_size)),
505
506             "min_align_of" => {
507                 try!(self.memory.write_int(dest, 1, dest_size));
508             }
509
510             "move_val_init" => {
511                 let ty = *substs.types.get(subst::FnSpace, 0);
512                 let ptr = try!(self.memory.read_ptr(args[0]));
513                 try!(self.move_(args[1], ptr, ty));
514             }
515
516             // FIXME(tsion): Handle different integer types correctly.
517             "add_with_overflow" => {
518                 let ty = *substs.types.get(subst::FnSpace, 0);
519                 let size = self.type_size(ty);
520                 let left = try!(self.memory.read_int(args[0], size));
521                 let right = try!(self.memory.read_int(args[1], size));
522                 let (n, overflowed) = unsafe {
523                     ::std::intrinsics::add_with_overflow::<i64>(left, right)
524                 };
525                 try!(self.memory.write_int(dest, n, size));
526                 try!(self.memory.write_bool(dest.offset(size as isize), overflowed));
527             }
528
529             // FIXME(tsion): Handle different integer types correctly.
530             "mul_with_overflow" => {
531                 let ty = *substs.types.get(subst::FnSpace, 0);
532                 let size = self.type_size(ty);
533                 let left = try!(self.memory.read_int(args[0], size));
534                 let right = try!(self.memory.read_int(args[1], size));
535                 let (n, overflowed) = unsafe {
536                     ::std::intrinsics::mul_with_overflow::<i64>(left, right)
537                 };
538                 try!(self.memory.write_int(dest, n, size));
539                 try!(self.memory.write_bool(dest.offset(size as isize), overflowed));
540             }
541
542             "offset" => {
543                 let pointee_ty = *substs.types.get(subst::FnSpace, 0);
544                 let pointee_size = self.type_size(pointee_ty) as isize;
545                 let ptr_arg = args[0];
546                 let offset = try!(self.memory.read_isize(args[1]));
547
548                 match self.memory.read_ptr(ptr_arg) {
549                     Ok(ptr) => {
550                         let result_ptr = ptr.offset(offset as isize * pointee_size);
551                         try!(self.memory.write_ptr(dest, result_ptr));
552                     }
553                     Err(EvalError::ReadBytesAsPointer) => {
554                         let addr = try!(self.memory.read_isize(ptr_arg));
555                         let result_addr = addr + offset * pointee_size as i64;
556                         try!(self.memory.write_isize(dest, result_addr));
557                     }
558                     Err(e) => return Err(e),
559                 }
560             }
561
562             // FIXME(tsion): Handle different integer types correctly. Use primvals?
563             "overflowing_sub" => {
564                 let ty = *substs.types.get(subst::FnSpace, 0);
565                 let size = self.type_size(ty);
566                 let left = try!(self.memory.read_int(args[0], size));
567                 let right = try!(self.memory.read_int(args[1], size));
568                 let n = left.wrapping_sub(right);
569                 try!(self.memory.write_int(dest, n, size));
570             }
571
572             "size_of" => {
573                 let ty = *substs.types.get(subst::FnSpace, 0);
574                 let size = self.type_size(ty) as u64;
575                 try!(self.memory.write_uint(dest, size, dest_size));
576             }
577
578             "transmute" => {
579                 let ty = *substs.types.get(subst::FnSpace, 0);
580                 try!(self.move_(args[0], dest, ty));
581             }
582             "uninit" => try!(self.memory.mark_definedness(dest, dest_size, false)),
583
584             name => panic!("can't handle intrinsic: {}", name),
585         }
586
587         // Since we pushed no stack frame, the main loop will act
588         // as if the call just completed and it's returning to the
589         // current frame.
590         Ok(TerminatorTarget::Call)
591     }
592
593     fn call_c_abi(
594         &mut self,
595         def_id: DefId,
596         args: &[mir::Operand<'tcx>],
597         dest: Pointer
598     ) -> EvalResult<TerminatorTarget> {
599         let name = self.tcx.item_name(def_id);
600         let attrs = self.tcx.get_attrs(def_id);
601         let link_name = match attr::first_attr_value_str_by_name(&attrs, "link_name") {
602             Some(ln) => ln.clone(),
603             None => name.as_str(),
604         };
605
606         let args_res: EvalResult<Vec<Pointer>> = args.iter()
607             .map(|arg| self.eval_operand(arg))
608             .collect();
609         let args = try!(args_res);
610
611         match &link_name[..] {
612             "__rust_allocate" => {
613                 let size = try!(self.memory.read_usize(args[0]));
614                 let ptr = self.memory.allocate(size as usize);
615                 try!(self.memory.write_ptr(dest, ptr));
616             }
617
618             "__rust_reallocate" => {
619                 let ptr = try!(self.memory.read_ptr(args[0]));
620                 let size = try!(self.memory.read_usize(args[2]));
621                 try!(self.memory.reallocate(ptr, size as usize));
622                 try!(self.memory.write_ptr(dest, ptr));
623             }
624
625             _ => panic!("can't call C ABI function: {}", link_name),
626         }
627
628         // Since we pushed no stack frame, the main loop will act
629         // as if the call just completed and it's returning to the
630         // current frame.
631         Ok(TerminatorTarget::Call)
632     }
633
634     fn assign_fields<I: IntoIterator<Item = u64>>(
635         &mut self,
636         dest: Pointer,
637         offsets: I,
638         operands: &[mir::Operand<'tcx>],
639     ) -> EvalResult<()> {
640         for (offset, operand) in offsets.into_iter().zip(operands) {
641             let src = try!(self.eval_operand(operand));
642             let src_ty = self.operand_ty(operand);
643             let field_dest = dest.offset(offset as isize);
644             try!(self.move_(src, field_dest, src_ty));
645         }
646         Ok(())
647     }
648
649     fn eval_assignment(&mut self, lvalue: &mir::Lvalue<'tcx>, rvalue: &mir::Rvalue<'tcx>)
650         -> EvalResult<()>
651     {
652         let dest = try!(self.eval_lvalue(lvalue)).to_ptr();
653         let dest_ty = self.lvalue_ty(lvalue);
654         let dest_layout = self.type_layout(dest_ty);
655
656         use rustc::mir::repr::Rvalue::*;
657         match *rvalue {
658             Use(ref operand) => {
659                 let src = try!(self.eval_operand(operand));
660                 try!(self.move_(src, dest, dest_ty));
661             }
662
663             BinaryOp(bin_op, ref left, ref right) => {
664                 let left_ptr = try!(self.eval_operand(left));
665                 let left_ty = self.operand_ty(left);
666                 let left_val = try!(self.read_primval(left_ptr, left_ty));
667
668                 let right_ptr = try!(self.eval_operand(right));
669                 let right_ty = self.operand_ty(right);
670                 let right_val = try!(self.read_primval(right_ptr, right_ty));
671
672                 let val = try!(primval::binary_op(bin_op, left_val, right_val));
673                 try!(self.memory.write_primval(dest, val));
674             }
675
676             UnaryOp(un_op, ref operand) => {
677                 let ptr = try!(self.eval_operand(operand));
678                 let ty = self.operand_ty(operand);
679                 let val = try!(self.read_primval(ptr, ty));
680                 try!(self.memory.write_primval(dest, primval::unary_op(un_op, val)));
681             }
682
683             Aggregate(ref kind, ref operands) => {
684                 use rustc::ty::layout::Layout::*;
685                 match *dest_layout {
686                     Univariant { ref variant, .. } => {
687                         let offsets = iter::once(0)
688                             .chain(variant.offset_after_field.iter().map(|s| s.bytes()));
689                         try!(self.assign_fields(dest, offsets, operands));
690                     }
691
692                     Array { .. } => {
693                         let elem_size = match dest_ty.sty {
694                             ty::TyArray(elem_ty, _) => self.type_size(elem_ty) as u64,
695                             _ => panic!("tried to assign {:?} to non-array type {:?}",
696                                         kind, dest_ty),
697                         };
698                         let offsets = (0..).map(|i| i * elem_size);
699                         try!(self.assign_fields(dest, offsets, operands));
700                     }
701
702                     General { discr, ref variants, .. } => {
703                         if let mir::AggregateKind::Adt(adt_def, variant, _) = *kind {
704                             let discr_val = adt_def.variants[variant].disr_val.to_u64_unchecked();
705                             let discr_size = discr.size().bytes() as usize;
706                             try!(self.memory.write_uint(dest, discr_val, discr_size));
707
708                             let offsets = variants[variant].offset_after_field.iter()
709                                 .map(|s| s.bytes());
710                             try!(self.assign_fields(dest, offsets, operands));
711                         } else {
712                             panic!("tried to assign {:?} to Layout::General", kind);
713                         }
714                     }
715
716                     RawNullablePointer { nndiscr, .. } => {
717                         if let mir::AggregateKind::Adt(_, variant, _) = *kind {
718                             if nndiscr == variant as u64 {
719                                 assert_eq!(operands.len(), 1);
720                                 let operand = &operands[0];
721                                 let src = try!(self.eval_operand(operand));
722                                 let src_ty = self.operand_ty(operand);
723                                 try!(self.move_(src, dest, src_ty));
724                             } else {
725                                 assert_eq!(operands.len(), 0);
726                                 try!(self.memory.write_isize(dest, 0));
727                             }
728                         } else {
729                             panic!("tried to assign {:?} to Layout::RawNullablePointer", kind);
730                         }
731                     }
732
733                     CEnum { discr, signed, .. } => {
734                         assert_eq!(operands.len(), 0);
735                         if let mir::AggregateKind::Adt(adt_def, variant, _) = *kind {
736                             let val = adt_def.variants[variant].disr_val.to_u64_unchecked();
737                             let size = discr.size().bytes() as usize;
738
739                             if signed {
740                                 try!(self.memory.write_int(dest, val as i64, size));
741                             } else {
742                                 try!(self.memory.write_uint(dest, val, size));
743                             }
744                         } else {
745                             panic!("tried to assign {:?} to Layout::CEnum", kind);
746                         }
747                     }
748
749                     _ => panic!("can't handle destination layout {:?} when assigning {:?}",
750                                 dest_layout, kind),
751                 }
752             }
753
754             Repeat(ref operand, _) => {
755                 let (elem_size, length) = match dest_ty.sty {
756                     ty::TyArray(elem_ty, n) => (self.type_size(elem_ty), n),
757                     _ => panic!("tried to assign array-repeat to non-array type {:?}", dest_ty),
758                 };
759
760                 let src = try!(self.eval_operand(operand));
761                 for i in 0..length {
762                     let elem_dest = dest.offset((i * elem_size) as isize);
763                     try!(self.memory.copy(src, elem_dest, elem_size));
764                 }
765             }
766
767             Len(ref lvalue) => {
768                 let src = try!(self.eval_lvalue(lvalue));
769                 let ty = self.lvalue_ty(lvalue);
770                 let len = match ty.sty {
771                     ty::TyArray(_, n) => n as u64,
772                     ty::TySlice(_) => if let LvalueExtra::Length(n) = src.extra {
773                         n
774                     } else {
775                         panic!("Rvalue::Len of a slice given non-slice pointer: {:?}", src);
776                     },
777                     _ => panic!("Rvalue::Len expected array or slice, got {:?}", ty),
778                 };
779                 try!(self.memory.write_usize(dest, len));
780             }
781
782             Ref(_, _, ref lvalue) => {
783                 let lv = try!(self.eval_lvalue(lvalue));
784                 try!(self.memory.write_ptr(dest, lv.ptr));
785                 match lv.extra {
786                     LvalueExtra::None => {},
787                     LvalueExtra::Length(len) => {
788                         let len_ptr = dest.offset(self.memory.pointer_size as isize);
789                         try!(self.memory.write_usize(len_ptr, len));
790                     }
791                     LvalueExtra::DowncastVariant(..) =>
792                         panic!("attempted to take a reference to an enum downcast lvalue"),
793                 }
794             }
795
796             Box(ty) => {
797                 let size = self.type_size(ty);
798                 let ptr = self.memory.allocate(size);
799                 try!(self.memory.write_ptr(dest, ptr));
800             }
801
802             Cast(kind, ref operand, dest_ty) => {
803                 let src = try!(self.eval_operand(operand));
804                 let src_ty = self.operand_ty(operand);
805
806                 use rustc::mir::repr::CastKind::*;
807                 match kind {
808                     Unsize => {
809                         try!(self.move_(src, dest, src_ty));
810                         let src_pointee_ty = pointee_type(src_ty).unwrap();
811                         let dest_pointee_ty = pointee_type(dest_ty).unwrap();
812
813                         match (&src_pointee_ty.sty, &dest_pointee_ty.sty) {
814                             (&ty::TyArray(_, length), &ty::TySlice(_)) => {
815                                 let len_ptr = dest.offset(self.memory.pointer_size as isize);
816                                 try!(self.memory.write_usize(len_ptr, length as u64));
817                             }
818
819                             _ => panic!("can't handle cast: {:?}", rvalue),
820                         }
821                     }
822
823                     Misc => {
824                         // FIXME(tsion): Wrong for almost everything.
825                         let size = dest_layout.size(&self.tcx.data_layout).bytes() as usize;
826                         try!(self.memory.copy(src, dest, size));
827                     }
828
829                     _ => panic!("can't handle cast: {:?}", rvalue),
830                 }
831             }
832
833             Slice { .. } => unimplemented!(),
834             InlineAsm { .. } => unimplemented!(),
835         }
836
837         Ok(())
838     }
839
840     fn eval_operand(&mut self, op: &mir::Operand<'tcx>) -> EvalResult<Pointer> {
841         use rustc::mir::repr::Operand::*;
842         match *op {
843             Consume(ref lvalue) =>
844                 Ok(try!(self.eval_lvalue(lvalue)).to_ptr()),
845             Constant(mir::Constant { ref literal, .. }) => {
846                 use rustc::mir::repr::Literal::*;
847                 match *literal {
848                     Value { ref value } => Ok(try!(self.const_to_ptr(value))),
849                     Item { .. } => unimplemented!(),
850                     Promoted { index } => {
851                         let current_mir = self.mir();
852                         let mir = &current_mir.promoted[index];
853                         self.call_nested(mir).map(Option::unwrap)
854                     }
855                 }
856             }
857         }
858     }
859
860     fn eval_lvalue(&mut self, lvalue: &mir::Lvalue<'tcx>) -> EvalResult<Lvalue> {
861         use rustc::mir::repr::Lvalue::*;
862         let ptr = match *lvalue {
863             ReturnPointer => self.frame().return_ptr
864                 .expect("ReturnPointer used in a function with no return value"),
865             Arg(i) => self.frame().locals[i as usize],
866             Var(i) => self.frame().locals[self.frame().var_offset + i as usize],
867             Temp(i) => self.frame().locals[self.frame().temp_offset + i as usize],
868
869             Static(_def_id) => unimplemented!(),
870
871             Projection(ref proj) => {
872                 let base = try!(self.eval_lvalue(&proj.base));
873                 let base_ty = self.lvalue_ty(&proj.base);
874                 let base_layout = self.type_layout(base_ty);
875
876                 use rustc::mir::repr::ProjectionElem::*;
877                 match proj.elem {
878                     Field(field, _) => {
879                         let variant = match *base_layout {
880                             Layout::Univariant { ref variant, .. } => variant,
881                             Layout::General { ref variants, .. } => {
882                                 if let LvalueExtra::DowncastVariant(variant_idx) = base.extra {
883                                     &variants[variant_idx]
884                                 } else {
885                                     panic!("field access on enum had no variant index");
886                                 }
887                             }
888                             Layout::RawNullablePointer { .. } => {
889                                 assert_eq!(field.index(), 0);
890                                 return Ok(base);
891                             }
892                             _ => panic!("field access on non-product type: {:?}", base_layout),
893                         };
894
895                         let offset = variant.field_offset(field.index()).bytes();
896                         base.ptr.offset(offset as isize)
897                     },
898
899                     Downcast(_, variant) => match *base_layout {
900                         Layout::General { discr, .. } => {
901                             return Ok(Lvalue {
902                                 ptr: base.ptr.offset(discr.size().bytes() as isize),
903                                 extra: LvalueExtra::DowncastVariant(variant),
904                             });
905                         }
906                         Layout::RawNullablePointer { .. } => return Ok(base),
907                         _ => panic!("variant downcast on non-aggregate type: {:?}", base_layout),
908                     },
909
910                     Deref => {
911                         let pointee_ty = pointee_type(base_ty).expect("Deref of non-pointer");
912                         let ptr = try!(self.memory.read_ptr(base.ptr));
913                         let extra = match pointee_ty.sty {
914                             ty::TySlice(_) | ty::TyStr => {
915                                 let len_ptr = base.ptr.offset(self.memory.pointer_size as isize);
916                                 let len = try!(self.memory.read_usize(len_ptr));
917                                 LvalueExtra::Length(len)
918                             }
919                             ty::TyTrait(_) => unimplemented!(),
920                             _ => LvalueExtra::None,
921                         };
922                         return Ok(Lvalue { ptr: ptr, extra: extra });
923                     }
924
925                     Index(ref operand) => {
926                         let elem_size = match base_ty.sty {
927                             ty::TyArray(elem_ty, _) |
928                             ty::TySlice(elem_ty) => self.type_size(elem_ty),
929                             _ => panic!("indexing expected an array or slice, got {:?}", base_ty),
930                         };
931                         let n_ptr = try!(self.eval_operand(operand));
932                         let n = try!(self.memory.read_usize(n_ptr));
933                         base.ptr.offset(n as isize * elem_size as isize)
934                     }
935
936                     ConstantIndex { .. } => unimplemented!(),
937                 }
938             }
939         };
940
941         Ok(Lvalue { ptr: ptr, extra: LvalueExtra::None })
942     }
943
944     // TODO(tsion): Try making const_to_primval instead.
945     fn const_to_ptr(&mut self, const_val: &const_val::ConstVal) -> EvalResult<Pointer> {
946         use rustc::middle::const_val::ConstVal::*;
947         match *const_val {
948             Float(_f) => unimplemented!(),
949             Integral(int) => {
950                 // TODO(tsion): Check int constant type.
951                 let ptr = self.memory.allocate(8);
952                 try!(self.memory.write_uint(ptr, int.to_u64_unchecked(), 8));
953                 Ok(ptr)
954             }
955             Str(ref s) => {
956                 let psize = self.memory.pointer_size;
957                 let static_ptr = self.memory.allocate(s.len());
958                 let ptr = self.memory.allocate(psize * 2);
959                 try!(self.memory.write_bytes(static_ptr, s.as_bytes()));
960                 try!(self.memory.write_ptr(ptr, static_ptr));
961                 try!(self.memory.write_usize(ptr.offset(psize as isize), s.len() as u64));
962                 Ok(ptr)
963             }
964             ByteStr(ref bs) => {
965                 let psize = self.memory.pointer_size;
966                 let static_ptr = self.memory.allocate(bs.len());
967                 let ptr = self.memory.allocate(psize);
968                 try!(self.memory.write_bytes(static_ptr, bs));
969                 try!(self.memory.write_ptr(ptr, static_ptr));
970                 Ok(ptr)
971             }
972             Bool(b) => {
973                 let ptr = self.memory.allocate(1);
974                 try!(self.memory.write_bool(ptr, b));
975                 Ok(ptr)
976             }
977             Char(_c)          => unimplemented!(),
978             Struct(_node_id)  => unimplemented!(),
979             Tuple(_node_id)   => unimplemented!(),
980             Function(_def_id) => unimplemented!(),
981             Array(_, _)       => unimplemented!(),
982             Repeat(_, _)      => unimplemented!(),
983             Dummy             => unimplemented!(),
984         }
985     }
986
987     fn lvalue_ty(&self, lvalue: &mir::Lvalue<'tcx>) -> ty::Ty<'tcx> {
988         self.monomorphize(self.mir().lvalue_ty(self.tcx, lvalue).to_ty(self.tcx))
989     }
990
991     fn operand_ty(&self, operand: &mir::Operand<'tcx>) -> ty::Ty<'tcx> {
992         self.monomorphize(self.mir().operand_ty(self.tcx, operand))
993     }
994
995     fn monomorphize(&self, ty: ty::Ty<'tcx>) -> ty::Ty<'tcx> {
996         let substituted = ty.subst(self.tcx, self.substs());
997         infer::normalize_associated_type(self.tcx, &substituted)
998     }
999
1000     fn type_needs_drop(&self, ty: ty::Ty<'tcx>) -> bool {
1001         self.tcx.type_needs_drop_given_env(ty, &self.tcx.empty_parameter_environment())
1002     }
1003
1004     fn move_(&mut self, src: Pointer, dest: Pointer, ty: ty::Ty<'tcx>) -> EvalResult<()> {
1005         let size = self.type_size(ty);
1006         try!(self.memory.copy(src, dest, size));
1007         if self.type_needs_drop(ty) {
1008             try!(self.memory.drop_fill(src, size));
1009         }
1010         Ok(())
1011     }
1012
1013     fn type_is_sized(&self, ty: ty::Ty<'tcx>) -> bool {
1014         ty.is_sized(&self.tcx.empty_parameter_environment(), DUMMY_SP)
1015     }
1016
1017     fn type_size(&self, ty: ty::Ty<'tcx>) -> usize {
1018         self.type_layout(ty).size(&self.tcx.data_layout).bytes() as usize
1019     }
1020
1021     fn type_layout(&self, ty: ty::Ty<'tcx>) -> &'tcx Layout {
1022         // TODO(tsion): Is this inefficient? Needs investigation.
1023         let ty = self.monomorphize(ty);
1024
1025         let infcx = infer::normalizing_infer_ctxt(self.tcx, &self.tcx.tables, ProjectionMode::Any);
1026
1027         // TODO(tsion): Report this error properly.
1028         ty.layout(&infcx).unwrap()
1029     }
1030
1031     pub fn read_primval(&mut self, ptr: Pointer, ty: ty::Ty<'tcx>) -> EvalResult<PrimVal> {
1032         use syntax::ast::{IntTy, UintTy};
1033         let val = match ty.sty {
1034             ty::TyBool              => PrimVal::Bool(try!(self.memory.read_bool(ptr))),
1035             ty::TyInt(IntTy::I8)    => PrimVal::I8(try!(self.memory.read_int(ptr, 1)) as i8),
1036             ty::TyInt(IntTy::I16)   => PrimVal::I16(try!(self.memory.read_int(ptr, 2)) as i16),
1037             ty::TyInt(IntTy::I32)   => PrimVal::I32(try!(self.memory.read_int(ptr, 4)) as i32),
1038             ty::TyInt(IntTy::I64)   => PrimVal::I64(try!(self.memory.read_int(ptr, 8)) as i64),
1039             ty::TyUint(UintTy::U8)  => PrimVal::U8(try!(self.memory.read_uint(ptr, 1)) as u8),
1040             ty::TyUint(UintTy::U16) => PrimVal::U16(try!(self.memory.read_uint(ptr, 2)) as u16),
1041             ty::TyUint(UintTy::U32) => PrimVal::U32(try!(self.memory.read_uint(ptr, 4)) as u32),
1042             ty::TyUint(UintTy::U64) => PrimVal::U64(try!(self.memory.read_uint(ptr, 8)) as u64),
1043
1044             // TODO(tsion): Pick the PrimVal dynamically.
1045             ty::TyInt(IntTy::Is)   => PrimVal::I64(try!(self.memory.read_isize(ptr))),
1046             ty::TyUint(UintTy::Us) => PrimVal::U64(try!(self.memory.read_usize(ptr))),
1047
1048             ty::TyRef(_, ty::TypeAndMut { ty, .. }) |
1049             ty::TyRawPtr(ty::TypeAndMut { ty, .. }) => {
1050                 if self.type_is_sized(ty) {
1051                     match self.memory.read_ptr(ptr) {
1052                         Ok(p) => PrimVal::AbstractPtr(p),
1053                         Err(EvalError::ReadBytesAsPointer) => {
1054                             let n = try!(self.memory.read_usize(ptr));
1055                             PrimVal::IntegerPtr(n)
1056                         }
1057                         Err(e) => return Err(e),
1058                     }
1059                 } else {
1060                     panic!("unimplemented: primitive read of fat pointer type: {:?}", ty);
1061                 }
1062             }
1063
1064             _ => panic!("primitive read of non-primitive type: {:?}", ty),
1065         };
1066         Ok(val)
1067     }
1068
1069     fn frame(&self) -> &Frame<'mir, 'tcx> {
1070         self.stack.last().expect("no call frames exist")
1071     }
1072
1073     fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx> {
1074         self.stack.last_mut().expect("no call frames exist")
1075     }
1076
1077     fn mir(&self) -> CachedMir<'mir, 'tcx> {
1078         self.frame().mir.clone()
1079     }
1080
1081     fn substs(&self) -> &'tcx Substs<'tcx> {
1082         self.substs_stack.last().cloned().unwrap_or_else(|| self.tcx.mk_substs(Substs::empty()))
1083     }
1084
1085     fn load_mir(&self, def_id: DefId) -> CachedMir<'mir, 'tcx> {
1086         match self.tcx.map.as_local_node_id(def_id) {
1087             Some(node_id) => CachedMir::Ref(self.mir_map.map.get(&node_id).unwrap()),
1088             None => {
1089                 let mut mir_cache = self.mir_cache.borrow_mut();
1090                 if let Some(mir) = mir_cache.get(&def_id) {
1091                     return CachedMir::Owned(mir.clone());
1092                 }
1093
1094                 let cs = &self.tcx.sess.cstore;
1095                 let mir = cs.maybe_get_item_mir(self.tcx, def_id).unwrap_or_else(|| {
1096                     panic!("no mir for {:?}", def_id);
1097                 });
1098                 let cached = Rc::new(mir);
1099                 mir_cache.insert(def_id, cached.clone());
1100                 CachedMir::Owned(cached)
1101             }
1102         }
1103     }
1104
1105     fn fulfill_obligation(&self, trait_ref: ty::PolyTraitRef<'tcx>) -> traits::Vtable<'tcx, ()> {
1106         // Do the initial selection for the obligation. This yields the shallow result we are
1107         // looking for -- that is, what specific impl.
1108         let infcx = infer::normalizing_infer_ctxt(self.tcx, &self.tcx.tables, ProjectionMode::Any);
1109         let mut selcx = traits::SelectionContext::new(&infcx);
1110
1111         let obligation = traits::Obligation::new(
1112             traits::ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID),
1113             trait_ref.to_poly_trait_predicate(),
1114         );
1115         let selection = selcx.select(&obligation).unwrap().unwrap();
1116
1117         // Currently, we use a fulfillment context to completely resolve all nested obligations.
1118         // This is because they can inform the inference of the impl's type parameters.
1119         let mut fulfill_cx = traits::FulfillmentContext::new();
1120         let vtable = selection.map(|predicate| {
1121             fulfill_cx.register_predicate_obligation(&infcx, predicate);
1122         });
1123         infer::drain_fulfillment_cx_or_panic(
1124             DUMMY_SP, &infcx, &mut fulfill_cx, &vtable
1125         )
1126     }
1127
1128     /// Trait method, which has to be resolved to an impl method.
1129     pub fn trait_method(&self, def_id: DefId, substs: &'tcx Substs<'tcx>)
1130         -> (DefId, &'tcx Substs<'tcx>)
1131     {
1132         let method_item = self.tcx.impl_or_trait_item(def_id);
1133         let trait_id = method_item.container().id();
1134         let trait_ref = ty::Binder(substs.to_trait_ref(self.tcx, trait_id));
1135         match self.fulfill_obligation(trait_ref) {
1136             traits::VtableImpl(vtable_impl) => {
1137                 let impl_did = vtable_impl.impl_def_id;
1138                 let mname = self.tcx.item_name(def_id);
1139                 // Create a concatenated set of substitutions which includes those from the impl
1140                 // and those from the method:
1141                 let impl_substs = vtable_impl.substs.with_method_from(substs);
1142                 let substs = self.tcx.mk_substs(impl_substs);
1143                 let mth = get_impl_method(self.tcx, impl_did, substs, mname);
1144
1145                 (mth.method.def_id, mth.substs)
1146             }
1147
1148             traits::VtableClosure(vtable_closure) =>
1149                 (vtable_closure.closure_def_id, vtable_closure.substs.func_substs),
1150
1151             traits::VtableFnPointer(_fn_ty) => {
1152                 let _trait_closure_kind = self.tcx.lang_items.fn_trait_kind(trait_id).unwrap();
1153                 unimplemented!()
1154                 // let llfn = trans_fn_pointer_shim(ccx, trait_closure_kind, fn_ty);
1155
1156                 // let method_ty = def_ty(tcx, def_id, substs);
1157                 // let fn_ptr_ty = match method_ty.sty {
1158                 //     ty::TyFnDef(_, _, fty) => tcx.mk_ty(ty::TyFnPtr(fty)),
1159                 //     _ => unreachable!("expected fn item type, found {}",
1160                 //                       method_ty)
1161                 // };
1162                 // Callee::ptr(immediate_rvalue(llfn, fn_ptr_ty))
1163             }
1164
1165             traits::VtableObject(ref _data) => {
1166                 unimplemented!()
1167                 // Callee {
1168                 //     data: Virtual(traits::get_vtable_index_of_object_method(
1169                 //                   tcx, data, def_id)),
1170                 //                   ty: def_ty(tcx, def_id, substs)
1171                 // }
1172             }
1173             vtable => unreachable!("resolved vtable bad vtable {:?} in trans", vtable),
1174         }
1175     }
1176 }
1177
1178 fn pointee_type(ptr_ty: ty::Ty) -> Option<ty::Ty> {
1179     match ptr_ty.sty {
1180         ty::TyRef(_, ty::TypeAndMut { ty, .. }) |
1181         ty::TyRawPtr(ty::TypeAndMut { ty, .. }) |
1182         ty::TyBox(ty) => {
1183             Some(ty)
1184         }
1185         _ => None,
1186     }
1187 }
1188
1189 impl Lvalue {
1190     fn to_ptr(self) -> Pointer {
1191         assert_eq!(self.extra, LvalueExtra::None);
1192         self.ptr
1193     }
1194 }
1195
1196 impl<'mir, 'tcx: 'mir> Deref for CachedMir<'mir, 'tcx> {
1197     type Target = mir::Mir<'tcx>;
1198     fn deref(&self) -> &mir::Mir<'tcx> {
1199         match *self {
1200             CachedMir::Ref(r) => r,
1201             CachedMir::Owned(ref rc) => &rc,
1202         }
1203     }
1204 }
1205
1206 #[derive(Debug)]
1207 pub struct ImplMethod<'tcx> {
1208     pub method: Rc<ty::Method<'tcx>>,
1209     pub substs: &'tcx Substs<'tcx>,
1210     pub is_provided: bool,
1211 }
1212
1213 /// Locates the applicable definition of a method, given its name.
1214 pub fn get_impl_method<'tcx>(
1215     tcx: &TyCtxt<'tcx>,
1216     impl_def_id: DefId,
1217     substs: &'tcx Substs<'tcx>,
1218     name: ast::Name,
1219 ) -> ImplMethod<'tcx> {
1220     assert!(!substs.types.needs_infer());
1221
1222     let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
1223     let trait_def = tcx.lookup_trait_def(trait_def_id);
1224     let infcx = infer::normalizing_infer_ctxt(tcx, &tcx.tables, ProjectionMode::Any);
1225
1226     match trait_def.ancestors(impl_def_id).fn_defs(tcx, name).next() {
1227         Some(node_item) => {
1228             ImplMethod {
1229                 method: node_item.item,
1230                 substs: traits::translate_substs(&infcx, impl_def_id, substs, node_item.node),
1231                 is_provided: node_item.node.is_from_trait(),
1232             }
1233         }
1234         None => {
1235             bug!("method {:?} not found in {:?}", name, impl_def_id);
1236         }
1237     }
1238 }
1239
1240 pub fn interpret_start_points<'tcx>(tcx: &TyCtxt<'tcx>, mir_map: &MirMap<'tcx>) {
1241     for (&id, mir) in &mir_map.map {
1242         for attr in tcx.map.attrs(id) {
1243             use syntax::attr::AttrMetaMethods;
1244             if attr.check_name("miri_run") {
1245                 let item = tcx.map.expect_item(id);
1246
1247                 println!("Interpreting: {}", item.name);
1248
1249                 let mut gecx = GlobalEvalContext::new(tcx, mir_map);
1250                 let mut fecx = FnEvalContext::new(&mut gecx);
1251                 match fecx.call_nested(mir) {
1252                     Ok(Some(return_ptr)) => fecx.memory.dump(return_ptr.alloc_id),
1253                     Ok(None) => println!("(diverging function returned)"),
1254                     Err(_e) => {
1255                         // TODO(tsion): Detect whether the error was already reported or not.
1256                         // tcx.sess.err(&e.to_string());
1257                     }
1258                 }
1259
1260                 println!("");
1261             }
1262         }
1263     }
1264 }
1265
1266 // TODO(tsion): Upstream these methods into rustc::ty::layout.
1267
1268 trait IntegerExt {
1269     fn size(self) -> Size;
1270 }
1271
1272 impl IntegerExt for layout::Integer {
1273     fn size(self) -> Size {
1274         use rustc::ty::layout::Integer::*;
1275         match self {
1276             I1 | I8 => Size::from_bits(8),
1277             I16 => Size::from_bits(16),
1278             I32 => Size::from_bits(32),
1279             I64 => Size::from_bits(64),
1280         }
1281     }
1282 }
1283
1284 trait StructExt {
1285     fn field_offset(&self, index: usize) -> Size;
1286 }
1287
1288 impl StructExt for layout::Struct {
1289     fn field_offset(&self, index: usize) -> Size {
1290         if index == 0 {
1291             Size::from_bytes(0)
1292         } else {
1293             self.offset_after_field[index - 1]
1294         }
1295     }
1296 }