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::constraints::{ConstraintSet, OutlivesConstraint};
17 use borrow_check::nll::facts::AllFacts;
18 use borrow_check::nll::liveness_map::NllLivenessMap;
19 use borrow_check::nll::region_infer::values::{LivenessValues, RegionValueElements};
20 use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
21 use borrow_check::nll::type_check::free_region_relations::{
22 CreateResult, UniversalRegionRelations,
24 use borrow_check::nll::universal_regions::UniversalRegions;
25 use borrow_check::nll::LocalWithRegion;
26 use borrow_check::nll::ToRegionVid;
27 use dataflow::move_paths::MoveData;
28 use dataflow::FlowAtLocation;
29 use dataflow::MaybeInitializedPlaces;
31 use rustc::hir::def_id::DefId;
32 use rustc::infer::canonical::QueryRegionConstraint;
33 use rustc::infer::region_constraints::GenericKind;
34 use rustc::infer::{InferCtxt, LateBoundRegionConversionTime};
35 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
36 use rustc::mir::tcx::PlaceTy;
37 use rustc::mir::visit::{PlaceContext, Visitor};
39 use rustc::traits::query::type_op;
40 use rustc::traits::query::{Fallible, NoSolution};
41 use rustc::ty::fold::TypeFoldable;
42 use rustc::ty::{self, CanonicalTy, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TypeVariants};
43 use rustc_errors::Diagnostic;
46 use syntax_pos::{Span, DUMMY_SP};
47 use transform::{MirPass, MirSource};
48 use util::liveness::LivenessResults;
50 use rustc_data_structures::fx::FxHashSet;
51 use rustc_data_structures::indexed_vec::Idx;
53 macro_rules! span_mirbug {
54 ($context:expr, $elem:expr, $($message:tt)*) => ({
55 $crate::borrow_check::nll::type_check::mirbug(
59 "broken MIR in {:?} ({:?}): {}",
62 format_args!($($message)*),
68 macro_rules! span_mirbug_and_err {
69 ($context:expr, $elem:expr, $($message:tt)*) => ({
71 span_mirbug!($context, $elem, $($message)*);
77 mod constraint_conversion;
78 pub mod free_region_relations;
83 /// Type checks the given `mir` in the context of the inference
84 /// context `infcx`. Returns any region constraints that have yet to
85 /// be proven. This result is includes liveness constraints that
86 /// ensure that regions appearing in the types of all local variables
87 /// are live at all points where that local variable may later be
90 /// This phase of type-check ought to be infallible -- this is because
91 /// the original, HIR-based type-check succeeded. So if any errors
92 /// occur here, we will get a `bug!` reported.
96 /// - `infcx` -- inference context to use
97 /// - `param_env` -- parameter environment to use for trait solving
98 /// - `mir` -- MIR to type-check
99 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
100 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
101 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
102 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
103 /// to outlive; should represent the fn body
104 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
105 /// the types of the input parameters found in the MIR itself will be equated with these
106 /// - `output_ty` -- fully liberaetd, but **not** normalized, expected return type;
107 /// the type for the RETURN_PLACE will be equated with this
108 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
109 /// constraints for the regions in the types of variables
110 /// - `flow_inits` -- results of a maybe-init dataflow analysis
111 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
112 /// - `errors_buffer` -- errors are sent here for future reporting
113 pub(crate) fn type_check<'gcx, 'tcx>(
114 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
115 param_env: ty::ParamEnv<'gcx>,
118 universal_regions: &Rc<UniversalRegions<'tcx>>,
119 location_table: &LocationTable,
120 borrow_set: &BorrowSet<'tcx>,
121 liveness: &LivenessResults<LocalWithRegion>,
122 liveness_map: &NllLivenessMap,
123 all_facts: &mut Option<AllFacts>,
124 flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
125 move_data: &MoveData<'tcx>,
126 elements: &Rc<RegionValueElements>,
127 errors_buffer: &mut Vec<Diagnostic>,
129 MirTypeckRegionConstraints<'tcx>,
130 Rc<UniversalRegionRelations<'tcx>>,
132 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
133 let mut constraints = MirTypeckRegionConstraints {
134 liveness_constraints: LivenessValues::new(elements),
135 outlives_constraints: ConstraintSet::default(),
136 type_tests: Vec::default(),
140 universal_region_relations,
142 normalized_inputs_and_output,
143 } = free_region_relations::create(
148 Some(implicit_region_bound),
155 let mut borrowck_context = BorrowCheckContext {
160 constraints: &mut constraints,
169 Some(implicit_region_bound),
170 Some(&mut borrowck_context),
173 liveness::generate(cx, mir, liveness, liveness_map, flow_inits, move_data);
174 cx.equate_inputs_and_outputs(
178 &universal_region_relations,
179 &normalized_inputs_and_output,
185 (constraints, universal_region_relations)
188 fn type_check_internal<'a, 'gcx, 'tcx, F>(
189 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
191 param_env: ty::ParamEnv<'gcx>,
193 region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
194 implicit_region_bound: Option<ty::Region<'tcx>>,
195 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
196 errors_buffer: Option<&mut Vec<Diagnostic>>,
199 F: FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>),
201 let mut checker = TypeChecker::new(
207 implicit_region_bound,
210 let errors_reported = {
211 let mut verifier = TypeVerifier::new(&mut checker, mir);
212 verifier.visit_mir(mir);
213 verifier.errors_reported
216 if !errors_reported {
217 // if verifier failed, don't do further checks to avoid ICEs
218 checker.typeck_mir(mir, errors_buffer);
224 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
225 // We sometimes see MIR failures (notably predicate failures) due to
226 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
227 // to avoid reporting bugs in those cases.
228 tcx.sess.diagnostic().delay_span_bug(span, msg);
231 enum FieldAccessError {
232 OutOfRange { field_count: usize },
235 /// Verifies that MIR types are sane to not crash further checks.
237 /// The sanitize_XYZ methods here take an MIR object and compute its
238 /// type, calling `span_mirbug` and returning an error type if there
240 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
241 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
245 errors_reported: bool,
248 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
249 fn visit_span(&mut self, span: &Span) {
250 if !span.is_dummy() {
251 self.last_span = *span;
255 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
256 self.sanitize_place(place, location, context);
259 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
260 self.super_constant(constant, location);
261 self.sanitize_constant(constant, location);
262 self.sanitize_type(constant, constant.ty);
265 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
266 self.super_rvalue(rvalue, location);
267 let rval_ty = rvalue.ty(self.mir, self.tcx());
268 self.sanitize_type(rvalue, rval_ty);
271 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
272 self.super_local_decl(local, local_decl);
273 self.sanitize_type(local_decl, local_decl.ty);
276 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
277 self.sanitize_type(&"return type", mir.return_ty());
278 for local_decl in &mir.local_decls {
279 self.sanitize_type(local_decl, local_decl.ty);
281 if self.errors_reported {
288 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
289 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
292 mir_def_id: cx.mir_def_id,
295 errors_reported: false,
299 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
303 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
304 if ty.has_escaping_regions() || ty.references_error() {
305 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
311 /// Checks that the constant's `ty` field matches up with what
312 /// would be expected from its literal.
313 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
315 "sanitize_constant(constant={:?}, location={:?})",
319 // FIXME(#46702) -- We need some way to get the predicates
320 // associated with the "pre-evaluated" form of the
321 // constant. For example, consider that the constant
322 // may have associated constant projections (`<Foo as
323 // Trait<'a, 'b>>::SOME_CONST`) that impose
324 // constraints on `'a` and `'b`. These constraints
325 // would be lost if we just look at the normalized
327 if let ty::TyFnDef(def_id, substs) = constant.literal.ty.sty {
328 let tcx = self.tcx();
329 let type_checker = &mut self.cx;
331 // FIXME -- For now, use the substitutions from
332 // `value.ty` rather than `value.val`. The
333 // renumberer will rewrite them to independent
334 // sets of regions; in principle, we ought to
335 // derive the type of the `value.val` from "first
336 // principles" and equate with value.ty, but as we
337 // are transitioning to the miri-based system, we
338 // don't have a handy function for that, so for
339 // now we just ignore `value.val` regions.
341 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
342 type_checker.normalize_and_prove_instantiated_predicates(
343 instantiated_predicates,
348 debug!("sanitize_constant: expected_ty={:?}", constant.literal.ty);
350 if let Err(terr) = self
352 .eq_types(constant.literal.ty, constant.ty, location.boring())
357 "constant {:?} should have type {:?} but has {:?} ({:?})",
366 /// Checks that the types internal to the `place` match up with
367 /// what would be expected.
372 context: PlaceContext,
374 debug!("sanitize_place: {:?}", place);
375 let place_ty = match *place {
376 Place::Local(index) => PlaceTy::Ty {
377 ty: self.mir.local_decls[index].ty,
379 Place::Promoted(box (_index, sty)) => {
380 let sty = self.sanitize_type(place, sty);
381 // FIXME -- promoted MIR return types reference
382 // various "free regions" (e.g., scopes and things)
383 // that they ought not to do. We have to figure out
384 // how best to handle that -- probably we want treat
385 // promoted MIR much like closures, renumbering all
386 // their free regions and propagating constraints
387 // upwards. We have the same acyclic guarantees, so
388 // that should be possible. But for now, ignore them.
390 // let promoted_mir = &self.mir.promoted[index];
391 // promoted_mir.return_ty()
392 PlaceTy::Ty { ty: sty }
394 Place::Static(box Static { def_id, ty: sty }) => {
395 let sty = self.sanitize_type(place, sty);
396 let ty = self.tcx().type_of(def_id);
397 let ty = self.cx.normalize(ty, location);
398 if let Err(terr) = self.cx.eq_types(ty, sty, location.boring()) {
402 "bad static type ({:?}: {:?}): {:?}",
408 PlaceTy::Ty { ty: sty }
410 Place::Projection(ref proj) => {
411 let base_context = if context.is_mutating_use() {
412 PlaceContext::Projection(Mutability::Mut)
414 PlaceContext::Projection(Mutability::Not)
416 let base_ty = self.sanitize_place(&proj.base, location, base_context);
417 if let PlaceTy::Ty { ty } = base_ty {
418 if ty.references_error() {
419 assert!(self.errors_reported);
421 ty: self.tcx().types.err,
425 self.sanitize_projection(base_ty, &proj.elem, place, location)
428 if let PlaceContext::Copy = context {
429 let tcx = self.tcx();
430 let trait_ref = ty::TraitRef {
431 def_id: tcx.lang_items().copy_trait().unwrap(),
432 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
435 // In order to have a Copy operand, the type T of the value must be Copy. Note that we
436 // prove that T: Copy, rather than using the type_moves_by_default test. This is
437 // important because type_moves_by_default ignores the resulting region obligations and
438 // assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
439 // (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
440 // fully apply: in effect, the rule is that if a value of some type could implement
441 // Copy, then it must.
442 self.cx.prove_trait_ref(trait_ref, location.interesting());
447 fn sanitize_projection(
450 pi: &PlaceElem<'tcx>,
454 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
455 let tcx = self.tcx();
456 let base_ty = base.to_ty(tcx);
458 ProjectionElem::Deref => {
459 let deref_ty = base_ty.builtin_deref(true);
461 ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
462 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
466 ProjectionElem::Index(i) => {
467 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
468 if index_ty != tcx.types.usize {
470 ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
474 ty: base_ty.builtin_index().unwrap_or_else(|| {
475 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
480 ProjectionElem::ConstantIndex { .. } => {
481 // consider verifying in-bounds
483 ty: base_ty.builtin_index().unwrap_or_else(|| {
484 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
488 ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
489 ty: match base_ty.sty {
490 ty::TyArray(inner, size) => {
491 let size = size.unwrap_usize(tcx);
492 let min_size = (from as u64) + (to as u64);
493 if let Some(rest_size) = size.checked_sub(min_size) {
494 tcx.mk_array(inner, rest_size)
496 span_mirbug_and_err!(
499 "taking too-small slice of {:?}",
504 ty::TySlice(..) => base_ty,
505 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
508 ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
509 ty::TyAdt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
510 if index >= adt_def.variants.len() {
512 ty: span_mirbug_and_err!(
515 "cast to variant #{:?} but enum only has {:?}",
517 adt_def.variants.len()
524 variant_index: index,
529 ty: span_mirbug_and_err!(
532 "can't downcast {:?} as {:?}",
538 ProjectionElem::Field(field, fty) => {
539 let fty = self.sanitize_type(place, fty);
540 match self.field_ty(place, base, field, location) {
541 Ok(ty) => if let Err(terr) = self.cx.eq_types(ty, fty, location.boring()) {
545 "bad field access ({:?}: {:?}): {:?}",
551 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
554 "accessed field #{} but variant only has {}",
559 PlaceTy::Ty { ty: fty }
564 fn error(&mut self) -> Ty<'tcx> {
565 self.errors_reported = true;
571 parent: &dyn fmt::Debug,
572 base_ty: PlaceTy<'tcx>,
575 ) -> Result<Ty<'tcx>, FieldAccessError> {
576 let tcx = self.tcx();
578 let (variant, substs) = match base_ty {
583 } => (&adt_def.variants[variant_index], substs),
584 PlaceTy::Ty { ty } => match ty.sty {
585 ty::TyAdt(adt_def, substs) if !adt_def.is_enum() => (&adt_def.variants[0], substs),
586 ty::TyClosure(def_id, substs) => {
587 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
589 None => Err(FieldAccessError::OutOfRange {
590 field_count: substs.upvar_tys(def_id, tcx).count(),
594 ty::TyGenerator(def_id, substs, _) => {
595 // Try pre-transform fields first (upvars and current state)
596 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
600 // Then try `field_tys` which contains all the fields, but it
601 // requires the final optimized MIR.
602 return match substs.field_tys(def_id, tcx).nth(field.index()) {
604 None => Err(FieldAccessError::OutOfRange {
605 field_count: substs.field_tys(def_id, tcx).count(),
609 ty::TyTuple(tys) => {
610 return match tys.get(field.index()) {
612 None => Err(FieldAccessError::OutOfRange {
613 field_count: tys.len(),
618 return Ok(span_mirbug_and_err!(
621 "can't project out of {:?}",
628 if let Some(field) = variant.fields.get(field.index()) {
629 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
631 Err(FieldAccessError::OutOfRange {
632 field_count: variant.fields.len(),
638 /// The MIR type checker. Visits the MIR and enforces all the
639 /// constraints needed for it to be valid and well-typed. Along the
640 /// way, it accrues region constraints -- these can later be used by
641 /// NLL region checking.
642 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
643 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
644 param_env: ty::ParamEnv<'gcx>,
648 region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
649 implicit_region_bound: Option<ty::Region<'tcx>>,
650 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
651 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
654 struct BorrowCheckContext<'a, 'tcx: 'a> {
655 universal_regions: &'a UniversalRegions<'tcx>,
656 location_table: &'a LocationTable,
657 all_facts: &'a mut Option<AllFacts>,
658 borrow_set: &'a BorrowSet<'tcx>,
659 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
662 /// A collection of region constraints that must be satisfied for the
663 /// program to be considered well-typed.
664 crate struct MirTypeckRegionConstraints<'tcx> {
665 /// In general, the type-checker is not responsible for enforcing
666 /// liveness constraints; this job falls to the region inferencer,
667 /// which performs a liveness analysis. However, in some limited
668 /// cases, the MIR type-checker creates temporary regions that do
669 /// not otherwise appear in the MIR -- in particular, the
670 /// late-bound regions that it instantiates at call-sites -- and
671 /// hence it must report on their liveness constraints.
672 crate liveness_constraints: LivenessValues<RegionVid>,
674 crate outlives_constraints: ConstraintSet,
676 crate type_tests: Vec<TypeTest<'tcx>>,
679 /// The `Locations` type summarizes *where* region constraints are
680 /// required to hold. Normally, this is at a particular point which
681 /// created the obligation, but for constraints that the user gave, we
682 /// want the constraint to hold at all points.
683 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
685 /// Indicates that a type constraint should always be true. This
686 /// is particularly important in the new borrowck analysis for
687 /// things like the type of the return slot. Consider this
691 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
693 /// return &y; // error
697 /// Here, we wind up with the signature from the return type being
698 /// something like `&'1 u32` where `'1` is a universal region. But
699 /// the type of the return slot `_0` is something like `&'2 u32`
700 /// where `'2` is an existential region variable. The type checker
701 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
702 /// older NLL analysis, we required this only at the entry point
703 /// to the function. By the nature of the constraints, this wound
704 /// up propagating to all points reachable from start (because
705 /// `'1` -- as a universal region -- is live everywhere). In the
706 /// newer analysis, though, this doesn't work: `_0` is considered
707 /// dead at the start (it has no usable value) and hence this type
708 /// equality is basically a no-op. Then, later on, when we do `_0
709 /// = &'3 y`, that region `'3` never winds up related to the
710 /// universal region `'1` and hence no error occurs. Therefore, we
711 /// use Locations::All instead, which ensures that the `'1` and
712 /// `'2` are equal everything. We also use this for other
713 /// user-given type annotations; e.g., if the user wrote `let mut
714 /// x: &'static u32 = ...`, we would ensure that all values
715 /// assigned to `x` are of `'static` lifetime.
718 /// A "boring" constraint (caused by the given location) is one that
719 /// the user probably doesn't want to see described in diagnostics,
720 /// because it is kind of an artifact of the type system setup.
722 /// Example: `x = Foo { field: y }` technically creates
723 /// intermediate regions representing the "type of `Foo { field: y
724 /// }`", and data flows from `y` into those variables, but they
725 /// are not very interesting. The assignment into `x` on the other
729 /// An *important* outlives constraint (caused by the given
730 /// location) is one that would be useful to highlight in
731 /// diagnostics, because it represents a point where references
732 /// flow from one spot to another (e.g., `x = y`)
733 Interesting(Location),
737 pub fn from_location(&self) -> Option<Location> {
739 Locations::All => None,
740 Locations::Boring(from_location) | Locations::Interesting(from_location) => {
746 /// Gets a span representing the location.
747 pub fn span(&self, mir: &Mir<'_>) -> Span {
748 let span_location = match self {
749 Locations::All => Location::START,
750 Locations::Boring(l) | Locations::Interesting(l) => *l,
752 mir.source_info(span_location).span
756 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
758 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
761 param_env: ty::ParamEnv<'gcx>,
762 region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
763 implicit_region_bound: Option<ty::Region<'tcx>>,
764 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
773 implicit_region_bound,
775 reported_errors: FxHashSet(),
779 /// Given some operation `op` that manipulates types, proves
780 /// predicates, or otherwise uses the inference context, executes
781 /// `op` and then executes all the further obligations that `op`
782 /// returns. This will yield a set of outlives constraints amongst
783 /// regions which are extracted and stored as having occured at
786 /// **Any `rustc::infer` operations that might generate region
787 /// constraints should occur within this method so that those
788 /// constraints can be properly localized!**
789 fn fully_perform_op<R>(
791 locations: Locations,
792 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
794 let (r, opt_data) = op.fully_perform(self.infcx)?;
796 if let Some(data) = &opt_data {
797 self.push_region_constraints(locations, data);
803 fn push_region_constraints(
805 locations: Locations,
806 data: &[QueryRegionConstraint<'tcx>],
809 "push_region_constraints: constraints generated at {:?} are {:#?}",
813 if let Some(ref mut borrowck_context) = self.borrowck_context {
814 constraint_conversion::ConstraintConversion::new(
816 borrowck_context.universal_regions,
817 borrowck_context.location_table,
818 self.region_bound_pairs,
819 self.implicit_region_bound,
822 &mut borrowck_context.constraints.outlives_constraints,
823 &mut borrowck_context.constraints.type_tests,
824 &mut borrowck_context.all_facts,
825 ).convert_all(&data);
829 fn sub_types(&mut self, sub: Ty<'tcx>, sup: Ty<'tcx>, locations: Locations) -> Fallible<()> {
830 relate_tys::sub_types(
835 self.borrowck_context.as_mut().map(|x| &mut **x),
839 fn eq_types(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, locations: Locations) -> Fallible<()> {
840 relate_tys::eq_types(
845 self.borrowck_context.as_mut().map(|x| &mut **x),
849 fn eq_canonical_type_and_type(
851 a: CanonicalTy<'tcx>,
853 locations: Locations,
855 relate_tys::eq_canonical_type_and_type(
860 self.borrowck_context.as_mut().map(|x| &mut **x),
864 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
868 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
869 debug!("check_stmt: {:?}", stmt);
870 let tcx = self.tcx();
872 StatementKind::Assign(ref place, ref rv) => {
873 // Assignments to temporaries are not "interesting";
874 // they are not caused by the user, but rather artifacts
875 // of lowering. Assignments to other sorts of places *are* interesting
877 let is_temp = if let Place::Local(l) = place {
878 !mir.local_decls[*l].is_user_variable.is_some()
883 let locations = if is_temp {
886 location.interesting()
889 let place_ty = place.ty(mir, tcx).to_ty(tcx);
890 let rv_ty = rv.ty(mir, tcx);
891 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
895 "bad assignment ({:?} = {:?}): {:?}",
901 self.check_rvalue(mir, rv, location);
902 let trait_ref = ty::TraitRef {
903 def_id: tcx.lang_items().sized_trait().unwrap(),
904 substs: tcx.mk_substs_trait(place_ty, &[]),
906 self.prove_trait_ref(trait_ref, location.interesting());
908 StatementKind::SetDiscriminant {
912 let place_type = place.ty(mir, tcx).to_ty(tcx);
913 let adt = match place_type.sty {
914 TypeVariants::TyAdt(adt, _) if adt.is_enum() => adt,
917 stmt.source_info.span,
918 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
924 if variant_index >= adt.variants.len() {
926 stmt.source_info.span,
927 "bad set discriminant ({:?} = {:?}): value of of range",
933 StatementKind::UserAssertTy(c_ty, local) => {
934 let local_ty = mir.local_decls()[local].ty;
935 if let Err(terr) = self.eq_canonical_type_and_type(c_ty, local_ty, Locations::All) {
939 "bad type assert ({:?} = {:?}): {:?}",
946 StatementKind::ReadForMatch(_)
947 | StatementKind::StorageLive(_)
948 | StatementKind::StorageDead(_)
949 | StatementKind::InlineAsm { .. }
950 | StatementKind::EndRegion(_)
951 | StatementKind::Validate(..)
952 | StatementKind::Nop => {}
959 term: &Terminator<'tcx>,
960 term_location: Location,
962 debug!("check_terminator: {:?}", term);
963 let tcx = self.tcx();
965 TerminatorKind::Goto { .. }
966 | TerminatorKind::Resume
967 | TerminatorKind::Abort
968 | TerminatorKind::Return
969 | TerminatorKind::GeneratorDrop
970 | TerminatorKind::Unreachable
971 | TerminatorKind::Drop { .. }
972 | TerminatorKind::FalseEdges { .. }
973 | TerminatorKind::FalseUnwind { .. } => {
974 // no checks needed for these
977 TerminatorKind::DropAndReplace {
983 let place_ty = location.ty(mir, tcx).to_ty(tcx);
984 let rv_ty = value.ty(mir, tcx);
986 let locations = term_location.interesting();
987 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
991 "bad DropAndReplace ({:?} = {:?}): {:?}",
998 TerminatorKind::SwitchInt {
1003 let discr_ty = discr.ty(mir, tcx);
1004 if let Err(terr) = self.sub_types(discr_ty, switch_ty, term_location.boring()) {
1008 "bad SwitchInt ({:?} on {:?}): {:?}",
1014 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1015 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1017 // FIXME: check the values
1019 TerminatorKind::Call {
1025 let func_ty = func.ty(mir, tcx);
1026 debug!("check_terminator: call, func_ty={:?}", func_ty);
1027 let sig = match func_ty.sty {
1028 ty::TyFnDef(..) | ty::TyFnPtr(_) => func_ty.fn_sig(tcx),
1030 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1034 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
1035 term.source_info.span,
1036 LateBoundRegionConversionTime::FnCall,
1039 let sig = self.normalize(sig, term_location);
1040 self.check_call_dest(mir, term, &sig, destination, term_location);
1042 self.prove_predicates(
1043 sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1044 term_location.boring(),
1047 // The ordinary liveness rules will ensure that all
1048 // regions in the type of the callee are live here. We
1049 // then further constrain the late-bound regions that
1050 // were instantiated at the call site to be live as
1051 // well. The resulting is that all the input (and
1052 // output) types in the signature must be live, since
1053 // all the inputs that fed into it were live.
1054 for &late_bound_region in map.values() {
1055 if let Some(ref mut borrowck_context) = self.borrowck_context {
1056 let region_vid = borrowck_context
1058 .to_region_vid(late_bound_region);
1061 .liveness_constraints
1062 .add_element(region_vid, term_location);
1066 self.check_call_inputs(mir, term, &sig, args, term_location);
1068 TerminatorKind::Assert {
1069 ref cond, ref msg, ..
1071 let cond_ty = cond.ty(mir, tcx);
1072 if cond_ty != tcx.types.bool {
1073 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1076 if let BoundsCheck { ref len, ref index } = *msg {
1077 if len.ty(mir, tcx) != tcx.types.usize {
1078 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1080 if index.ty(mir, tcx) != tcx.types.usize {
1081 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1085 TerminatorKind::Yield { ref value, .. } => {
1086 let value_ty = value.ty(mir, tcx);
1087 match mir.yield_ty {
1088 None => span_mirbug!(self, term, "yield in non-generator"),
1090 if let Err(terr) = self.sub_types(value_ty, ty, term_location.interesting())
1095 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1110 term: &Terminator<'tcx>,
1111 sig: &ty::FnSig<'tcx>,
1112 destination: &Option<(Place<'tcx>, BasicBlock)>,
1113 term_location: Location,
1115 let tcx = self.tcx();
1116 match *destination {
1117 Some((ref dest, _target_block)) => {
1118 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1119 let locations = term_location.interesting();
1120 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations) {
1124 "call dest mismatch ({:?} <- {:?}): {:?}",
1132 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1133 if !sig.output().is_never() {
1134 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1140 fn check_call_inputs(
1143 term: &Terminator<'tcx>,
1144 sig: &ty::FnSig<'tcx>,
1145 args: &[Operand<'tcx>],
1146 term_location: Location,
1148 debug!("check_call_inputs({:?}, {:?})", sig, args);
1149 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1150 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1152 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1153 let op_arg_ty = op_arg.ty(mir, self.tcx());
1154 if let Err(terr) = self.sub_types(op_arg_ty, fn_arg, term_location.interesting()) {
1158 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1168 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1169 let is_cleanup = block_data.is_cleanup;
1170 self.last_span = block_data.terminator().source_info.span;
1171 match block_data.terminator().kind {
1172 TerminatorKind::Goto { target } => {
1173 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1175 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1176 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1178 TerminatorKind::Resume => if !is_cleanup {
1179 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1181 TerminatorKind::Abort => if !is_cleanup {
1182 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1184 TerminatorKind::Return => if is_cleanup {
1185 span_mirbug!(self, block_data, "return on cleanup block")
1187 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1188 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1190 TerminatorKind::Yield { resume, drop, .. } => {
1192 span_mirbug!(self, block_data, "yield in cleanup block")
1194 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1195 if let Some(drop) = drop {
1196 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1199 TerminatorKind::Unreachable => {}
1200 TerminatorKind::Drop { target, unwind, .. }
1201 | TerminatorKind::DropAndReplace { target, unwind, .. }
1202 | TerminatorKind::Assert {
1207 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1208 if let Some(unwind) = unwind {
1210 span_mirbug!(self, block_data, "unwind on cleanup block")
1212 self.assert_iscleanup(mir, block_data, unwind, true);
1215 TerminatorKind::Call {
1220 if let &Some((_, target)) = destination {
1221 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1223 if let Some(cleanup) = cleanup {
1225 span_mirbug!(self, block_data, "cleanup on cleanup block")
1227 self.assert_iscleanup(mir, block_data, cleanup, true);
1230 TerminatorKind::FalseEdges {
1232 ref imaginary_targets,
1234 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1235 for target in imaginary_targets {
1236 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1239 TerminatorKind::FalseUnwind {
1243 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1244 if let Some(unwind) = unwind {
1249 "cleanup in cleanup block via false unwind"
1252 self.assert_iscleanup(mir, block_data, unwind, true);
1258 fn assert_iscleanup(
1261 ctxt: &dyn fmt::Debug,
1265 if mir[bb].is_cleanup != iscleanuppad {
1269 "cleanuppad mismatch: {:?} should be {:?}",
1280 local_decl: &LocalDecl<'tcx>,
1281 errors_buffer: &mut Option<&mut Vec<Diagnostic>>,
1283 match mir.local_kind(local) {
1284 LocalKind::ReturnPointer | LocalKind::Arg => {
1285 // return values of normal functions are required to be
1286 // sized by typeck, but return values of ADT constructors are
1287 // not because we don't include a `Self: Sized` bounds on them.
1289 // Unbound parts of arguments were never required to be Sized
1290 // - maybe we should make that a warning.
1293 LocalKind::Var | LocalKind::Temp => {}
1296 let span = local_decl.source_info.span;
1297 let ty = local_decl.ty;
1299 // Erase the regions from `ty` to get a global type. The
1300 // `Sized` bound in no way depends on precise regions, so this
1301 // shouldn't affect `is_sized`.
1302 let gcx = self.tcx().global_tcx();
1303 let erased_ty = gcx.lift(&self.tcx().erase_regions(&ty)).unwrap();
1304 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1305 // in current MIR construction, all non-control-flow rvalue
1306 // expressions evaluate through `as_temp` or `into` a return
1307 // slot or local, so to find all unsized rvalues it is enough
1308 // to check all temps, return slots and locals.
1309 if let None = self.reported_errors.replace((ty, span)) {
1310 let mut diag = struct_span_err!(
1314 "cannot move a value of type {0}: the size of {0} \
1315 cannot be statically determined",
1318 if let Some(ref mut errors_buffer) = *errors_buffer {
1319 diag.buffer(errors_buffer);
1321 // we're allowed to use emit() here because the
1322 // NLL migration will be turned on (and thus
1323 // errors will need to be buffered) *only if*
1324 // errors_buffer is Some.
1331 fn aggregate_field_ty(
1333 ak: &AggregateKind<'tcx>,
1336 ) -> Result<Ty<'tcx>, FieldAccessError> {
1337 let tcx = self.tcx();
1340 AggregateKind::Adt(def, variant_index, substs, active_field_index) => {
1341 let variant = &def.variants[variant_index];
1342 let adj_field_index = active_field_index.unwrap_or(field_index);
1343 if let Some(field) = variant.fields.get(adj_field_index) {
1344 Ok(self.normalize(field.ty(tcx, substs), location))
1346 Err(FieldAccessError::OutOfRange {
1347 field_count: variant.fields.len(),
1351 AggregateKind::Closure(def_id, substs) => {
1352 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1354 None => Err(FieldAccessError::OutOfRange {
1355 field_count: substs.upvar_tys(def_id, tcx).count(),
1359 AggregateKind::Generator(def_id, substs, _) => {
1360 // Try pre-transform fields first (upvars and current state)
1361 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1364 // Then try `field_tys` which contains all the fields, but it
1365 // requires the final optimized MIR.
1366 match substs.field_tys(def_id, tcx).nth(field_index) {
1368 None => Err(FieldAccessError::OutOfRange {
1369 field_count: substs.field_tys(def_id, tcx).count(),
1374 AggregateKind::Array(ty) => Ok(ty),
1375 AggregateKind::Tuple => {
1376 unreachable!("This should have been covered in check_rvalues");
1381 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1382 let tcx = self.tcx();
1385 Rvalue::Aggregate(ak, ops) => {
1386 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1389 Rvalue::Repeat(operand, len) => if *len > 1 {
1390 let operand_ty = operand.ty(mir, tcx);
1392 let trait_ref = ty::TraitRef {
1393 def_id: tcx.lang_items().copy_trait().unwrap(),
1394 substs: tcx.mk_substs_trait(operand_ty, &[]),
1397 self.prove_trait_ref(trait_ref, location.interesting());
1400 Rvalue::NullaryOp(_, ty) => {
1401 let trait_ref = ty::TraitRef {
1402 def_id: tcx.lang_items().sized_trait().unwrap(),
1403 substs: tcx.mk_substs_trait(ty, &[]),
1406 self.prove_trait_ref(trait_ref, location.interesting());
1409 Rvalue::Cast(cast_kind, op, ty) => match cast_kind {
1410 CastKind::ReifyFnPointer => {
1411 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1413 // The type that we see in the fcx is like
1414 // `foo::<'a, 'b>`, where `foo` is the path to a
1415 // function definition. When we extract the
1416 // signature, it comes from the `fn_sig` query,
1417 // and hence may contain unnormalized results.
1418 let fn_sig = self.normalize(fn_sig, location);
1420 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1422 if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1426 "equating {:?} with {:?} yields {:?}",
1434 CastKind::ClosureFnPointer => {
1435 let sig = match op.ty(mir, tcx).sty {
1436 ty::TyClosure(def_id, substs) => {
1437 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1441 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1443 if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1447 "equating {:?} with {:?} yields {:?}",
1455 CastKind::UnsafeFnPointer => {
1456 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1458 // The type that we see in the fcx is like
1459 // `foo::<'a, 'b>`, where `foo` is the path to a
1460 // function definition. When we extract the
1461 // signature, it comes from the `fn_sig` query,
1462 // and hence may contain unnormalized results.
1463 let fn_sig = self.normalize(fn_sig, location);
1465 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1467 if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1471 "equating {:?} with {:?} yields {:?}",
1479 CastKind::Unsize => {
1481 let trait_ref = ty::TraitRef {
1482 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1483 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1486 self.prove_trait_ref(trait_ref, location.interesting());
1489 CastKind::Misc => {}
1492 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1493 self.add_reborrow_constraint(location, region, borrowed_place);
1496 // FIXME: These other cases have to be implemented in future PRs
1499 | Rvalue::BinaryOp(..)
1500 | Rvalue::CheckedBinaryOp(..)
1501 | Rvalue::UnaryOp(..)
1502 | Rvalue::Discriminant(..) => {}
1506 fn check_aggregate_rvalue(
1509 rvalue: &Rvalue<'tcx>,
1510 aggregate_kind: &AggregateKind<'tcx>,
1511 operands: &[Operand<'tcx>],
1514 let tcx = self.tcx();
1516 self.prove_aggregate_predicates(aggregate_kind, location);
1518 if *aggregate_kind == AggregateKind::Tuple {
1519 // tuple rvalue field type is always the type of the op. Nothing to check here.
1523 for (i, operand) in operands.iter().enumerate() {
1524 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
1525 Ok(field_ty) => field_ty,
1526 Err(FieldAccessError::OutOfRange { field_count }) => {
1530 "accessed field #{} but variant only has {}",
1537 let operand_ty = operand.ty(mir, tcx);
1539 if let Err(terr) = self.sub_types(operand_ty, field_ty, location.boring()) {
1543 "{:?} is not a subtype of {:?}: {:?}",
1552 /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
1556 /// - `location`: the location `L` where the borrow expression occurs
1557 /// - `borrow_region`: the region `'a` associated with the borrow
1558 /// - `borrowed_place`: the place `P` being borrowed
1559 fn add_reborrow_constraint(
1562 borrow_region: ty::Region<'tcx>,
1563 borrowed_place: &Place<'tcx>,
1565 // These constraints are only meaningful during borrowck:
1566 let BorrowCheckContext {
1572 } = match self.borrowck_context {
1573 Some(ref mut borrowck_context) => borrowck_context,
1577 // In Polonius mode, we also push a `borrow_region` fact
1578 // linking the loan to the region (in some cases, though,
1579 // there is no loan associated with this borrow expression --
1580 // that occurs when we are borrowing an unsafe place, for
1582 if let Some(all_facts) = all_facts {
1583 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
1584 let region_vid = borrow_region.to_region_vid();
1585 all_facts.borrow_region.push((
1588 location_table.mid_index(location),
1593 // If we are reborrowing the referent of another reference, we
1594 // need to add outlives relationships. In a case like `&mut
1595 // *p`, where the `p` has type `&'b mut Foo`, for example, we
1596 // need to ensure that `'b: 'a`.
1598 let mut borrowed_place = borrowed_place;
1601 "add_reborrow_constraint({:?}, {:?}, {:?})",
1602 location, borrow_region, borrowed_place
1604 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
1605 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
1608 ProjectionElem::Deref => {
1609 let tcx = self.infcx.tcx;
1610 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1612 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
1614 ty::TyRef(ref_region, _, mutbl) => {
1615 constraints.outlives_constraints.push(OutlivesConstraint {
1616 sup: ref_region.to_region_vid(),
1617 sub: borrow_region.to_region_vid(),
1618 locations: location.boring(),
1621 if let Some(all_facts) = all_facts {
1622 all_facts.outlives.push((
1623 ref_region.to_region_vid(),
1624 borrow_region.to_region_vid(),
1625 location_table.mid_index(location),
1630 hir::Mutability::MutImmutable => {
1631 // Immutable reference. We don't need the base
1632 // to be valid for the entire lifetime of
1636 hir::Mutability::MutMutable => {
1637 // Mutable reference. We *do* need the base
1638 // to be valid, because after the base becomes
1639 // invalid, someone else can use our mutable deref.
1641 // This is in order to make the following function
1644 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
1649 // As otherwise you could clone `&mut T` using the
1650 // following function:
1652 // fn bad(x: &mut T) -> (&mut T, &mut T) {
1653 // let my_clone = unsafe_deref(&'a x);
1661 ty::TyRawPtr(..) => {
1662 // deref of raw pointer, guaranteed to be valid
1665 ty::TyAdt(def, _) if def.is_box() => {
1666 // deref of `Box`, need the base to be valid - propagate
1668 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
1671 ProjectionElem::Field(..)
1672 | ProjectionElem::Downcast(..)
1673 | ProjectionElem::Index(..)
1674 | ProjectionElem::ConstantIndex { .. }
1675 | ProjectionElem::Subslice { .. } => {
1676 // other field access
1680 // The "propagate" case. We need to check that our base is valid
1681 // for the borrow's lifetime.
1682 borrowed_place = base;
1686 fn prove_aggregate_predicates(
1688 aggregate_kind: &AggregateKind<'tcx>,
1691 let tcx = self.tcx();
1694 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
1695 aggregate_kind, location
1698 let instantiated_predicates = match aggregate_kind {
1699 AggregateKind::Adt(def, _, substs, _) => {
1700 tcx.predicates_of(def.did).instantiate(tcx, substs)
1703 // For closures, we have some **extra requirements** we
1705 // have to check. In particular, in their upvars and
1706 // signatures, closures often reference various regions
1707 // from the surrounding function -- we call those the
1708 // closure's free regions. When we borrow-check (and hence
1709 // region-check) closures, we may find that the closure
1710 // requires certain relationships between those free
1711 // regions. However, because those free regions refer to
1712 // portions of the CFG of their caller, the closure is not
1713 // in a position to verify those relationships. In that
1714 // case, the requirements get "propagated" to us, and so
1715 // we have to solve them here where we instantiate the
1718 // Despite the opacity of the previous parapgrah, this is
1719 // actually relatively easy to understand in terms of the
1720 // desugaring. A closure gets desugared to a struct, and
1721 // these extra requirements are basically like where
1722 // clauses on the struct.
1723 AggregateKind::Closure(def_id, substs) => {
1724 if let Some(closure_region_requirements) =
1725 tcx.mir_borrowck(*def_id).closure_requirements
1727 let closure_constraints = closure_region_requirements.apply_requirements(
1734 // Hmm, are these constraints *really* boring?
1735 self.push_region_constraints(location.boring(), &closure_constraints);
1738 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1741 AggregateKind::Generator(def_id, substs, _) => {
1742 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1745 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
1748 self.normalize_and_prove_instantiated_predicates(
1749 instantiated_predicates,
1754 fn prove_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>, locations: Locations) {
1755 self.prove_predicates(
1756 Some(ty::Predicate::Trait(
1757 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
1763 fn normalize_and_prove_instantiated_predicates(
1765 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
1766 locations: Locations,
1768 for predicate in instantiated_predicates.predicates {
1769 let predicate = self.normalize(predicate, locations);
1770 self.prove_predicate(predicate, locations);
1774 fn prove_predicates(
1776 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
1777 locations: Locations,
1779 for predicate in predicates {
1781 "prove_predicates(predicate={:?}, locations={:?})",
1782 predicate, locations,
1785 self.prove_predicate(predicate, locations);
1789 fn prove_predicate(&mut self, predicate: ty::Predicate<'tcx>, locations: Locations) {
1791 "prove_predicate(predicate={:?}, location={:?})",
1792 predicate, locations,
1795 let param_env = self.param_env;
1796 self.fully_perform_op(
1798 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
1799 ).unwrap_or_else(|NoSolution| {
1800 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
1804 fn typeck_mir(&mut self, mir: &Mir<'tcx>, mut errors_buffer: Option<&mut Vec<Diagnostic>>) {
1805 self.last_span = mir.span;
1806 debug!("run_on_mir: {:?}", mir.span);
1808 for (local, local_decl) in mir.local_decls.iter_enumerated() {
1809 self.check_local(mir, local, local_decl, &mut errors_buffer);
1812 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
1813 let mut location = Location {
1817 for stmt in &block_data.statements {
1818 if !stmt.source_info.span.is_dummy() {
1819 self.last_span = stmt.source_info.span;
1821 self.check_stmt(mir, stmt, location);
1822 location.statement_index += 1;
1825 self.check_terminator(mir, block_data.terminator(), location);
1826 self.check_iscleanup(mir, block_data);
1830 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
1832 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
1834 debug!("normalize(value={:?}, location={:?})", value, location);
1835 let param_env = self.param_env;
1836 self.fully_perform_op(
1837 location.to_locations(),
1838 param_env.and(type_op::normalize::Normalize::new(value)),
1839 ).unwrap_or_else(|NoSolution| {
1840 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
1846 pub struct TypeckMir;
1848 impl MirPass for TypeckMir {
1849 fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
1850 let def_id = src.def_id;
1851 debug!("run_pass: {:?}", def_id);
1853 // When NLL is enabled, the borrow checker runs the typeck
1854 // itself, so we don't need this MIR pass anymore.
1855 if tcx.use_mir_borrowck() {
1859 if tcx.sess.err_count() > 0 {
1860 // compiling a broken program can obviously result in a
1861 // broken MIR, so try not to report duplicate errors.
1865 if tcx.is_struct_constructor(def_id) {
1866 // We just assume that the automatically generated struct constructors are
1867 // correct. See the comment in the `mir_borrowck` implementation for an
1868 // explanation why we need this.
1872 let param_env = tcx.param_env(def_id);
1873 tcx.infer_ctxt().enter(|infcx| {
1874 type_check_internal(
1886 // For verification purposes, we just ignore the resulting
1887 // region constraint sets. Not our problem. =)
1892 pub trait AtLocation {
1893 /// Indicates a "boring" constraint that the user probably
1894 /// woudln't want to see highlights.
1895 fn boring(self) -> Locations;
1897 /// Indicates an "interesting" edge, which is of significance only
1898 /// for diagnostics.
1899 fn interesting(self) -> Locations;
1902 impl AtLocation for Location {
1903 fn boring(self) -> Locations {
1904 Locations::Boring(self)
1907 fn interesting(self) -> Locations {
1908 Locations::Interesting(self)
1912 trait NormalizeLocation: fmt::Debug + Copy {
1913 fn to_locations(self) -> Locations;
1916 impl NormalizeLocation for Locations {
1917 fn to_locations(self) -> Locations {
1922 impl NormalizeLocation for Location {
1923 fn to_locations(self) -> Locations {