]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/type_check.rs
Fix invalid associated type rendering in rustdoc
[rust.git] / src / librustc_mir / transform / type_check.rs
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.
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 //! This pass type-checks the MIR to ensure it is not broken.
12 #![allow(unreachable_code)]
13
14 use rustc::infer::{self, InferCtxt, InferOk};
15 use rustc::traits::{self, Reveal};
16 use rustc::ty::fold::TypeFoldable;
17 use rustc::ty::{self, Ty, TyCtxt, TypeVariants};
18 use rustc::middle::const_val::ConstVal;
19 use rustc::mir::*;
20 use rustc::mir::tcx::LvalueTy;
21 use rustc::mir::transform::{MirPass, MirSource, Pass};
22 use rustc::mir::visit::Visitor;
23 use std::fmt;
24 use syntax::ast;
25 use syntax_pos::{Span, DUMMY_SP};
26
27 use rustc_data_structures::indexed_vec::Idx;
28
29 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
30     tcx.sess.diagnostic().span_bug(span, msg);
31 }
32
33 macro_rules! span_mirbug {
34     ($context:expr, $elem:expr, $($message:tt)*) => ({
35         mirbug($context.tcx(), $context.last_span,
36                &format!("broken MIR ({:?}): {}", $elem, format!($($message)*)))
37     })
38 }
39
40 macro_rules! span_mirbug_and_err {
41     ($context:expr, $elem:expr, $($message:tt)*) => ({
42         {
43             span_mirbug!($context, $elem, $($message)*);
44             $context.error()
45         }
46     })
47 }
48
49 enum FieldAccessError {
50     OutOfRange { field_count: usize }
51 }
52
53 /// Verifies that MIR types are sane to not crash further checks.
54 ///
55 /// The sanitize_XYZ methods here take an MIR object and compute its
56 /// type, calling `span_mirbug` and returning an error type if there
57 /// is a problem.
58 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> {
59     cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
60     mir: &'a Mir<'tcx>,
61     last_span: Span,
62     errors_reported: bool
63 }
64
65 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
66     fn visit_span(&mut self, span: &Span) {
67         if *span != DUMMY_SP {
68             self.last_span = *span;
69         }
70     }
71
72     fn visit_lvalue(&mut self,
73                     lvalue: &Lvalue<'tcx>,
74                     _context: visit::LvalueContext,
75                     location: Location) {
76         self.sanitize_lvalue(lvalue, location);
77     }
78
79     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
80         self.super_constant(constant, location);
81         self.sanitize_type(constant, constant.ty);
82     }
83
84     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
85         self.super_rvalue(rvalue, location);
86         let rval_ty = rvalue.ty(self.mir, self.tcx());
87         self.sanitize_type(rvalue, rval_ty);
88     }
89
90     fn visit_mir(&mut self, mir: &Mir<'tcx>) {
91         self.sanitize_type(&"return type", mir.return_ty);
92         for local_decl in &mir.local_decls {
93             self.sanitize_type(local_decl, local_decl.ty);
94         }
95         if self.errors_reported {
96             return;
97         }
98         self.super_mir(mir);
99     }
100 }
101
102 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
103     fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
104         TypeVerifier {
105             cx: cx,
106             mir: mir,
107             last_span: mir.span,
108             errors_reported: false
109         }
110     }
111
112     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
113         self.cx.infcx.tcx
114     }
115
116     fn sanitize_type(&mut self, parent: &fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
117         if ty.needs_infer() || ty.has_escaping_regions() || ty.references_error() {
118             span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
119         } else {
120             ty
121         }
122     }
123
124     fn sanitize_lvalue(&mut self, lvalue: &Lvalue<'tcx>, location: Location) -> LvalueTy<'tcx> {
125         debug!("sanitize_lvalue: {:?}", lvalue);
126         match *lvalue {
127             Lvalue::Local(index) => LvalueTy::Ty { ty: self.mir.local_decls[index].ty },
128             Lvalue::Static(box Static { def_id, ty: sty }) => {
129                 let sty = self.sanitize_type(lvalue, sty);
130                 let ty = self.tcx().item_type(def_id);
131                 let ty = self.cx.normalize(&ty);
132                 if let Err(terr) = self.cx.eq_types(self.last_span, ty, sty) {
133                     span_mirbug!(
134                         self, lvalue, "bad static type ({:?}: {:?}): {:?}",
135                         ty, sty, terr);
136                 }
137                 LvalueTy::Ty { ty: sty }
138
139             },
140             Lvalue::Projection(ref proj) => {
141                 let base_ty = self.sanitize_lvalue(&proj.base, location);
142                 if let LvalueTy::Ty { ty } = base_ty {
143                     if ty.references_error() {
144                         assert!(self.errors_reported);
145                         return LvalueTy::Ty { ty: self.tcx().types.err };
146                     }
147                 }
148                 self.sanitize_projection(base_ty, &proj.elem, lvalue, location)
149             }
150         }
151     }
152
153     fn sanitize_projection(&mut self,
154                            base: LvalueTy<'tcx>,
155                            pi: &LvalueElem<'tcx>,
156                            lvalue: &Lvalue<'tcx>,
157                            location: Location)
158                            -> LvalueTy<'tcx> {
159         debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, lvalue);
160         let tcx = self.tcx();
161         let base_ty = base.to_ty(tcx);
162         let span = self.last_span;
163         match *pi {
164             ProjectionElem::Deref => {
165                 let deref_ty = base_ty.builtin_deref(true, ty::LvaluePreference::NoPreference);
166                 LvalueTy::Ty {
167                     ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
168                         span_mirbug_and_err!(
169                             self, lvalue, "deref of non-pointer {:?}", base_ty)
170                     })
171                 }
172             }
173             ProjectionElem::Index(ref i) => {
174                 self.visit_operand(i, location);
175                 let index_ty = i.ty(self.mir, tcx);
176                 if index_ty != tcx.types.usize {
177                     LvalueTy::Ty {
178                         ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i)
179                     }
180                 } else {
181                     LvalueTy::Ty {
182                         ty: base_ty.builtin_index().unwrap_or_else(|| {
183                             span_mirbug_and_err!(
184                                 self, lvalue, "index of non-array {:?}", base_ty)
185                         })
186                     }
187                 }
188             }
189             ProjectionElem::ConstantIndex { .. } => {
190                 // consider verifying in-bounds
191                 LvalueTy::Ty {
192                     ty: base_ty.builtin_index().unwrap_or_else(|| {
193                         span_mirbug_and_err!(
194                             self, lvalue, "index of non-array {:?}", base_ty)
195                     })
196                 }
197             }
198             ProjectionElem::Subslice { from, to } => {
199                 LvalueTy::Ty {
200                     ty: match base_ty.sty {
201                         ty::TyArray(inner, size) => {
202                             let min_size = (from as usize) + (to as usize);
203                             if let Some(rest_size) = size.checked_sub(min_size) {
204                                 tcx.mk_array(inner, rest_size)
205                             } else {
206                                 span_mirbug_and_err!(
207                                     self, lvalue, "taking too-small slice of {:?}", base_ty)
208                             }
209                         }
210                         ty::TySlice(..) => base_ty,
211                         _ => {
212                             span_mirbug_and_err!(
213                                 self, lvalue, "slice of non-array {:?}", base_ty)
214                         }
215                     }
216                 }
217             }
218             ProjectionElem::Downcast(adt_def1, index) =>
219                 match base_ty.sty {
220                     ty::TyAdt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
221                         if index >= adt_def.variants.len() {
222                             LvalueTy::Ty {
223                                 ty: span_mirbug_and_err!(
224                                     self,
225                                     lvalue,
226                                     "cast to variant #{:?} but enum only has {:?}",
227                                     index,
228                                     adt_def.variants.len())
229                             }
230                         } else {
231                             LvalueTy::Downcast {
232                                 adt_def: adt_def,
233                                 substs: substs,
234                                 variant_index: index
235                             }
236                         }
237                     }
238                     _ => LvalueTy::Ty {
239                         ty: span_mirbug_and_err!(
240                             self, lvalue, "can't downcast {:?} as {:?}",
241                             base_ty, adt_def1)
242                     }
243                 },
244             ProjectionElem::Field(field, fty) => {
245                 let fty = self.sanitize_type(lvalue, fty);
246                 match self.field_ty(lvalue, base, field) {
247                     Ok(ty) => {
248                         if let Err(terr) = self.cx.eq_types(span, ty, fty) {
249                             span_mirbug!(
250                                 self, lvalue, "bad field access ({:?}: {:?}): {:?}",
251                                 ty, fty, terr);
252                         }
253                     }
254                     Err(FieldAccessError::OutOfRange { field_count }) => {
255                         span_mirbug!(
256                             self, lvalue, "accessed field #{} but variant only has {}",
257                             field.index(), field_count)
258                     }
259                 }
260                 LvalueTy::Ty { ty: fty }
261             }
262         }
263     }
264
265     fn error(&mut self) -> Ty<'tcx> {
266         self.errors_reported = true;
267         self.tcx().types.err
268     }
269
270     fn field_ty(&mut self,
271                 parent: &fmt::Debug,
272                 base_ty: LvalueTy<'tcx>,
273                 field: Field)
274                 -> Result<Ty<'tcx>, FieldAccessError>
275     {
276         let tcx = self.tcx();
277
278         let (variant, substs) = match base_ty {
279             LvalueTy::Downcast { adt_def, substs, variant_index } => {
280                 (&adt_def.variants[variant_index], substs)
281             }
282             LvalueTy::Ty { ty } => match ty.sty {
283                 ty::TyAdt(adt_def, substs) if adt_def.is_univariant() => {
284                         (&adt_def.variants[0], substs)
285                     }
286                 ty::TyClosure(def_id, substs) => {
287                     return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
288                         Some(ty) => Ok(ty),
289                         None => Err(FieldAccessError::OutOfRange {
290                             field_count: substs.upvar_tys(def_id, tcx).count()
291                         })
292                     }
293                 }
294                 ty::TyTuple(tys, _) => {
295                     return match tys.get(field.index()) {
296                         Some(&ty) => Ok(ty),
297                         None => Err(FieldAccessError::OutOfRange {
298                             field_count: tys.len()
299                         })
300                     }
301                 }
302                 _ => return Ok(span_mirbug_and_err!(
303                     self, parent, "can't project out of {:?}", base_ty))
304             }
305         };
306
307         if let Some(field) = variant.fields.get(field.index()) {
308             Ok(self.cx.normalize(&field.ty(tcx, substs)))
309         } else {
310             Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
311         }
312     }
313 }
314
315 pub struct TypeChecker<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
316     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
317     fulfillment_cx: traits::FulfillmentContext<'tcx>,
318     last_span: Span,
319     body_id: ast::NodeId,
320 }
321
322 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
323     fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>, body_id: ast::NodeId) -> Self {
324         TypeChecker {
325             infcx: infcx,
326             fulfillment_cx: traits::FulfillmentContext::new(),
327             last_span: DUMMY_SP,
328             body_id: body_id,
329         }
330     }
331
332     fn misc(&self, span: Span) -> traits::ObligationCause<'tcx> {
333         traits::ObligationCause::misc(span, self.body_id)
334     }
335
336     pub fn register_infer_ok_obligations<T>(&mut self, infer_ok: InferOk<'tcx, T>) -> T {
337         for obligation in infer_ok.obligations {
338             self.fulfillment_cx.register_predicate_obligation(self.infcx, obligation);
339         }
340         infer_ok.value
341     }
342
343     fn sub_types(&mut self, sup: Ty<'tcx>, sub: Ty<'tcx>)
344                  -> infer::UnitResult<'tcx>
345     {
346         self.infcx.sub_types(false, &self.misc(self.last_span), sup, sub)
347             .map(|ok| self.register_infer_ok_obligations(ok))
348     }
349
350     fn eq_types(&mut self, span: Span, a: Ty<'tcx>, b: Ty<'tcx>)
351                 -> infer::UnitResult<'tcx>
352     {
353         self.infcx.eq_types(false, &self.misc(span), a, b)
354             .map(|ok| self.register_infer_ok_obligations(ok))
355     }
356
357     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
358         self.infcx.tcx
359     }
360
361     fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>) {
362         debug!("check_stmt: {:?}", stmt);
363         let tcx = self.tcx();
364         match stmt.kind {
365             StatementKind::Assign(ref lv, ref rv) => {
366                 let lv_ty = lv.ty(mir, tcx).to_ty(tcx);
367                 let rv_ty = rv.ty(mir, tcx);
368                 if let Err(terr) = self.sub_types(rv_ty, lv_ty) {
369                     span_mirbug!(self, stmt, "bad assignment ({:?} = {:?}): {:?}",
370                                  lv_ty, rv_ty, terr);
371                 }
372             }
373             StatementKind::SetDiscriminant{ ref lvalue, variant_index } => {
374                 let lvalue_type = lvalue.ty(mir, tcx).to_ty(tcx);
375                 let adt = match lvalue_type.sty {
376                     TypeVariants::TyAdt(adt, _) if adt.is_enum() => adt,
377                     _ => {
378                         span_bug!(stmt.source_info.span,
379                                   "bad set discriminant ({:?} = {:?}): lhs is not an enum",
380                                   lvalue,
381                                   variant_index);
382                     }
383                 };
384                 if variant_index >= adt.variants.len() {
385                      span_bug!(stmt.source_info.span,
386                                "bad set discriminant ({:?} = {:?}): value of of range",
387                                lvalue,
388                                variant_index);
389                 };
390             }
391             StatementKind::StorageLive(ref lv) |
392             StatementKind::StorageDead(ref lv) => {
393                 match *lv {
394                     Lvalue::Local(_) => {}
395                     _ => {
396                         span_mirbug!(self, stmt, "bad lvalue: expected local");
397                     }
398                 }
399             }
400             StatementKind::InlineAsm { .. } |
401             StatementKind::Nop => {}
402         }
403     }
404
405     fn check_terminator(&mut self,
406                         mir: &Mir<'tcx>,
407                         term: &Terminator<'tcx>) {
408         debug!("check_terminator: {:?}", term);
409         let tcx = self.tcx();
410         match term.kind {
411             TerminatorKind::Goto { .. } |
412             TerminatorKind::Resume |
413             TerminatorKind::Return |
414             TerminatorKind::Unreachable |
415             TerminatorKind::Drop { .. } => {
416                 // no checks needed for these
417             }
418
419
420             TerminatorKind::DropAndReplace {
421                 ref location,
422                 ref value,
423                 ..
424             } => {
425                 let lv_ty = location.ty(mir, tcx).to_ty(tcx);
426                 let rv_ty = value.ty(mir, tcx);
427                 if let Err(terr) = self.sub_types(rv_ty, lv_ty) {
428                     span_mirbug!(self, term, "bad DropAndReplace ({:?} = {:?}): {:?}",
429                                  lv_ty, rv_ty, terr);
430                 }
431             }
432             TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
433                 let discr_ty = discr.ty(mir, tcx);
434                 if let Err(terr) = self.sub_types(discr_ty, switch_ty) {
435                     span_mirbug!(self, term, "bad SwitchInt ({:?} on {:?}): {:?}",
436                                  switch_ty, discr_ty, terr);
437                 }
438                 if !switch_ty.is_integral() && !switch_ty.is_char() &&
439                     !switch_ty.is_bool()
440                 {
441                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}",switch_ty);
442                 }
443                 // FIXME: check the values
444             }
445             TerminatorKind::Call { ref func, ref args, ref destination, .. } => {
446                 let func_ty = func.ty(mir, tcx);
447                 debug!("check_terminator: call, func_ty={:?}", func_ty);
448                 let sig = match func_ty.sty {
449                     ty::TyFnDef(.., sig) | ty::TyFnPtr(sig) => sig,
450                     _ => {
451                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
452                         return;
453                     }
454                 };
455                 let sig = tcx.erase_late_bound_regions(&sig);
456                 let sig = self.normalize(&sig);
457                 self.check_call_dest(mir, term, &sig, destination);
458
459                 if self.is_box_free(func) {
460                     self.check_box_free_inputs(mir, term, &sig, args);
461                 } else {
462                     self.check_call_inputs(mir, term, &sig, args);
463                 }
464             }
465             TerminatorKind::Assert { ref cond, ref msg, .. } => {
466                 let cond_ty = cond.ty(mir, tcx);
467                 if cond_ty != tcx.types.bool {
468                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
469                 }
470
471                 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
472                     if len.ty(mir, tcx) != tcx.types.usize {
473                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
474                     }
475                     if index.ty(mir, tcx) != tcx.types.usize {
476                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
477                     }
478                 }
479             }
480         }
481     }
482
483     fn check_call_dest(&mut self,
484                        mir: &Mir<'tcx>,
485                        term: &Terminator<'tcx>,
486                        sig: &ty::FnSig<'tcx>,
487                        destination: &Option<(Lvalue<'tcx>, BasicBlock)>) {
488         let tcx = self.tcx();
489         match *destination {
490             Some((ref dest, _)) => {
491                 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
492                 if let Err(terr) = self.sub_types(sig.output(), dest_ty) {
493                     span_mirbug!(self, term,
494                                  "call dest mismatch ({:?} <- {:?}): {:?}",
495                                  dest_ty, sig.output(), terr);
496                 }
497             },
498             None => {
499                 // FIXME(canndrew): This is_never should probably be an is_uninhabited
500                 if !sig.output().is_never() {
501                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
502                 }
503             },
504         }
505     }
506
507     fn check_call_inputs(&mut self,
508                          mir: &Mir<'tcx>,
509                          term: &Terminator<'tcx>,
510                          sig: &ty::FnSig<'tcx>,
511                          args: &[Operand<'tcx>])
512     {
513         debug!("check_call_inputs({:?}, {:?})", sig, args);
514         if args.len() < sig.inputs().len() ||
515            (args.len() > sig.inputs().len() && !sig.variadic) {
516             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
517         }
518         for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
519             let op_arg_ty = op_arg.ty(mir, self.tcx());
520             if let Err(terr) = self.sub_types(op_arg_ty, fn_arg) {
521                 span_mirbug!(self, term, "bad arg #{:?} ({:?} <- {:?}): {:?}",
522                              n, fn_arg, op_arg_ty, terr);
523             }
524         }
525     }
526
527     fn is_box_free(&self, operand: &Operand<'tcx>) -> bool {
528         match operand {
529             &Operand::Constant(Constant {
530                 literal: Literal::Value {
531                     value: ConstVal::Function(def_id, _), ..
532                 }, ..
533             }) => {
534                 Some(def_id) == self.tcx().lang_items.box_free_fn()
535             }
536             _ => false,
537         }
538     }
539
540     fn check_box_free_inputs(&mut self,
541                              mir: &Mir<'tcx>,
542                              term: &Terminator<'tcx>,
543                              sig: &ty::FnSig<'tcx>,
544                              args: &[Operand<'tcx>])
545     {
546         debug!("check_box_free_inputs");
547
548         // box_free takes a Box as a pointer. Allow for that.
549
550         if sig.inputs().len() != 1 {
551             span_mirbug!(self, term, "box_free should take 1 argument");
552             return;
553         }
554
555         let pointee_ty = match sig.inputs()[0].sty {
556             ty::TyRawPtr(mt) => mt.ty,
557             _ => {
558                 span_mirbug!(self, term, "box_free should take a raw ptr");
559                 return;
560             }
561         };
562
563         if args.len() != 1 {
564             span_mirbug!(self, term, "box_free called with wrong # of args");
565             return;
566         }
567
568         let ty = args[0].ty(mir, self.tcx());
569         let arg_ty = match ty.sty {
570             ty::TyRawPtr(mt) => mt.ty,
571             ty::TyAdt(def, _) if def.is_box() => ty.boxed_ty(),
572             _ => {
573                 span_mirbug!(self, term, "box_free called with bad arg ty");
574                 return;
575             }
576         };
577
578         if let Err(terr) = self.sub_types(arg_ty, pointee_ty) {
579             span_mirbug!(self, term, "bad box_free arg ({:?} <- {:?}): {:?}",
580                          pointee_ty, arg_ty, terr);
581         }
582     }
583
584     fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block: &BasicBlockData<'tcx>)
585     {
586         let is_cleanup = block.is_cleanup;
587         self.last_span = block.terminator().source_info.span;
588         match block.terminator().kind {
589             TerminatorKind::Goto { target } =>
590                 self.assert_iscleanup(mir, block, target, is_cleanup),
591             TerminatorKind::SwitchInt { ref targets, .. } => {
592                 for target in targets {
593                     self.assert_iscleanup(mir, block, *target, is_cleanup);
594                 }
595             }
596             TerminatorKind::Resume => {
597                 if !is_cleanup {
598                     span_mirbug!(self, block, "resume on non-cleanup block!")
599                 }
600             }
601             TerminatorKind::Return => {
602                 if is_cleanup {
603                     span_mirbug!(self, block, "return on cleanup block")
604                 }
605             }
606             TerminatorKind::Unreachable => {}
607             TerminatorKind::Drop { target, unwind, .. } |
608             TerminatorKind::DropAndReplace { target, unwind, .. } |
609             TerminatorKind::Assert { target, cleanup: unwind, .. } => {
610                 self.assert_iscleanup(mir, block, target, is_cleanup);
611                 if let Some(unwind) = unwind {
612                     if is_cleanup {
613                         span_mirbug!(self, block, "unwind on cleanup block")
614                     }
615                     self.assert_iscleanup(mir, block, unwind, true);
616                 }
617             }
618             TerminatorKind::Call { ref destination, cleanup, .. } => {
619                 if let &Some((_, target)) = destination {
620                     self.assert_iscleanup(mir, block, target, is_cleanup);
621                 }
622                 if let Some(cleanup) = cleanup {
623                     if is_cleanup {
624                         span_mirbug!(self, block, "cleanup on cleanup block")
625                     }
626                     self.assert_iscleanup(mir, block, cleanup, true);
627                 }
628             }
629         }
630     }
631
632     fn assert_iscleanup(&mut self,
633                         mir: &Mir<'tcx>,
634                         ctxt: &fmt::Debug,
635                         bb: BasicBlock,
636                         iscleanuppad: bool)
637     {
638         if mir[bb].is_cleanup != iscleanuppad {
639             span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}",
640                          bb, iscleanuppad);
641         }
642     }
643
644     fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
645         self.last_span = mir.span;
646         debug!("run_on_mir: {:?}", mir.span);
647         for block in mir.basic_blocks() {
648             for stmt in &block.statements {
649                 if stmt.source_info.span != DUMMY_SP {
650                     self.last_span = stmt.source_info.span;
651                 }
652                 self.check_stmt(mir, stmt);
653             }
654
655             self.check_terminator(mir, block.terminator());
656             self.check_iscleanup(mir, block);
657         }
658     }
659
660
661     fn normalize<T>(&mut self, value: &T) -> T
662         where T: fmt::Debug + TypeFoldable<'tcx>
663     {
664         let mut selcx = traits::SelectionContext::new(self.infcx);
665         let cause = traits::ObligationCause::misc(self.last_span, ast::CRATE_NODE_ID);
666         let traits::Normalized { value, obligations } =
667             traits::normalize(&mut selcx, cause, value);
668
669         debug!("normalize: value={:?} obligations={:?}",
670                value,
671                obligations);
672
673         let mut fulfill_cx = &mut self.fulfillment_cx;
674         for obligation in obligations {
675             fulfill_cx.register_predicate_obligation(self.infcx, obligation);
676         }
677
678         value
679     }
680
681     fn verify_obligations(&mut self, mir: &Mir<'tcx>) {
682         self.last_span = mir.span;
683         if let Err(e) = self.fulfillment_cx.select_all_or_error(self.infcx) {
684             span_mirbug!(self, "", "errors selecting obligation: {:?}",
685                          e);
686         }
687     }
688 }
689
690 pub struct TypeckMir;
691
692 impl TypeckMir {
693     pub fn new() -> Self {
694         TypeckMir
695     }
696 }
697
698 impl<'tcx> MirPass<'tcx> for TypeckMir {
699     fn run_pass<'a>(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
700                     src: MirSource, mir: &mut Mir<'tcx>) {
701         debug!("run_pass: {}", tcx.node_path_str(src.item_id()));
702
703         if tcx.sess.err_count() > 0 {
704             // compiling a broken program can obviously result in a
705             // broken MIR, so try not to report duplicate errors.
706             return;
707         }
708         let param_env = ty::ParameterEnvironment::for_item(tcx, src.item_id());
709         tcx.infer_ctxt(param_env, Reveal::UserFacing).enter(|infcx| {
710             let mut checker = TypeChecker::new(&infcx, src.item_id());
711             {
712                 let mut verifier = TypeVerifier::new(&mut checker, mir);
713                 verifier.visit_mir(mir);
714                 if verifier.errors_reported {
715                     // don't do further checks to avoid ICEs
716                     return;
717                 }
718             }
719             checker.typeck_mir(mir);
720             checker.verify_obligations(mir);
721         });
722     }
723 }
724
725 impl Pass for TypeckMir {
726 }