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.
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.
11 //! This pass type-checks the MIR to ensure it is not broken.
12 #![allow(unreachable_code)]
14 use borrow_check::borrow_set::BorrowSet;
15 use borrow_check::location::LocationTable;
16 use borrow_check::nll::constraint_set::{ConstraintSet, OutlivesConstraint};
17 use borrow_check::nll::facts::AllFacts;
18 use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
19 use borrow_check::nll::universal_regions::UniversalRegions;
20 use borrow_check::nll::ToRegionVid;
21 use dataflow::move_paths::MoveData;
22 use dataflow::FlowAtLocation;
23 use dataflow::MaybeInitializedPlaces;
25 use rustc::hir::def_id::DefId;
26 use rustc::infer::canonical::QueryRegionConstraint;
27 use rustc::infer::region_constraints::GenericKind;
28 use rustc::infer::{InferCtxt, LateBoundRegionConversionTime};
29 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
30 use rustc::mir::tcx::PlaceTy;
31 use rustc::mir::visit::{PlaceContext, Visitor};
33 use rustc::traits::query::type_op;
34 use rustc::traits::query::{Fallible, NoSolution};
35 use rustc::ty::fold::TypeFoldable;
36 use rustc::ty::{self, ToPolyTraitRef, Ty, TyCtxt, TypeVariants};
38 use syntax_pos::{Span, DUMMY_SP};
39 use transform::{MirPass, MirSource};
40 use util::liveness::LivenessResults;
42 use rustc_data_structures::fx::FxHashSet;
43 use rustc_data_structures::indexed_vec::Idx;
45 macro_rules! span_mirbug {
46 ($context:expr, $elem:expr, $($message:tt)*) => ({
47 $crate::borrow_check::nll::type_check::mirbug(
51 "broken MIR in {:?} ({:?}): {}",
54 format_args!($($message)*),
60 macro_rules! span_mirbug_and_err {
61 ($context:expr, $elem:expr, $($message:tt)*) => ({
63 span_mirbug!($context, $elem, $($message)*);
69 mod constraint_conversion;
73 /// Type checks the given `mir` in the context of the inference
74 /// context `infcx`. Returns any region constraints that have yet to
75 /// be proven. This result is includes liveness constraints that
76 /// ensure that regions appearing in the types of all local variables
77 /// are live at all points where that local variable may later be
80 /// This phase of type-check ought to be infallible -- this is because
81 /// the original, HIR-based type-check succeeded. So if any errors
82 /// occur here, we will get a `bug!` reported.
86 /// - `infcx` -- inference context to use
87 /// - `param_env` -- parameter environment to use for trait solving
88 /// - `mir` -- MIR to type-check
89 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
90 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
91 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
92 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
93 /// to outlive; should represent the fn body
94 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
95 /// the types of the input parameters found in the MIR itself will be equated with these
96 /// - `output_ty` -- fully liberaetd, but **not** normalized, expected return type;
97 /// the type for the RETURN_PLACE will be equated with this
98 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
99 /// constraints for the regions in the types of variables
100 /// - `flow_inits` -- results of a maybe-init dataflow analysis
101 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
102 pub(crate) fn type_check<'gcx, 'tcx>(
103 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
104 param_env: ty::ParamEnv<'gcx>,
107 universal_regions: &UniversalRegions<'tcx>,
108 location_table: &LocationTable,
109 borrow_set: &BorrowSet<'tcx>,
110 liveness: &LivenessResults,
111 all_facts: &mut Option<AllFacts>,
112 flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
113 move_data: &MoveData<'tcx>,
114 ) -> MirTypeckRegionConstraints<'tcx> {
115 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
121 &universal_regions.region_bound_pairs,
122 Some(implicit_region_bound),
123 Some(BorrowCheckContext {
130 liveness::generate(cx, mir, liveness, flow_inits, move_data);
132 cx.equate_inputs_and_outputs(mir, mir_def_id, universal_regions);
137 fn type_check_internal<'gcx, 'tcx>(
138 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
140 param_env: ty::ParamEnv<'gcx>,
142 region_bound_pairs: &[(ty::Region<'tcx>, GenericKind<'tcx>)],
143 implicit_region_bound: Option<ty::Region<'tcx>>,
144 borrowck_context: Option<BorrowCheckContext<'_, 'tcx>>,
145 extra: &mut dyn FnMut(&mut TypeChecker<'_, 'gcx, 'tcx>),
146 ) -> MirTypeckRegionConstraints<'tcx> {
147 let mut checker = TypeChecker::new(
153 implicit_region_bound,
156 let errors_reported = {
157 let mut verifier = TypeVerifier::new(&mut checker, mir);
158 verifier.visit_mir(mir);
159 verifier.errors_reported
162 if !errors_reported {
163 // if verifier failed, don't do further checks to avoid ICEs
164 checker.typeck_mir(mir);
172 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
173 // We sometimes see MIR failures (notably predicate failures) due to
174 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
175 // to avoid reporting bugs in those cases.
176 tcx.sess.diagnostic().delay_span_bug(span, msg);
179 enum FieldAccessError {
180 OutOfRange { field_count: usize },
183 /// Verifies that MIR types are sane to not crash further checks.
185 /// The sanitize_XYZ methods here take an MIR object and compute its
186 /// type, calling `span_mirbug` and returning an error type if there
188 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'b + 'tcx, 'tcx: 'b> {
189 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
193 errors_reported: bool,
196 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
197 fn visit_span(&mut self, span: &Span) {
198 if !span.is_dummy() {
199 self.last_span = *span;
203 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
204 self.sanitize_place(place, location, context);
207 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
208 self.super_constant(constant, location);
209 self.sanitize_constant(constant, location);
210 self.sanitize_type(constant, constant.ty);
213 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
214 self.super_rvalue(rvalue, location);
215 let rval_ty = rvalue.ty(self.mir, self.tcx());
216 self.sanitize_type(rvalue, rval_ty);
219 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
220 self.super_local_decl(local, local_decl);
221 self.sanitize_type(local_decl, local_decl.ty);
224 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
225 self.sanitize_type(&"return type", mir.return_ty());
226 for local_decl in &mir.local_decls {
227 self.sanitize_type(local_decl, local_decl.ty);
229 if self.errors_reported {
236 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
237 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
240 mir_def_id: cx.mir_def_id,
243 errors_reported: false,
247 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
251 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
252 if ty.has_escaping_regions() || ty.references_error() {
253 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
259 /// Checks that the constant's `ty` field matches up with what
260 /// would be expected from its literal.
261 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
263 "sanitize_constant(constant={:?}, location={:?})",
267 let expected_ty = match constant.literal {
268 Literal::Value { value } => {
269 // FIXME(#46702) -- We need some way to get the predicates
270 // associated with the "pre-evaluated" form of the
271 // constant. For example, consider that the constant
272 // may have associated constant projections (`<Foo as
273 // Trait<'a, 'b>>::SOME_CONST`) that impose
274 // constraints on `'a` and `'b`. These constraints
275 // would be lost if we just look at the normalized
277 if let ty::TyFnDef(def_id, substs) = value.ty.sty {
278 let tcx = self.tcx();
279 let type_checker = &mut self.cx;
281 // FIXME -- For now, use the substitutions from
282 // `value.ty` rather than `value.val`. The
283 // renumberer will rewrite them to independent
284 // sets of regions; in principle, we ought to
285 // derive the type of the `value.val` from "first
286 // principles" and equate with value.ty, but as we
287 // are transitioning to the miri-based system, we
288 // don't have a handy function for that, so for
289 // now we just ignore `value.val` regions.
291 let instantiated_predicates =
292 tcx.predicates_of(def_id).instantiate(tcx, substs);
293 type_checker.normalize_and_prove_instantiated_predicates(
294 instantiated_predicates,
302 Literal::Promoted { .. } => {
303 // FIXME -- promoted MIR return types reference
304 // various "free regions" (e.g., scopes and things)
305 // that they ought not to do. We have to figure out
306 // how best to handle that -- probably we want treat
307 // promoted MIR much like closures, renumbering all
308 // their free regions and propagating constraints
309 // upwards. We have the same acyclic guarantees, so
310 // that should be possible. But for now, ignore them.
312 // let promoted_mir = &self.mir.promoted[index];
313 // promoted_mir.return_ty()
318 debug!("sanitize_constant: expected_ty={:?}", expected_ty);
320 if let Err(terr) = self
322 .eq_types(expected_ty, constant.ty, location.boring())
327 "constant {:?} should have type {:?} but has {:?} ({:?})",
336 /// Checks that the types internal to the `place` match up with
337 /// what would be expected.
342 context: PlaceContext,
344 debug!("sanitize_place: {:?}", place);
345 let place_ty = match *place {
346 Place::Local(index) => PlaceTy::Ty {
347 ty: self.mir.local_decls[index].ty,
349 Place::Static(box Static { def_id, ty: sty }) => {
350 let sty = self.sanitize_type(place, sty);
351 let ty = self.tcx().type_of(def_id);
352 let ty = self.cx.normalize(ty, location);
353 if let Err(terr) = self.cx.eq_types(ty, sty, location.boring()) {
357 "bad static type ({:?}: {:?}): {:?}",
363 PlaceTy::Ty { ty: sty }
365 Place::Projection(ref proj) => {
366 let base_context = if context.is_mutating_use() {
367 PlaceContext::Projection(Mutability::Mut)
369 PlaceContext::Projection(Mutability::Not)
371 let base_ty = self.sanitize_place(&proj.base, location, base_context);
372 if let PlaceTy::Ty { ty } = base_ty {
373 if ty.references_error() {
374 assert!(self.errors_reported);
376 ty: self.tcx().types.err,
380 self.sanitize_projection(base_ty, &proj.elem, place, location)
383 if let PlaceContext::Copy = context {
384 let tcx = self.tcx();
385 let trait_ref = ty::TraitRef {
386 def_id: tcx.lang_items().copy_trait().unwrap(),
387 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
390 // In order to have a Copy operand, the type T of the value must be Copy. Note that we
391 // prove that T: Copy, rather than using the type_moves_by_default test. This is
392 // important because type_moves_by_default ignores the resulting region obligations and
393 // assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
394 // (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
395 // fully apply: in effect, the rule is that if a value of some type could implement
396 // Copy, then it must.
397 self.cx.prove_trait_ref(trait_ref, location.interesting());
402 fn sanitize_projection(
405 pi: &PlaceElem<'tcx>,
409 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
410 let tcx = self.tcx();
411 let base_ty = base.to_ty(tcx);
413 ProjectionElem::Deref => {
414 let deref_ty = base_ty.builtin_deref(true);
416 ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
417 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
421 ProjectionElem::Index(i) => {
422 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
423 if index_ty != tcx.types.usize {
425 ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
429 ty: base_ty.builtin_index().unwrap_or_else(|| {
430 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
435 ProjectionElem::ConstantIndex { .. } => {
436 // consider verifying in-bounds
438 ty: base_ty.builtin_index().unwrap_or_else(|| {
439 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
443 ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
444 ty: match base_ty.sty {
445 ty::TyArray(inner, size) => {
446 let size = size.unwrap_usize(tcx);
447 let min_size = (from as u64) + (to as u64);
448 if let Some(rest_size) = size.checked_sub(min_size) {
449 tcx.mk_array(inner, rest_size)
451 span_mirbug_and_err!(
454 "taking too-small slice of {:?}",
459 ty::TySlice(..) => base_ty,
460 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
463 ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
464 ty::TyAdt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
465 if index >= adt_def.variants.len() {
467 ty: span_mirbug_and_err!(
470 "cast to variant #{:?} but enum only has {:?}",
472 adt_def.variants.len()
479 variant_index: index,
484 ty: span_mirbug_and_err!(
487 "can't downcast {:?} as {:?}",
493 ProjectionElem::Field(field, fty) => {
494 let fty = self.sanitize_type(place, fty);
495 match self.field_ty(place, base, field, location) {
496 Ok(ty) => if let Err(terr) = self.cx.eq_types(ty, fty, location.boring()) {
500 "bad field access ({:?}: {:?}): {:?}",
506 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
509 "accessed field #{} but variant only has {}",
514 PlaceTy::Ty { ty: fty }
519 fn error(&mut self) -> Ty<'tcx> {
520 self.errors_reported = true;
526 parent: &dyn fmt::Debug,
527 base_ty: PlaceTy<'tcx>,
530 ) -> Result<Ty<'tcx>, FieldAccessError> {
531 let tcx = self.tcx();
533 let (variant, substs) = match base_ty {
538 } => (&adt_def.variants[variant_index], substs),
539 PlaceTy::Ty { ty } => match ty.sty {
540 ty::TyAdt(adt_def, substs) if !adt_def.is_enum() => (&adt_def.variants[0], substs),
541 ty::TyClosure(def_id, substs) => {
542 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
544 None => Err(FieldAccessError::OutOfRange {
545 field_count: substs.upvar_tys(def_id, tcx).count(),
549 ty::TyGenerator(def_id, substs, _) => {
550 // Try pre-transform fields first (upvars and current state)
551 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
555 // Then try `field_tys` which contains all the fields, but it
556 // requires the final optimized MIR.
557 return match substs.field_tys(def_id, tcx).nth(field.index()) {
559 None => Err(FieldAccessError::OutOfRange {
560 field_count: substs.field_tys(def_id, tcx).count(),
564 ty::TyTuple(tys) => {
565 return match tys.get(field.index()) {
567 None => Err(FieldAccessError::OutOfRange {
568 field_count: tys.len(),
573 return Ok(span_mirbug_and_err!(
576 "can't project out of {:?}",
583 if let Some(field) = variant.fields.get(field.index()) {
584 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
586 Err(FieldAccessError::OutOfRange {
587 field_count: variant.fields.len(),
593 /// The MIR type checker. Visits the MIR and enforces all the
594 /// constraints needed for it to be valid and well-typed. Along the
595 /// way, it accrues region constraints -- these can later be used by
596 /// NLL region checking.
597 struct TypeChecker<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
598 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
599 param_env: ty::ParamEnv<'gcx>,
603 region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
604 implicit_region_bound: Option<ty::Region<'tcx>>,
605 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
606 constraints: MirTypeckRegionConstraints<'tcx>,
607 borrowck_context: Option<BorrowCheckContext<'a, 'tcx>>,
610 struct BorrowCheckContext<'a, 'tcx: 'a> {
611 universal_regions: &'a UniversalRegions<'tcx>,
612 location_table: &'a LocationTable,
613 all_facts: &'a mut Option<AllFacts>,
614 borrow_set: &'a BorrowSet<'tcx>,
617 /// A collection of region constraints that must be satisfied for the
618 /// program to be considered well-typed.
620 crate struct MirTypeckRegionConstraints<'tcx> {
621 /// In general, the type-checker is not responsible for enforcing
622 /// liveness constraints; this job falls to the region inferencer,
623 /// which performs a liveness analysis. However, in some limited
624 /// cases, the MIR type-checker creates temporary regions that do
625 /// not otherwise appear in the MIR -- in particular, the
626 /// late-bound regions that it instantiates at call-sites -- and
627 /// hence it must report on their liveness constraints.
628 crate liveness_set: Vec<(ty::Region<'tcx>, Location)>,
630 crate outlives_constraints: ConstraintSet,
632 crate type_tests: Vec<TypeTest<'tcx>>,
635 /// The `Locations` type summarizes *where* region constraints are
636 /// required to hold. Normally, this is at a particular point which
637 /// created the obligation, but for constraints that the user gave, we
638 /// want the constraint to hold at all points.
639 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
641 /// Indicates that a type constraint should always be true. This
642 /// is particularly important in the new borrowck analysis for
643 /// things like the type of the return slot. Consider this
647 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
649 /// return &y; // error
653 /// Here, we wind up with the signature from the return type being
654 /// something like `&'1 u32` where `'1` is a universal region. But
655 /// the type of the return slot `_0` is something like `&'2 u32`
656 /// where `'2` is an existential region variable. The type checker
657 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
658 /// older NLL analysis, we required this only at the entry point
659 /// to the function. By the nature of the constraints, this wound
660 /// up propagating to all points reachable from start (because
661 /// `'1` -- as a universal region -- is live everywhere). In the
662 /// newer analysis, though, this doesn't work: `_0` is considered
663 /// dead at the start (it has no usable value) and hence this type
664 /// equality is basically a no-op. Then, later on, when we do `_0
665 /// = &'3 y`, that region `'3` never winds up related to the
666 /// universal region `'1` and hence no error occurs. Therefore, we
667 /// use Locations::All instead, which ensures that the `'1` and
668 /// `'2` are equal everything. We also use this for other
669 /// user-given type annotations; e.g., if the user wrote `let mut
670 /// x: &'static u32 = ...`, we would ensure that all values
671 /// assigned to `x` are of `'static` lifetime.
674 /// A "boring" constraint (caused by the given location) is one that
675 /// the user probably doesn't want to see described in diagnostics,
676 /// because it is kind of an artifact of the type system setup.
678 /// Example: `x = Foo { field: y }` technically creates
679 /// intermediate regions representing the "type of `Foo { field: y
680 /// }`", and data flows from `y` into those variables, but they
681 /// are not very interesting. The assignment into `x` on the other
685 /// An *important* outlives constraint (caused by the given
686 /// location) is one that would be useful to highlight in
687 /// diagnostics, because it represents a point where references
688 /// flow from one spot to another (e.g., `x = y`)
689 Interesting(Location),
693 pub fn from_location(&self) -> Option<Location> {
695 Locations::All => None,
696 Locations::Boring(from_location) | Locations::Interesting(from_location) => {
702 /// Gets a span representing the location.
703 pub fn span(&self, mir: &Mir<'_>) -> Span {
704 let span_location = match self {
705 Locations::All => Location::START,
706 Locations::Boring(l) | Locations::Interesting(l) => *l,
708 mir.source_info(span_location).span
712 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
714 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
717 param_env: ty::ParamEnv<'gcx>,
718 region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
719 implicit_region_bound: Option<ty::Region<'tcx>>,
720 borrowck_context: Option<BorrowCheckContext<'a, 'tcx>>,
729 implicit_region_bound,
731 reported_errors: FxHashSet(),
732 constraints: MirTypeckRegionConstraints::default(),
736 /// Given some operation `op` that manipulates types, proves
737 /// predicates, or otherwise uses the inference context, executes
738 /// `op` and then executes all the further obligations that `op`
739 /// returns. This will yield a set of outlives constraints amongst
740 /// regions which are extracted and stored as having occured at
743 /// **Any `rustc::infer` operations that might generate region
744 /// constraints should occur within this method so that those
745 /// constraints can be properly localized!**
746 fn fully_perform_op<R>(
748 locations: Locations,
749 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
751 let (r, opt_data) = op.fully_perform(self.infcx)?;
753 if let Some(data) = &opt_data {
754 self.push_region_constraints(locations, data);
760 fn push_region_constraints(
762 locations: Locations,
763 data: &[QueryRegionConstraint<'tcx>],
766 "push_region_constraints: constraints generated at {:?} are {:#?}",
770 if let Some(borrowck_context) = &mut self.borrowck_context {
771 constraint_conversion::ConstraintConversion::new(
773 borrowck_context.universal_regions,
774 borrowck_context.location_table,
775 self.region_bound_pairs,
776 self.implicit_region_bound,
779 &mut self.constraints.outlives_constraints,
780 &mut self.constraints.type_tests,
781 &mut borrowck_context.all_facts,
782 ).convert_all(&data);
786 fn sub_types(&mut self, sub: Ty<'tcx>, sup: Ty<'tcx>, locations: Locations) -> Fallible<()> {
787 let param_env = self.param_env;
788 self.fully_perform_op(
790 param_env.and(type_op::subtype::Subtype::new(sub, sup)),
794 fn eq_types(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, locations: Locations) -> Fallible<()> {
795 let param_env = self.param_env;
796 self.fully_perform_op(locations, param_env.and(type_op::eq::Eq::new(b, a)))
799 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
803 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
804 debug!("check_stmt: {:?}", stmt);
805 let tcx = self.tcx();
807 StatementKind::Assign(ref place, ref rv) => {
808 // Assignments to temporaries are not "interesting";
809 // they are not caused by the user, but rather artifacts
810 // of lowering. Assignments to other sorts of places *are* interesting
812 let is_temp = if let Place::Local(l) = place {
813 !mir.local_decls[*l].is_user_variable.is_some()
818 let locations = if is_temp {
821 location.interesting()
824 let place_ty = place.ty(mir, tcx).to_ty(tcx);
825 let rv_ty = rv.ty(mir, tcx);
826 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
830 "bad assignment ({:?} = {:?}): {:?}",
836 self.check_rvalue(mir, rv, location);
837 let trait_ref = ty::TraitRef {
838 def_id: tcx.lang_items().sized_trait().unwrap(),
839 substs: tcx.mk_substs_trait(place_ty, &[]),
841 self.prove_trait_ref(trait_ref, location.interesting());
843 StatementKind::SetDiscriminant {
847 let place_type = place.ty(mir, tcx).to_ty(tcx);
848 let adt = match place_type.sty {
849 TypeVariants::TyAdt(adt, _) if adt.is_enum() => adt,
852 stmt.source_info.span,
853 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
859 if variant_index >= adt.variants.len() {
861 stmt.source_info.span,
862 "bad set discriminant ({:?} = {:?}): value of of range",
868 StatementKind::UserAssertTy(ref c_ty, ref local) => {
869 let local_ty = mir.local_decls()[*local].ty;
870 let (ty, _) = self.infcx
871 .instantiate_canonical_with_fresh_inference_vars(stmt.source_info.span, c_ty);
873 "check_stmt: user_assert_ty ty={:?} local_ty={:?}",
876 if let Err(terr) = self.eq_types(ty, local_ty, Locations::All) {
880 "bad type assert ({:?} = {:?}): {:?}",
887 StatementKind::ReadForMatch(_)
888 | StatementKind::StorageLive(_)
889 | StatementKind::StorageDead(_)
890 | StatementKind::InlineAsm { .. }
891 | StatementKind::EndRegion(_)
892 | StatementKind::Validate(..)
893 | StatementKind::Nop => {}
900 term: &Terminator<'tcx>,
901 term_location: Location,
903 debug!("check_terminator: {:?}", term);
904 let tcx = self.tcx();
906 TerminatorKind::Goto { .. }
907 | TerminatorKind::Resume
908 | TerminatorKind::Abort
909 | TerminatorKind::Return
910 | TerminatorKind::GeneratorDrop
911 | TerminatorKind::Unreachable
912 | TerminatorKind::Drop { .. }
913 | TerminatorKind::FalseEdges { .. }
914 | TerminatorKind::FalseUnwind { .. } => {
915 // no checks needed for these
918 TerminatorKind::DropAndReplace {
924 let place_ty = location.ty(mir, tcx).to_ty(tcx);
925 let rv_ty = value.ty(mir, tcx);
927 let locations = term_location.interesting();
928 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
932 "bad DropAndReplace ({:?} = {:?}): {:?}",
939 TerminatorKind::SwitchInt {
944 let discr_ty = discr.ty(mir, tcx);
945 if let Err(terr) = self.sub_types(discr_ty, switch_ty, term_location.boring()) {
949 "bad SwitchInt ({:?} on {:?}): {:?}",
955 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
956 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
958 // FIXME: check the values
960 TerminatorKind::Call {
966 let func_ty = func.ty(mir, tcx);
967 debug!("check_terminator: call, func_ty={:?}", func_ty);
968 let sig = match func_ty.sty {
969 ty::TyFnDef(..) | ty::TyFnPtr(_) => func_ty.fn_sig(tcx),
971 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
975 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
976 term.source_info.span,
977 LateBoundRegionConversionTime::FnCall,
980 let sig = self.normalize(sig, term_location);
981 self.check_call_dest(mir, term, &sig, destination, term_location);
983 self.prove_predicates(
984 sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
985 term_location.boring(),
988 // The ordinary liveness rules will ensure that all
989 // regions in the type of the callee are live here. We
990 // then further constrain the late-bound regions that
991 // were instantiated at the call site to be live as
992 // well. The resulting is that all the input (and
993 // output) types in the signature must be live, since
994 // all the inputs that fed into it were live.
995 for &late_bound_region in map.values() {
998 .push((late_bound_region, term_location));
1001 self.check_call_inputs(mir, term, &sig, args, term_location);
1003 TerminatorKind::Assert {
1004 ref cond, ref msg, ..
1006 let cond_ty = cond.ty(mir, tcx);
1007 if cond_ty != tcx.types.bool {
1008 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1011 if let BoundsCheck { ref len, ref index } = *msg {
1012 if len.ty(mir, tcx) != tcx.types.usize {
1013 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1015 if index.ty(mir, tcx) != tcx.types.usize {
1016 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1020 TerminatorKind::Yield { ref value, .. } => {
1021 let value_ty = value.ty(mir, tcx);
1022 match mir.yield_ty {
1023 None => span_mirbug!(self, term, "yield in non-generator"),
1025 if let Err(terr) = self.sub_types(value_ty, ty, term_location.interesting())
1030 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1045 term: &Terminator<'tcx>,
1046 sig: &ty::FnSig<'tcx>,
1047 destination: &Option<(Place<'tcx>, BasicBlock)>,
1048 term_location: Location,
1050 let tcx = self.tcx();
1051 match *destination {
1052 Some((ref dest, _target_block)) => {
1053 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1054 let locations = term_location.interesting();
1055 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations) {
1059 "call dest mismatch ({:?} <- {:?}): {:?}",
1067 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1068 if !sig.output().is_never() {
1069 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1075 fn check_call_inputs(
1078 term: &Terminator<'tcx>,
1079 sig: &ty::FnSig<'tcx>,
1080 args: &[Operand<'tcx>],
1081 term_location: Location,
1083 debug!("check_call_inputs({:?}, {:?})", sig, args);
1084 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1085 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1087 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1088 let op_arg_ty = op_arg.ty(mir, self.tcx());
1089 if let Err(terr) = self.sub_types(op_arg_ty, fn_arg, term_location.interesting()) {
1093 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1103 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1104 let is_cleanup = block_data.is_cleanup;
1105 self.last_span = block_data.terminator().source_info.span;
1106 match block_data.terminator().kind {
1107 TerminatorKind::Goto { target } => {
1108 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1110 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1111 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1113 TerminatorKind::Resume => if !is_cleanup {
1114 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1116 TerminatorKind::Abort => if !is_cleanup {
1117 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1119 TerminatorKind::Return => if is_cleanup {
1120 span_mirbug!(self, block_data, "return on cleanup block")
1122 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1123 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1125 TerminatorKind::Yield { resume, drop, .. } => {
1127 span_mirbug!(self, block_data, "yield in cleanup block")
1129 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1130 if let Some(drop) = drop {
1131 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1134 TerminatorKind::Unreachable => {}
1135 TerminatorKind::Drop { target, unwind, .. }
1136 | TerminatorKind::DropAndReplace { target, unwind, .. }
1137 | TerminatorKind::Assert {
1142 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1143 if let Some(unwind) = unwind {
1145 span_mirbug!(self, block_data, "unwind on cleanup block")
1147 self.assert_iscleanup(mir, block_data, unwind, true);
1150 TerminatorKind::Call {
1155 if let &Some((_, target)) = destination {
1156 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1158 if let Some(cleanup) = cleanup {
1160 span_mirbug!(self, block_data, "cleanup on cleanup block")
1162 self.assert_iscleanup(mir, block_data, cleanup, true);
1165 TerminatorKind::FalseEdges {
1167 ref imaginary_targets,
1169 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1170 for target in imaginary_targets {
1171 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1174 TerminatorKind::FalseUnwind {
1178 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1179 if let Some(unwind) = unwind {
1184 "cleanup in cleanup block via false unwind"
1187 self.assert_iscleanup(mir, block_data, unwind, true);
1193 fn assert_iscleanup(
1196 ctxt: &dyn fmt::Debug,
1200 if mir[bb].is_cleanup != iscleanuppad {
1204 "cleanuppad mismatch: {:?} should be {:?}",
1211 fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1212 match mir.local_kind(local) {
1213 LocalKind::ReturnPointer | LocalKind::Arg => {
1214 // return values of normal functions are required to be
1215 // sized by typeck, but return values of ADT constructors are
1216 // not because we don't include a `Self: Sized` bounds on them.
1218 // Unbound parts of arguments were never required to be Sized
1219 // - maybe we should make that a warning.
1222 LocalKind::Var | LocalKind::Temp => {}
1225 let span = local_decl.source_info.span;
1226 let ty = local_decl.ty;
1228 // Erase the regions from `ty` to get a global type. The
1229 // `Sized` bound in no way depends on precise regions, so this
1230 // shouldn't affect `is_sized`.
1231 let gcx = self.tcx().global_tcx();
1232 let erased_ty = gcx.lift(&self.tcx().erase_regions(&ty)).unwrap();
1233 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1234 // in current MIR construction, all non-control-flow rvalue
1235 // expressions evaluate through `as_temp` or `into` a return
1236 // slot or local, so to find all unsized rvalues it is enough
1237 // to check all temps, return slots and locals.
1238 if let None = self.reported_errors.replace((ty, span)) {
1243 "cannot move a value of type {0}: the size of {0} \
1244 cannot be statically determined",
1251 fn aggregate_field_ty(
1253 ak: &AggregateKind<'tcx>,
1256 ) -> Result<Ty<'tcx>, FieldAccessError> {
1257 let tcx = self.tcx();
1260 AggregateKind::Adt(def, variant_index, substs, active_field_index) => {
1261 let variant = &def.variants[variant_index];
1262 let adj_field_index = active_field_index.unwrap_or(field_index);
1263 if let Some(field) = variant.fields.get(adj_field_index) {
1264 Ok(self.normalize(field.ty(tcx, substs), location))
1266 Err(FieldAccessError::OutOfRange {
1267 field_count: variant.fields.len(),
1271 AggregateKind::Closure(def_id, substs) => {
1272 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1274 None => Err(FieldAccessError::OutOfRange {
1275 field_count: substs.upvar_tys(def_id, tcx).count(),
1279 AggregateKind::Generator(def_id, substs, _) => {
1280 // Try pre-transform fields first (upvars and current state)
1281 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1284 // Then try `field_tys` which contains all the fields, but it
1285 // requires the final optimized MIR.
1286 match substs.field_tys(def_id, tcx).nth(field_index) {
1288 None => Err(FieldAccessError::OutOfRange {
1289 field_count: substs.field_tys(def_id, tcx).count(),
1294 AggregateKind::Array(ty) => Ok(ty),
1295 AggregateKind::Tuple => {
1296 unreachable!("This should have been covered in check_rvalues");
1301 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1302 let tcx = self.tcx();
1305 Rvalue::Aggregate(ak, ops) => {
1306 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1309 Rvalue::Repeat(operand, len) => if *len > 1 {
1310 let operand_ty = operand.ty(mir, tcx);
1312 let trait_ref = ty::TraitRef {
1313 def_id: tcx.lang_items().copy_trait().unwrap(),
1314 substs: tcx.mk_substs_trait(operand_ty, &[]),
1317 self.prove_trait_ref(trait_ref, location.interesting());
1320 Rvalue::NullaryOp(_, ty) => {
1321 let trait_ref = ty::TraitRef {
1322 def_id: tcx.lang_items().sized_trait().unwrap(),
1323 substs: tcx.mk_substs_trait(ty, &[]),
1326 self.prove_trait_ref(trait_ref, location.interesting());
1329 Rvalue::Cast(cast_kind, op, ty) => match cast_kind {
1330 CastKind::ReifyFnPointer => {
1331 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1333 // The type that we see in the fcx is like
1334 // `foo::<'a, 'b>`, where `foo` is the path to a
1335 // function definition. When we extract the
1336 // signature, it comes from the `fn_sig` query,
1337 // and hence may contain unnormalized results.
1338 let fn_sig = self.normalize(fn_sig, location);
1340 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1342 if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1346 "equating {:?} with {:?} yields {:?}",
1354 CastKind::ClosureFnPointer => {
1355 let sig = match op.ty(mir, tcx).sty {
1356 ty::TyClosure(def_id, substs) => {
1357 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1361 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1363 if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1367 "equating {:?} with {:?} yields {:?}",
1375 CastKind::UnsafeFnPointer => {
1376 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1378 // The type that we see in the fcx is like
1379 // `foo::<'a, 'b>`, where `foo` is the path to a
1380 // function definition. When we extract the
1381 // signature, it comes from the `fn_sig` query,
1382 // and hence may contain unnormalized results.
1383 let fn_sig = self.normalize(fn_sig, location);
1385 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1387 if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1391 "equating {:?} with {:?} yields {:?}",
1399 CastKind::Unsize => {
1401 let trait_ref = ty::TraitRef {
1402 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1403 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1406 self.prove_trait_ref(trait_ref, location.interesting());
1409 CastKind::Misc => {}
1412 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1413 self.add_reborrow_constraint(location, region, borrowed_place);
1416 // FIXME: These other cases have to be implemented in future PRs
1419 | Rvalue::BinaryOp(..)
1420 | Rvalue::CheckedBinaryOp(..)
1421 | Rvalue::UnaryOp(..)
1422 | Rvalue::Discriminant(..) => {}
1426 fn check_aggregate_rvalue(
1429 rvalue: &Rvalue<'tcx>,
1430 aggregate_kind: &AggregateKind<'tcx>,
1431 operands: &[Operand<'tcx>],
1434 let tcx = self.tcx();
1436 self.prove_aggregate_predicates(aggregate_kind, location);
1438 if *aggregate_kind == AggregateKind::Tuple {
1439 // tuple rvalue field type is always the type of the op. Nothing to check here.
1443 for (i, operand) in operands.iter().enumerate() {
1444 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
1445 Ok(field_ty) => field_ty,
1446 Err(FieldAccessError::OutOfRange { field_count }) => {
1450 "accessed field #{} but variant only has {}",
1457 let operand_ty = operand.ty(mir, tcx);
1459 if let Err(terr) = self.sub_types(operand_ty, field_ty, location.boring()) {
1463 "{:?} is not a subtype of {:?}: {:?}",
1472 /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
1476 /// - `location`: the location `L` where the borrow expression occurs
1477 /// - `borrow_region`: the region `'a` associated with the borrow
1478 /// - `borrowed_place`: the place `P` being borrowed
1479 fn add_reborrow_constraint(
1482 borrow_region: ty::Region<'tcx>,
1483 borrowed_place: &Place<'tcx>,
1485 // These constraints are only meaningful during borrowck:
1486 let BorrowCheckContext {
1491 } = match &mut self.borrowck_context {
1492 Some(borrowck_context) => borrowck_context,
1496 // In Polonius mode, we also push a `borrow_region` fact
1497 // linking the loan to the region (in some cases, though,
1498 // there is no loan associated with this borrow expression --
1499 // that occurs when we are borrowing an unsafe place, for
1501 if let Some(all_facts) = all_facts {
1502 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
1503 let region_vid = borrow_region.to_region_vid();
1504 all_facts.borrow_region.push((
1507 location_table.mid_index(location),
1512 // If we are reborrowing the referent of another reference, we
1513 // need to add outlives relationships. In a case like `&mut
1514 // *p`, where the `p` has type `&'b mut Foo`, for example, we
1515 // need to ensure that `'b: 'a`.
1517 let mut borrowed_place = borrowed_place;
1520 "add_reborrow_constraint({:?}, {:?}, {:?})",
1521 location, borrow_region, borrowed_place
1523 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
1524 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
1527 ProjectionElem::Deref => {
1528 let tcx = self.infcx.tcx;
1529 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1531 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
1533 ty::TyRef(ref_region, _, mutbl) => {
1535 .outlives_constraints
1536 .push(OutlivesConstraint {
1537 sup: ref_region.to_region_vid(),
1538 sub: borrow_region.to_region_vid(),
1539 locations: location.boring(),
1542 if let Some(all_facts) = all_facts {
1543 all_facts.outlives.push((
1544 ref_region.to_region_vid(),
1545 borrow_region.to_region_vid(),
1546 location_table.mid_index(location),
1551 hir::Mutability::MutImmutable => {
1552 // Immutable reference. We don't need the base
1553 // to be valid for the entire lifetime of
1557 hir::Mutability::MutMutable => {
1558 // Mutable reference. We *do* need the base
1559 // to be valid, because after the base becomes
1560 // invalid, someone else can use our mutable deref.
1562 // This is in order to make the following function
1565 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
1570 // As otherwise you could clone `&mut T` using the
1571 // following function:
1573 // fn bad(x: &mut T) -> (&mut T, &mut T) {
1574 // let my_clone = unsafe_deref(&'a x);
1582 ty::TyRawPtr(..) => {
1583 // deref of raw pointer, guaranteed to be valid
1586 ty::TyAdt(def, _) if def.is_box() => {
1587 // deref of `Box`, need the base to be valid - propagate
1589 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
1592 ProjectionElem::Field(..)
1593 | ProjectionElem::Downcast(..)
1594 | ProjectionElem::Index(..)
1595 | ProjectionElem::ConstantIndex { .. }
1596 | ProjectionElem::Subslice { .. } => {
1597 // other field access
1601 // The "propagate" case. We need to check that our base is valid
1602 // for the borrow's lifetime.
1603 borrowed_place = base;
1607 fn prove_aggregate_predicates(
1609 aggregate_kind: &AggregateKind<'tcx>,
1612 let tcx = self.tcx();
1615 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
1616 aggregate_kind, location
1619 let instantiated_predicates = match aggregate_kind {
1620 AggregateKind::Adt(def, _, substs, _) => {
1621 tcx.predicates_of(def.did).instantiate(tcx, substs)
1624 // For closures, we have some **extra requirements** we
1626 // have to check. In particular, in their upvars and
1627 // signatures, closures often reference various regions
1628 // from the surrounding function -- we call those the
1629 // closure's free regions. When we borrow-check (and hence
1630 // region-check) closures, we may find that the closure
1631 // requires certain relationships between those free
1632 // regions. However, because those free regions refer to
1633 // portions of the CFG of their caller, the closure is not
1634 // in a position to verify those relationships. In that
1635 // case, the requirements get "propagated" to us, and so
1636 // we have to solve them here where we instantiate the
1639 // Despite the opacity of the previous parapgrah, this is
1640 // actually relatively easy to understand in terms of the
1641 // desugaring. A closure gets desugared to a struct, and
1642 // these extra requirements are basically like where
1643 // clauses on the struct.
1644 AggregateKind::Closure(def_id, substs) => {
1645 if let Some(closure_region_requirements) =
1646 tcx.mir_borrowck(*def_id).closure_requirements
1648 let closure_constraints = closure_region_requirements.apply_requirements(
1655 // Hmm, are these constraints *really* boring?
1656 self.push_region_constraints(location.boring(), &closure_constraints);
1659 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1662 AggregateKind::Generator(def_id, substs, _) => {
1663 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1666 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
1669 self.normalize_and_prove_instantiated_predicates(
1670 instantiated_predicates,
1675 fn prove_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>, locations: Locations) {
1676 self.prove_predicates(
1677 Some(ty::Predicate::Trait(
1678 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
1684 fn normalize_and_prove_instantiated_predicates(
1686 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
1687 locations: Locations,
1689 for predicate in instantiated_predicates.predicates {
1690 let predicate = self.normalize(predicate, locations);
1691 self.prove_predicate(predicate, locations);
1695 fn prove_predicates(
1697 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
1698 locations: Locations,
1700 for predicate in predicates {
1702 "prove_predicates(predicate={:?}, locations={:?})",
1703 predicate, locations,
1706 self.prove_predicate(predicate, locations);
1710 fn prove_predicate(&mut self, predicate: ty::Predicate<'tcx>, locations: Locations) {
1712 "prove_predicate(predicate={:?}, location={:?})",
1713 predicate, locations,
1716 let param_env = self.param_env;
1717 self.fully_perform_op(
1719 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
1720 ).unwrap_or_else(|NoSolution| {
1721 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
1725 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
1726 self.last_span = mir.span;
1727 debug!("run_on_mir: {:?}", mir.span);
1729 for (local, local_decl) in mir.local_decls.iter_enumerated() {
1730 self.check_local(mir, local, local_decl);
1733 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
1734 let mut location = Location {
1738 for stmt in &block_data.statements {
1739 if !stmt.source_info.span.is_dummy() {
1740 self.last_span = stmt.source_info.span;
1742 self.check_stmt(mir, stmt, location);
1743 location.statement_index += 1;
1746 self.check_terminator(mir, block_data.terminator(), location);
1747 self.check_iscleanup(mir, block_data);
1751 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
1753 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
1755 debug!("normalize(value={:?}, location={:?})", value, location);
1756 let param_env = self.param_env;
1757 self.fully_perform_op(
1758 location.to_locations(),
1759 param_env.and(type_op::normalize::Normalize::new(value)),
1760 ).unwrap_or_else(|NoSolution| {
1761 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
1767 pub struct TypeckMir;
1769 impl MirPass for TypeckMir {
1770 fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
1771 let def_id = src.def_id;
1772 debug!("run_pass: {:?}", def_id);
1774 // When NLL is enabled, the borrow checker runs the typeck
1775 // itself, so we don't need this MIR pass anymore.
1776 if tcx.use_mir_borrowck() {
1780 if tcx.sess.err_count() > 0 {
1781 // compiling a broken program can obviously result in a
1782 // broken MIR, so try not to report duplicate errors.
1786 if tcx.is_struct_constructor(def_id) {
1787 // We just assume that the automatically generated struct constructors are
1788 // correct. See the comment in the `mir_borrowck` implementation for an
1789 // explanation why we need this.
1793 let param_env = tcx.param_env(def_id);
1794 tcx.infer_ctxt().enter(|infcx| {
1796 type_check_internal(&infcx, def_id, param_env, mir, &[], None, None, &mut |_| ());
1798 // For verification purposes, we just ignore the resulting
1799 // region constraint sets. Not our problem. =)
1804 pub trait AtLocation {
1805 /// Indicates a "boring" constraint that the user probably
1806 /// woudln't want to see highlights.
1807 fn boring(self) -> Locations;
1809 /// Indicates an "interesting" edge, which is of significance only
1810 /// for diagnostics.
1811 fn interesting(self) -> Locations;
1814 impl AtLocation for Location {
1815 fn boring(self) -> Locations {
1816 Locations::Boring(self)
1819 fn interesting(self) -> Locations {
1820 Locations::Interesting(self)
1824 trait NormalizeLocation: fmt::Debug + Copy {
1825 fn to_locations(self) -> Locations;
1828 impl NormalizeLocation for Locations {
1829 fn to_locations(self) -> Locations {
1834 impl NormalizeLocation for Location {
1835 fn to_locations(self) -> Locations {