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::region_infer::values::{RegionValueElements, LivenessValues};
19 use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
20 use borrow_check::nll::type_check::free_region_relations::{CreateResult, UniversalRegionRelations};
21 use borrow_check::nll::type_check::liveness::liveness_map::NllLivenessMap;
22 use borrow_check::nll::universal_regions::UniversalRegions;
23 use borrow_check::nll::LocalWithRegion;
24 use borrow_check::nll::ToRegionVid;
25 use dataflow::move_paths::MoveData;
26 use dataflow::FlowAtLocation;
27 use dataflow::MaybeInitializedPlaces;
29 use rustc::hir::def_id::DefId;
30 use rustc::infer::canonical::QueryRegionConstraint;
31 use rustc::infer::region_constraints::GenericKind;
32 use rustc::infer::{InferCtxt, LateBoundRegionConversionTime};
33 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
34 use rustc::mir::tcx::PlaceTy;
35 use rustc::mir::visit::{PlaceContext, Visitor};
37 use rustc::traits::query::type_op;
38 use rustc::traits::query::{Fallible, NoSolution};
39 use rustc::ty::fold::TypeFoldable;
40 use rustc::ty::{self, CanonicalTy, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TyKind};
41 use rustc_errors::Diagnostic;
44 use syntax_pos::{Span, DUMMY_SP};
45 use transform::{MirPass, MirSource};
46 use util::liveness::LivenessResults;
48 use rustc_data_structures::fx::FxHashSet;
49 use rustc_data_structures::indexed_vec::Idx;
51 macro_rules! span_mirbug {
52 ($context:expr, $elem:expr, $($message:tt)*) => ({
53 $crate::borrow_check::nll::type_check::mirbug(
57 "broken MIR in {:?} ({:?}): {}",
60 format_args!($($message)*),
66 macro_rules! span_mirbug_and_err {
67 ($context:expr, $elem:expr, $($message:tt)*) => ({
69 span_mirbug!($context, $elem, $($message)*);
75 mod constraint_conversion;
76 pub mod free_region_relations;
81 /// Type checks the given `mir` in the context of the inference
82 /// context `infcx`. Returns any region constraints that have yet to
83 /// be proven. This result is includes liveness constraints that
84 /// ensure that regions appearing in the types of all local variables
85 /// are live at all points where that local variable may later be
88 /// This phase of type-check ought to be infallible -- this is because
89 /// the original, HIR-based type-check succeeded. So if any errors
90 /// occur here, we will get a `bug!` reported.
94 /// - `infcx` -- inference context to use
95 /// - `param_env` -- parameter environment to use for trait solving
96 /// - `mir` -- MIR to type-check
97 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
98 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
99 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
100 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
101 /// to outlive; should represent the fn body
102 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
103 /// the types of the input parameters found in the MIR itself will be equated with these
104 /// - `output_ty` -- fully liberaetd, but **not** normalized, expected return type;
105 /// the type for the RETURN_PLACE will be equated with this
106 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
107 /// constraints for the regions in the types of variables
108 /// - `flow_inits` -- results of a maybe-init dataflow analysis
109 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
110 /// - `errors_buffer` -- errors are sent here for future reporting
111 pub(crate) fn type_check<'gcx, 'tcx>(
112 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
113 param_env: ty::ParamEnv<'gcx>,
116 universal_regions: &Rc<UniversalRegions<'tcx>>,
117 location_table: &LocationTable,
118 borrow_set: &BorrowSet<'tcx>,
119 all_facts: &mut Option<AllFacts>,
120 flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
121 move_data: &MoveData<'tcx>,
122 elements: &Rc<RegionValueElements>,
123 errors_buffer: &mut Vec<Diagnostic>,
124 ) -> MirTypeckResults<'tcx> {
125 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
126 let mut constraints = MirTypeckRegionConstraints {
127 liveness_constraints: LivenessValues::new(elements),
128 outlives_constraints: ConstraintSet::default(),
129 type_tests: Vec::default(),
133 universal_region_relations,
135 normalized_inputs_and_output,
136 } = free_region_relations::create(
141 Some(implicit_region_bound),
147 let (liveness, liveness_map) = {
148 let mut borrowck_context = BorrowCheckContext {
153 constraints: &mut constraints,
162 Some(implicit_region_bound),
163 Some(&mut borrowck_context),
166 cx.equate_inputs_and_outputs(
170 &universal_region_relations,
171 &normalized_inputs_and_output,
173 liveness::generate(cx, mir, flow_inits, move_data)
180 universal_region_relations,
186 fn type_check_internal<'a, 'gcx, 'tcx, R>(
187 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
189 param_env: ty::ParamEnv<'gcx>,
191 region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
192 implicit_region_bound: Option<ty::Region<'tcx>>,
193 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
194 errors_buffer: Option<&mut Vec<Diagnostic>>,
195 mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
197 let mut checker = TypeChecker::new(
203 implicit_region_bound,
206 let errors_reported = {
207 let mut verifier = TypeVerifier::new(&mut checker, mir);
208 verifier.visit_mir(mir);
209 verifier.errors_reported
212 if !errors_reported {
213 // if verifier failed, don't do further checks to avoid ICEs
214 checker.typeck_mir(mir, errors_buffer);
220 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
221 // We sometimes see MIR failures (notably predicate failures) due to
222 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
223 // to avoid reporting bugs in those cases.
224 tcx.sess.diagnostic().delay_span_bug(span, msg);
227 enum FieldAccessError {
228 OutOfRange { field_count: usize },
231 /// Verifies that MIR types are sane to not crash further checks.
233 /// The sanitize_XYZ methods here take an MIR object and compute its
234 /// type, calling `span_mirbug` and returning an error type if there
236 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
237 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
241 errors_reported: bool,
244 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
245 fn visit_span(&mut self, span: &Span) {
246 if !span.is_dummy() {
247 self.last_span = *span;
251 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
252 self.sanitize_place(place, location, context);
255 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
256 self.super_constant(constant, location);
257 self.sanitize_constant(constant, location);
258 self.sanitize_type(constant, constant.ty);
261 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
262 self.super_rvalue(rvalue, location);
263 let rval_ty = rvalue.ty(self.mir, self.tcx());
264 self.sanitize_type(rvalue, rval_ty);
267 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
268 self.super_local_decl(local, local_decl);
269 self.sanitize_type(local_decl, local_decl.ty);
272 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
273 self.sanitize_type(&"return type", mir.return_ty());
274 for local_decl in &mir.local_decls {
275 self.sanitize_type(local_decl, local_decl.ty);
277 if self.errors_reported {
284 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
285 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
288 mir_def_id: cx.mir_def_id,
291 errors_reported: false,
295 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
299 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
300 if ty.has_escaping_regions() || ty.references_error() {
301 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
307 /// Checks that the constant's `ty` field matches up with what
308 /// would be expected from its literal.
309 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
311 "sanitize_constant(constant={:?}, location={:?})",
315 // FIXME(#46702) -- We need some way to get the predicates
316 // associated with the "pre-evaluated" form of the
317 // constant. For example, consider that the constant
318 // may have associated constant projections (`<Foo as
319 // Trait<'a, 'b>>::SOME_CONST`) that impose
320 // constraints on `'a` and `'b`. These constraints
321 // would be lost if we just look at the normalized
323 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
324 let tcx = self.tcx();
325 let type_checker = &mut self.cx;
327 // FIXME -- For now, use the substitutions from
328 // `value.ty` rather than `value.val`. The
329 // renumberer will rewrite them to independent
330 // sets of regions; in principle, we ought to
331 // derive the type of the `value.val` from "first
332 // principles" and equate with value.ty, but as we
333 // are transitioning to the miri-based system, we
334 // don't have a handy function for that, so for
335 // now we just ignore `value.val` regions.
337 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
338 type_checker.normalize_and_prove_instantiated_predicates(
339 instantiated_predicates,
344 debug!("sanitize_constant: expected_ty={:?}", constant.literal.ty);
346 if let Err(terr) = self
348 .eq_types(constant.literal.ty, constant.ty, location.boring())
353 "constant {:?} should have type {:?} but has {:?} ({:?})",
362 /// Checks that the types internal to the `place` match up with
363 /// what would be expected.
368 context: PlaceContext,
370 debug!("sanitize_place: {:?}", place);
371 let place_ty = match *place {
372 Place::Local(index) => PlaceTy::Ty {
373 ty: self.mir.local_decls[index].ty,
375 Place::Promoted(box (_index, sty)) => {
376 let sty = self.sanitize_type(place, sty);
377 // FIXME -- promoted MIR return types reference
378 // various "free regions" (e.g., scopes and things)
379 // that they ought not to do. We have to figure out
380 // how best to handle that -- probably we want treat
381 // promoted MIR much like closures, renumbering all
382 // their free regions and propagating constraints
383 // upwards. We have the same acyclic guarantees, so
384 // that should be possible. But for now, ignore them.
386 // let promoted_mir = &self.mir.promoted[index];
387 // promoted_mir.return_ty()
388 PlaceTy::Ty { ty: sty }
390 Place::Static(box Static { def_id, ty: sty }) => {
391 let sty = self.sanitize_type(place, sty);
392 let ty = self.tcx().type_of(def_id);
393 let ty = self.cx.normalize(ty, location);
394 if let Err(terr) = self.cx.eq_types(ty, sty, location.boring()) {
398 "bad static type ({:?}: {:?}): {:?}",
404 PlaceTy::Ty { ty: sty }
406 Place::Projection(ref proj) => {
407 let base_context = if context.is_mutating_use() {
408 PlaceContext::Projection(Mutability::Mut)
410 PlaceContext::Projection(Mutability::Not)
412 let base_ty = self.sanitize_place(&proj.base, location, base_context);
413 if let PlaceTy::Ty { ty } = base_ty {
414 if ty.references_error() {
415 assert!(self.errors_reported);
417 ty: self.tcx().types.err,
421 self.sanitize_projection(base_ty, &proj.elem, place, location)
424 if let PlaceContext::Copy = context {
425 let tcx = self.tcx();
426 let trait_ref = ty::TraitRef {
427 def_id: tcx.lang_items().copy_trait().unwrap(),
428 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
431 // In order to have a Copy operand, the type T of the value must be Copy. Note that we
432 // prove that T: Copy, rather than using the type_moves_by_default test. This is
433 // important because type_moves_by_default ignores the resulting region obligations and
434 // assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
435 // (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
436 // fully apply: in effect, the rule is that if a value of some type could implement
437 // Copy, then it must.
438 self.cx.prove_trait_ref(trait_ref, location.interesting());
443 fn sanitize_projection(
446 pi: &PlaceElem<'tcx>,
450 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
451 let tcx = self.tcx();
452 let base_ty = base.to_ty(tcx);
454 ProjectionElem::Deref => {
455 let deref_ty = base_ty.builtin_deref(true);
457 ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
458 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
462 ProjectionElem::Index(i) => {
463 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
464 if index_ty != tcx.types.usize {
466 ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
470 ty: base_ty.builtin_index().unwrap_or_else(|| {
471 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
476 ProjectionElem::ConstantIndex { .. } => {
477 // consider verifying in-bounds
479 ty: base_ty.builtin_index().unwrap_or_else(|| {
480 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
484 ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
485 ty: match base_ty.sty {
486 ty::Array(inner, size) => {
487 let size = size.unwrap_usize(tcx);
488 let min_size = (from as u64) + (to as u64);
489 if let Some(rest_size) = size.checked_sub(min_size) {
490 tcx.mk_array(inner, rest_size)
492 span_mirbug_and_err!(
495 "taking too-small slice of {:?}",
500 ty::Slice(..) => base_ty,
501 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
504 ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
505 ty::Adt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
506 if index >= adt_def.variants.len() {
508 ty: span_mirbug_and_err!(
511 "cast to variant #{:?} but enum only has {:?}",
513 adt_def.variants.len()
520 variant_index: index,
525 ty: span_mirbug_and_err!(
528 "can't downcast {:?} as {:?}",
534 ProjectionElem::Field(field, fty) => {
535 let fty = self.sanitize_type(place, fty);
536 match self.field_ty(place, base, field, location) {
537 Ok(ty) => if let Err(terr) = self.cx.eq_types(ty, fty, location.boring()) {
541 "bad field access ({:?}: {:?}): {:?}",
547 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
550 "accessed field #{} but variant only has {}",
555 PlaceTy::Ty { ty: fty }
560 fn error(&mut self) -> Ty<'tcx> {
561 self.errors_reported = true;
567 parent: &dyn fmt::Debug,
568 base_ty: PlaceTy<'tcx>,
571 ) -> Result<Ty<'tcx>, FieldAccessError> {
572 let tcx = self.tcx();
574 let (variant, substs) = match base_ty {
579 } => (&adt_def.variants[variant_index], substs),
580 PlaceTy::Ty { ty } => match ty.sty {
581 ty::Adt(adt_def, substs) if !adt_def.is_enum() => (&adt_def.variants[0], substs),
582 ty::Closure(def_id, substs) => {
583 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
585 None => Err(FieldAccessError::OutOfRange {
586 field_count: substs.upvar_tys(def_id, tcx).count(),
590 ty::Generator(def_id, substs, _) => {
591 // Try pre-transform fields first (upvars and current state)
592 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
596 // Then try `field_tys` which contains all the fields, but it
597 // requires the final optimized MIR.
598 return match substs.field_tys(def_id, tcx).nth(field.index()) {
600 None => Err(FieldAccessError::OutOfRange {
601 field_count: substs.field_tys(def_id, tcx).count(),
606 return match tys.get(field.index()) {
608 None => Err(FieldAccessError::OutOfRange {
609 field_count: tys.len(),
614 return Ok(span_mirbug_and_err!(
617 "can't project out of {:?}",
624 if let Some(field) = variant.fields.get(field.index()) {
625 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
627 Err(FieldAccessError::OutOfRange {
628 field_count: variant.fields.len(),
634 /// The MIR type checker. Visits the MIR and enforces all the
635 /// constraints needed for it to be valid and well-typed. Along the
636 /// way, it accrues region constraints -- these can later be used by
637 /// NLL region checking.
638 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
639 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
640 param_env: ty::ParamEnv<'gcx>,
644 region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
645 implicit_region_bound: Option<ty::Region<'tcx>>,
646 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
647 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
650 struct BorrowCheckContext<'a, 'tcx: 'a> {
651 universal_regions: &'a UniversalRegions<'tcx>,
652 location_table: &'a LocationTable,
653 all_facts: &'a mut Option<AllFacts>,
654 borrow_set: &'a BorrowSet<'tcx>,
655 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
658 crate struct MirTypeckResults<'tcx> {
659 crate constraints: MirTypeckRegionConstraints<'tcx>,
660 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
661 crate liveness: LivenessResults<LocalWithRegion>,
662 crate liveness_map: NllLivenessMap,
665 /// A collection of region constraints that must be satisfied for the
666 /// program to be considered well-typed.
667 crate struct MirTypeckRegionConstraints<'tcx> {
668 /// In general, the type-checker is not responsible for enforcing
669 /// liveness constraints; this job falls to the region inferencer,
670 /// which performs a liveness analysis. However, in some limited
671 /// cases, the MIR type-checker creates temporary regions that do
672 /// not otherwise appear in the MIR -- in particular, the
673 /// late-bound regions that it instantiates at call-sites -- and
674 /// hence it must report on their liveness constraints.
675 crate liveness_constraints: LivenessValues<RegionVid>,
677 crate outlives_constraints: ConstraintSet,
679 crate type_tests: Vec<TypeTest<'tcx>>,
682 /// The `Locations` type summarizes *where* region constraints are
683 /// required to hold. Normally, this is at a particular point which
684 /// created the obligation, but for constraints that the user gave, we
685 /// want the constraint to hold at all points.
686 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
688 /// Indicates that a type constraint should always be true. This
689 /// is particularly important in the new borrowck analysis for
690 /// things like the type of the return slot. Consider this
694 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
696 /// return &y; // error
700 /// Here, we wind up with the signature from the return type being
701 /// something like `&'1 u32` where `'1` is a universal region. But
702 /// the type of the return slot `_0` is something like `&'2 u32`
703 /// where `'2` is an existential region variable. The type checker
704 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
705 /// older NLL analysis, we required this only at the entry point
706 /// to the function. By the nature of the constraints, this wound
707 /// up propagating to all points reachable from start (because
708 /// `'1` -- as a universal region -- is live everywhere). In the
709 /// newer analysis, though, this doesn't work: `_0` is considered
710 /// dead at the start (it has no usable value) and hence this type
711 /// equality is basically a no-op. Then, later on, when we do `_0
712 /// = &'3 y`, that region `'3` never winds up related to the
713 /// universal region `'1` and hence no error occurs. Therefore, we
714 /// use Locations::All instead, which ensures that the `'1` and
715 /// `'2` are equal everything. We also use this for other
716 /// user-given type annotations; e.g., if the user wrote `let mut
717 /// x: &'static u32 = ...`, we would ensure that all values
718 /// assigned to `x` are of `'static` lifetime.
721 /// A "boring" constraint (caused by the given location) is one that
722 /// the user probably doesn't want to see described in diagnostics,
723 /// because it is kind of an artifact of the type system setup.
725 /// Example: `x = Foo { field: y }` technically creates
726 /// intermediate regions representing the "type of `Foo { field: y
727 /// }`", and data flows from `y` into those variables, but they
728 /// are not very interesting. The assignment into `x` on the other
732 /// An *important* outlives constraint (caused by the given
733 /// location) is one that would be useful to highlight in
734 /// diagnostics, because it represents a point where references
735 /// flow from one spot to another (e.g., `x = y`)
736 Interesting(Location),
740 pub fn from_location(&self) -> Option<Location> {
742 Locations::All => None,
743 Locations::Boring(from_location) | Locations::Interesting(from_location) => {
749 /// Gets a span representing the location.
750 pub fn span(&self, mir: &Mir<'_>) -> Span {
751 let span_location = match self {
752 Locations::All => Location::START,
753 Locations::Boring(l) | Locations::Interesting(l) => *l,
755 mir.source_info(span_location).span
759 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
761 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
764 param_env: ty::ParamEnv<'gcx>,
765 region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
766 implicit_region_bound: Option<ty::Region<'tcx>>,
767 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
776 implicit_region_bound,
778 reported_errors: FxHashSet(),
782 /// Given some operation `op` that manipulates types, proves
783 /// predicates, or otherwise uses the inference context, executes
784 /// `op` and then executes all the further obligations that `op`
785 /// returns. This will yield a set of outlives constraints amongst
786 /// regions which are extracted and stored as having occurred at
789 /// **Any `rustc::infer` operations that might generate region
790 /// constraints should occur within this method so that those
791 /// constraints can be properly localized!**
792 fn fully_perform_op<R>(
794 locations: Locations,
795 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
797 let (r, opt_data) = op.fully_perform(self.infcx)?;
799 if let Some(data) = &opt_data {
800 self.push_region_constraints(locations, data);
806 fn push_region_constraints(
808 locations: Locations,
809 data: &[QueryRegionConstraint<'tcx>],
812 "push_region_constraints: constraints generated at {:?} are {:#?}",
816 if let Some(ref mut borrowck_context) = self.borrowck_context {
817 constraint_conversion::ConstraintConversion::new(
819 borrowck_context.universal_regions,
820 borrowck_context.location_table,
821 self.region_bound_pairs,
822 self.implicit_region_bound,
825 &mut borrowck_context.constraints.outlives_constraints,
826 &mut borrowck_context.constraints.type_tests,
827 &mut borrowck_context.all_facts,
828 ).convert_all(&data);
832 fn sub_types(&mut self, sub: Ty<'tcx>, sup: Ty<'tcx>, locations: Locations) -> Fallible<()> {
833 relate_tys::sub_types(
838 self.borrowck_context.as_mut().map(|x| &mut **x),
842 fn eq_types(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, locations: Locations) -> Fallible<()> {
843 relate_tys::eq_types(
848 self.borrowck_context.as_mut().map(|x| &mut **x),
852 fn eq_canonical_type_and_type(
854 a: CanonicalTy<'tcx>,
856 locations: Locations,
858 relate_tys::eq_canonical_type_and_type(
863 self.borrowck_context.as_mut().map(|x| &mut **x),
867 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
871 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
872 debug!("check_stmt: {:?}", stmt);
873 let tcx = self.tcx();
875 StatementKind::Assign(ref place, ref rv) => {
876 // Assignments to temporaries are not "interesting";
877 // they are not caused by the user, but rather artifacts
878 // of lowering. Assignments to other sorts of places *are* interesting
880 let is_temp = if let Place::Local(l) = *place {
882 !mir.local_decls[l].is_user_variable.is_some()
887 let locations = if is_temp {
890 location.interesting()
893 let place_ty = place.ty(mir, tcx).to_ty(tcx);
894 let rv_ty = rv.ty(mir, tcx);
895 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
899 "bad assignment ({:?} = {:?}): {:?}",
905 self.check_rvalue(mir, rv, location);
906 if !self.tcx().features().unsized_locals {
907 let trait_ref = ty::TraitRef {
908 def_id: tcx.lang_items().sized_trait().unwrap(),
909 substs: tcx.mk_substs_trait(place_ty, &[]),
911 self.prove_trait_ref(trait_ref, location.interesting());
914 StatementKind::SetDiscriminant {
918 let place_type = place.ty(mir, tcx).to_ty(tcx);
919 let adt = match place_type.sty {
920 TyKind::Adt(adt, _) if adt.is_enum() => adt,
923 stmt.source_info.span,
924 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
930 if variant_index >= adt.variants.len() {
932 stmt.source_info.span,
933 "bad set discriminant ({:?} = {:?}): value of of range",
939 StatementKind::UserAssertTy(c_ty, local) => {
940 let local_ty = mir.local_decls()[local].ty;
941 if let Err(terr) = self.eq_canonical_type_and_type(c_ty, local_ty, Locations::All) {
945 "bad type assert ({:?} = {:?}): {:?}",
952 StatementKind::ReadForMatch(_)
953 | StatementKind::StorageLive(_)
954 | StatementKind::StorageDead(_)
955 | StatementKind::InlineAsm { .. }
956 | StatementKind::EndRegion(_)
957 | StatementKind::Validate(..)
958 | StatementKind::Nop => {}
965 term: &Terminator<'tcx>,
966 term_location: Location,
967 errors_buffer: &mut Option<&mut Vec<Diagnostic>>,
969 debug!("check_terminator: {:?}", term);
970 let tcx = self.tcx();
972 TerminatorKind::Goto { .. }
973 | TerminatorKind::Resume
974 | TerminatorKind::Abort
975 | TerminatorKind::Return
976 | TerminatorKind::GeneratorDrop
977 | TerminatorKind::Unreachable
978 | TerminatorKind::Drop { .. }
979 | TerminatorKind::FalseEdges { .. }
980 | TerminatorKind::FalseUnwind { .. } => {
981 // no checks needed for these
984 TerminatorKind::DropAndReplace {
990 let place_ty = location.ty(mir, tcx).to_ty(tcx);
991 let rv_ty = value.ty(mir, tcx);
993 let locations = term_location.interesting();
994 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
998 "bad DropAndReplace ({:?} = {:?}): {:?}",
1005 TerminatorKind::SwitchInt {
1010 let discr_ty = discr.ty(mir, tcx);
1011 if let Err(terr) = self.sub_types(discr_ty, switch_ty, term_location.boring()) {
1015 "bad SwitchInt ({:?} on {:?}): {:?}",
1021 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1022 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1024 // FIXME: check the values
1026 TerminatorKind::Call {
1032 let func_ty = func.ty(mir, tcx);
1033 debug!("check_terminator: call, func_ty={:?}", func_ty);
1034 let sig = match func_ty.sty {
1035 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1037 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1041 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
1042 term.source_info.span,
1043 LateBoundRegionConversionTime::FnCall,
1046 let sig = self.normalize(sig, term_location);
1047 self.check_call_dest(mir, term, &sig, destination, term_location, errors_buffer);
1049 self.prove_predicates(
1050 sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1051 term_location.boring(),
1054 // The ordinary liveness rules will ensure that all
1055 // regions in the type of the callee are live here. We
1056 // then further constrain the late-bound regions that
1057 // were instantiated at the call site to be live as
1058 // well. The resulting is that all the input (and
1059 // output) types in the signature must be live, since
1060 // all the inputs that fed into it were live.
1061 for &late_bound_region in map.values() {
1062 if let Some(ref mut borrowck_context) = self.borrowck_context {
1063 let region_vid = borrowck_context
1065 .to_region_vid(late_bound_region);
1068 .liveness_constraints
1069 .add_element(region_vid, term_location);
1073 self.check_call_inputs(mir, term, &sig, args, term_location);
1075 TerminatorKind::Assert {
1076 ref cond, ref msg, ..
1078 let cond_ty = cond.ty(mir, tcx);
1079 if cond_ty != tcx.types.bool {
1080 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1083 if let BoundsCheck { ref len, ref index } = *msg {
1084 if len.ty(mir, tcx) != tcx.types.usize {
1085 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1087 if index.ty(mir, tcx) != tcx.types.usize {
1088 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1092 TerminatorKind::Yield { ref value, .. } => {
1093 let value_ty = value.ty(mir, tcx);
1094 match mir.yield_ty {
1095 None => span_mirbug!(self, term, "yield in non-generator"),
1097 if let Err(terr) = self.sub_types(value_ty, ty, term_location.interesting())
1102 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1117 term: &Terminator<'tcx>,
1118 sig: &ty::FnSig<'tcx>,
1119 destination: &Option<(Place<'tcx>, BasicBlock)>,
1120 term_location: Location,
1121 errors_buffer: &mut Option<&mut Vec<Diagnostic>>,
1123 let tcx = self.tcx();
1124 match *destination {
1125 Some((ref dest, _target_block)) => {
1126 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1127 let is_temp = if let Place::Local(l) = *dest {
1128 l != RETURN_PLACE &&
1129 !mir.local_decls[l].is_user_variable.is_some()
1134 let locations = if is_temp {
1135 term_location.boring()
1137 term_location.interesting()
1140 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations) {
1144 "call dest mismatch ({:?} <- {:?}): {:?}",
1151 // When `#![feature(unsized_locals)]` is not enabled,
1152 // this check is done at `check_local`.
1153 if self.tcx().features().unsized_locals {
1154 let span = term.source_info.span;
1155 self.ensure_place_sized(dest_ty, span, errors_buffer);
1159 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1160 if !sig.output().is_never() {
1161 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1167 fn check_call_inputs(
1170 term: &Terminator<'tcx>,
1171 sig: &ty::FnSig<'tcx>,
1172 args: &[Operand<'tcx>],
1173 term_location: Location,
1175 debug!("check_call_inputs({:?}, {:?})", sig, args);
1176 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1177 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1179 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1180 let op_arg_ty = op_arg.ty(mir, self.tcx());
1181 if let Err(terr) = self.sub_types(op_arg_ty, fn_arg, term_location.interesting()) {
1185 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1195 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1196 let is_cleanup = block_data.is_cleanup;
1197 self.last_span = block_data.terminator().source_info.span;
1198 match block_data.terminator().kind {
1199 TerminatorKind::Goto { target } => {
1200 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1202 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1203 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1205 TerminatorKind::Resume => if !is_cleanup {
1206 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1208 TerminatorKind::Abort => if !is_cleanup {
1209 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1211 TerminatorKind::Return => if is_cleanup {
1212 span_mirbug!(self, block_data, "return on cleanup block")
1214 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1215 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1217 TerminatorKind::Yield { resume, drop, .. } => {
1219 span_mirbug!(self, block_data, "yield in cleanup block")
1221 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1222 if let Some(drop) = drop {
1223 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1226 TerminatorKind::Unreachable => {}
1227 TerminatorKind::Drop { target, unwind, .. }
1228 | TerminatorKind::DropAndReplace { target, unwind, .. }
1229 | TerminatorKind::Assert {
1234 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1235 if let Some(unwind) = unwind {
1237 span_mirbug!(self, block_data, "unwind on cleanup block")
1239 self.assert_iscleanup(mir, block_data, unwind, true);
1242 TerminatorKind::Call {
1247 if let &Some((_, target)) = destination {
1248 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1250 if let Some(cleanup) = cleanup {
1252 span_mirbug!(self, block_data, "cleanup on cleanup block")
1254 self.assert_iscleanup(mir, block_data, cleanup, true);
1257 TerminatorKind::FalseEdges {
1259 ref imaginary_targets,
1261 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1262 for target in imaginary_targets {
1263 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1266 TerminatorKind::FalseUnwind {
1270 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1271 if let Some(unwind) = unwind {
1276 "cleanup in cleanup block via false unwind"
1279 self.assert_iscleanup(mir, block_data, unwind, true);
1285 fn assert_iscleanup(
1288 ctxt: &dyn fmt::Debug,
1292 if mir[bb].is_cleanup != iscleanuppad {
1296 "cleanuppad mismatch: {:?} should be {:?}",
1307 local_decl: &LocalDecl<'tcx>,
1308 errors_buffer: &mut Option<&mut Vec<Diagnostic>>,
1310 match mir.local_kind(local) {
1311 LocalKind::ReturnPointer | LocalKind::Arg => {
1312 // return values of normal functions are required to be
1313 // sized by typeck, but return values of ADT constructors are
1314 // not because we don't include a `Self: Sized` bounds on them.
1316 // Unbound parts of arguments were never required to be Sized
1317 // - maybe we should make that a warning.
1320 LocalKind::Var | LocalKind::Temp => {}
1323 // When `#![feature(unsized_locals)]` is enabled, only function calls
1324 // are checked in `check_call_dest`.
1325 if !self.tcx().features().unsized_locals {
1326 let span = local_decl.source_info.span;
1327 let ty = local_decl.ty;
1328 self.ensure_place_sized(ty, span, errors_buffer);
1332 fn ensure_place_sized(&mut self,
1335 errors_buffer: &mut Option<&mut Vec<Diagnostic>>) {
1336 let tcx = self.tcx();
1338 // Erase the regions from `ty` to get a global type. The
1339 // `Sized` bound in no way depends on precise regions, so this
1340 // shouldn't affect `is_sized`.
1341 let gcx = tcx.global_tcx();
1342 let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1343 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1344 // in current MIR construction, all non-control-flow rvalue
1345 // expressions evaluate through `as_temp` or `into` a return
1346 // slot or local, so to find all unsized rvalues it is enough
1347 // to check all temps, return slots and locals.
1348 if let None = self.reported_errors.replace((ty, span)) {
1349 let mut diag = struct_span_err!(
1353 "cannot move a value of type {0}: the size of {0} \
1354 cannot be statically determined",
1357 if let Some(ref mut errors_buffer) = *errors_buffer {
1358 diag.buffer(errors_buffer);
1360 // we're allowed to use emit() here because the
1361 // NLL migration will be turned on (and thus
1362 // errors will need to be buffered) *only if*
1363 // errors_buffer is Some.
1370 fn aggregate_field_ty(
1372 ak: &AggregateKind<'tcx>,
1375 ) -> Result<Ty<'tcx>, FieldAccessError> {
1376 let tcx = self.tcx();
1379 AggregateKind::Adt(def, variant_index, substs, active_field_index) => {
1380 let variant = &def.variants[variant_index];
1381 let adj_field_index = active_field_index.unwrap_or(field_index);
1382 if let Some(field) = variant.fields.get(adj_field_index) {
1383 Ok(self.normalize(field.ty(tcx, substs), location))
1385 Err(FieldAccessError::OutOfRange {
1386 field_count: variant.fields.len(),
1390 AggregateKind::Closure(def_id, substs) => {
1391 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1393 None => Err(FieldAccessError::OutOfRange {
1394 field_count: substs.upvar_tys(def_id, tcx).count(),
1398 AggregateKind::Generator(def_id, substs, _) => {
1399 // Try pre-transform fields first (upvars and current state)
1400 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1403 // Then try `field_tys` which contains all the fields, but it
1404 // requires the final optimized MIR.
1405 match substs.field_tys(def_id, tcx).nth(field_index) {
1407 None => Err(FieldAccessError::OutOfRange {
1408 field_count: substs.field_tys(def_id, tcx).count(),
1413 AggregateKind::Array(ty) => Ok(ty),
1414 AggregateKind::Tuple => {
1415 unreachable!("This should have been covered in check_rvalues");
1420 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1421 let tcx = self.tcx();
1424 Rvalue::Aggregate(ak, ops) => {
1425 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1428 Rvalue::Repeat(operand, len) => if *len > 1 {
1429 let operand_ty = operand.ty(mir, tcx);
1431 let trait_ref = ty::TraitRef {
1432 def_id: tcx.lang_items().copy_trait().unwrap(),
1433 substs: tcx.mk_substs_trait(operand_ty, &[]),
1436 self.prove_trait_ref(trait_ref, location.interesting());
1439 Rvalue::NullaryOp(_, ty) => {
1440 let trait_ref = ty::TraitRef {
1441 def_id: tcx.lang_items().sized_trait().unwrap(),
1442 substs: tcx.mk_substs_trait(ty, &[]),
1445 self.prove_trait_ref(trait_ref, location.interesting());
1448 Rvalue::Cast(cast_kind, op, ty) => match cast_kind {
1449 CastKind::ReifyFnPointer => {
1450 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1452 // The type that we see in the fcx is like
1453 // `foo::<'a, 'b>`, where `foo` is the path to a
1454 // function definition. When we extract the
1455 // signature, it comes from the `fn_sig` query,
1456 // and hence may contain unnormalized results.
1457 let fn_sig = self.normalize(fn_sig, location);
1459 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1461 if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1465 "equating {:?} with {:?} yields {:?}",
1473 CastKind::ClosureFnPointer => {
1474 let sig = match op.ty(mir, tcx).sty {
1475 ty::Closure(def_id, substs) => {
1476 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1480 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1482 if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1486 "equating {:?} with {:?} yields {:?}",
1494 CastKind::UnsafeFnPointer => {
1495 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1497 // The type that we see in the fcx is like
1498 // `foo::<'a, 'b>`, where `foo` is the path to a
1499 // function definition. When we extract the
1500 // signature, it comes from the `fn_sig` query,
1501 // and hence may contain unnormalized results.
1502 let fn_sig = self.normalize(fn_sig, location);
1504 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1506 if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1510 "equating {:?} with {:?} yields {:?}",
1518 CastKind::Unsize => {
1520 let trait_ref = ty::TraitRef {
1521 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1522 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1525 self.prove_trait_ref(trait_ref, location.interesting());
1528 CastKind::Misc => {}
1531 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1532 self.add_reborrow_constraint(location, region, borrowed_place);
1535 // FIXME: These other cases have to be implemented in future PRs
1538 | Rvalue::BinaryOp(..)
1539 | Rvalue::CheckedBinaryOp(..)
1540 | Rvalue::UnaryOp(..)
1541 | Rvalue::Discriminant(..) => {}
1545 fn check_aggregate_rvalue(
1548 rvalue: &Rvalue<'tcx>,
1549 aggregate_kind: &AggregateKind<'tcx>,
1550 operands: &[Operand<'tcx>],
1553 let tcx = self.tcx();
1555 self.prove_aggregate_predicates(aggregate_kind, location);
1557 if *aggregate_kind == AggregateKind::Tuple {
1558 // tuple rvalue field type is always the type of the op. Nothing to check here.
1562 for (i, operand) in operands.iter().enumerate() {
1563 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
1564 Ok(field_ty) => field_ty,
1565 Err(FieldAccessError::OutOfRange { field_count }) => {
1569 "accessed field #{} but variant only has {}",
1576 let operand_ty = operand.ty(mir, tcx);
1578 if let Err(terr) = self.sub_types(operand_ty, field_ty, location.boring()) {
1582 "{:?} is not a subtype of {:?}: {:?}",
1591 /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
1595 /// - `location`: the location `L` where the borrow expression occurs
1596 /// - `borrow_region`: the region `'a` associated with the borrow
1597 /// - `borrowed_place`: the place `P` being borrowed
1598 fn add_reborrow_constraint(
1601 borrow_region: ty::Region<'tcx>,
1602 borrowed_place: &Place<'tcx>,
1604 // These constraints are only meaningful during borrowck:
1605 let BorrowCheckContext {
1611 } = match self.borrowck_context {
1612 Some(ref mut borrowck_context) => borrowck_context,
1616 // In Polonius mode, we also push a `borrow_region` fact
1617 // linking the loan to the region (in some cases, though,
1618 // there is no loan associated with this borrow expression --
1619 // that occurs when we are borrowing an unsafe place, for
1621 if let Some(all_facts) = all_facts {
1622 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
1623 let region_vid = borrow_region.to_region_vid();
1624 all_facts.borrow_region.push((
1627 location_table.mid_index(location),
1632 // If we are reborrowing the referent of another reference, we
1633 // need to add outlives relationships. In a case like `&mut
1634 // *p`, where the `p` has type `&'b mut Foo`, for example, we
1635 // need to ensure that `'b: 'a`.
1637 let mut borrowed_place = borrowed_place;
1640 "add_reborrow_constraint({:?}, {:?}, {:?})",
1641 location, borrow_region, borrowed_place
1643 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
1644 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
1647 ProjectionElem::Deref => {
1648 let tcx = self.infcx.tcx;
1649 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1651 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
1653 ty::Ref(ref_region, _, mutbl) => {
1654 constraints.outlives_constraints.push(OutlivesConstraint {
1655 sup: ref_region.to_region_vid(),
1656 sub: borrow_region.to_region_vid(),
1657 locations: location.boring(),
1660 if let Some(all_facts) = all_facts {
1661 all_facts.outlives.push((
1662 ref_region.to_region_vid(),
1663 borrow_region.to_region_vid(),
1664 location_table.mid_index(location),
1669 hir::Mutability::MutImmutable => {
1670 // Immutable reference. We don't need the base
1671 // to be valid for the entire lifetime of
1675 hir::Mutability::MutMutable => {
1676 // Mutable reference. We *do* need the base
1677 // to be valid, because after the base becomes
1678 // invalid, someone else can use our mutable deref.
1680 // This is in order to make the following function
1683 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
1688 // As otherwise you could clone `&mut T` using the
1689 // following function:
1691 // fn bad(x: &mut T) -> (&mut T, &mut T) {
1692 // let my_clone = unsafe_deref(&'a x);
1701 // deref of raw pointer, guaranteed to be valid
1704 ty::Adt(def, _) if def.is_box() => {
1705 // deref of `Box`, need the base to be valid - propagate
1707 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
1710 ProjectionElem::Field(..)
1711 | ProjectionElem::Downcast(..)
1712 | ProjectionElem::Index(..)
1713 | ProjectionElem::ConstantIndex { .. }
1714 | ProjectionElem::Subslice { .. } => {
1715 // other field access
1719 // The "propagate" case. We need to check that our base is valid
1720 // for the borrow's lifetime.
1721 borrowed_place = base;
1725 fn prove_aggregate_predicates(
1727 aggregate_kind: &AggregateKind<'tcx>,
1730 let tcx = self.tcx();
1733 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
1734 aggregate_kind, location
1737 let instantiated_predicates = match aggregate_kind {
1738 AggregateKind::Adt(def, _, substs, _) => {
1739 tcx.predicates_of(def.did).instantiate(tcx, substs)
1742 // For closures, we have some **extra requirements** we
1744 // have to check. In particular, in their upvars and
1745 // signatures, closures often reference various regions
1746 // from the surrounding function -- we call those the
1747 // closure's free regions. When we borrow-check (and hence
1748 // region-check) closures, we may find that the closure
1749 // requires certain relationships between those free
1750 // regions. However, because those free regions refer to
1751 // portions of the CFG of their caller, the closure is not
1752 // in a position to verify those relationships. In that
1753 // case, the requirements get "propagated" to us, and so
1754 // we have to solve them here where we instantiate the
1757 // Despite the opacity of the previous parapgrah, this is
1758 // actually relatively easy to understand in terms of the
1759 // desugaring. A closure gets desugared to a struct, and
1760 // these extra requirements are basically like where
1761 // clauses on the struct.
1762 AggregateKind::Closure(def_id, substs) => {
1763 if let Some(closure_region_requirements) =
1764 tcx.mir_borrowck(*def_id).closure_requirements
1766 let closure_constraints = closure_region_requirements.apply_requirements(
1773 // Hmm, are these constraints *really* boring?
1774 self.push_region_constraints(location.boring(), &closure_constraints);
1777 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1780 AggregateKind::Generator(def_id, substs, _) => {
1781 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1784 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
1787 self.normalize_and_prove_instantiated_predicates(
1788 instantiated_predicates,
1793 fn prove_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>, locations: Locations) {
1794 self.prove_predicates(
1795 Some(ty::Predicate::Trait(
1796 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
1802 fn normalize_and_prove_instantiated_predicates(
1804 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
1805 locations: Locations,
1807 for predicate in instantiated_predicates.predicates {
1808 let predicate = self.normalize(predicate, locations);
1809 self.prove_predicate(predicate, locations);
1813 fn prove_predicates(
1815 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
1816 locations: Locations,
1818 for predicate in predicates {
1820 "prove_predicates(predicate={:?}, locations={:?})",
1821 predicate, locations,
1824 self.prove_predicate(predicate, locations);
1828 fn prove_predicate(&mut self, predicate: ty::Predicate<'tcx>, locations: Locations) {
1830 "prove_predicate(predicate={:?}, location={:?})",
1831 predicate, locations,
1834 let param_env = self.param_env;
1835 self.fully_perform_op(
1837 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
1838 ).unwrap_or_else(|NoSolution| {
1839 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
1843 fn typeck_mir(&mut self, mir: &Mir<'tcx>, mut errors_buffer: Option<&mut Vec<Diagnostic>>) {
1844 self.last_span = mir.span;
1845 debug!("run_on_mir: {:?}", mir.span);
1847 for (local, local_decl) in mir.local_decls.iter_enumerated() {
1848 self.check_local(mir, local, local_decl, &mut errors_buffer);
1851 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
1852 let mut location = Location {
1856 for stmt in &block_data.statements {
1857 if !stmt.source_info.span.is_dummy() {
1858 self.last_span = stmt.source_info.span;
1860 self.check_stmt(mir, stmt, location);
1861 location.statement_index += 1;
1864 self.check_terminator(mir, block_data.terminator(), location, &mut errors_buffer);
1865 self.check_iscleanup(mir, block_data);
1869 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
1871 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
1873 debug!("normalize(value={:?}, location={:?})", value, location);
1874 let param_env = self.param_env;
1875 self.fully_perform_op(
1876 location.to_locations(),
1877 param_env.and(type_op::normalize::Normalize::new(value)),
1878 ).unwrap_or_else(|NoSolution| {
1879 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
1885 pub struct TypeckMir;
1887 impl MirPass for TypeckMir {
1888 fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
1889 let def_id = src.def_id;
1890 debug!("run_pass: {:?}", def_id);
1892 // When NLL is enabled, the borrow checker runs the typeck
1893 // itself, so we don't need this MIR pass anymore.
1894 if tcx.use_mir_borrowck() {
1898 if tcx.sess.err_count() > 0 {
1899 // compiling a broken program can obviously result in a
1900 // broken MIR, so try not to report duplicate errors.
1904 if tcx.is_struct_constructor(def_id) {
1905 // We just assume that the automatically generated struct constructors are
1906 // correct. See the comment in the `mir_borrowck` implementation for an
1907 // explanation why we need this.
1911 let param_env = tcx.param_env(def_id);
1912 tcx.infer_ctxt().enter(|infcx| {
1913 type_check_internal(
1925 // For verification purposes, we just ignore the resulting
1926 // region constraint sets. Not our problem. =)
1931 pub trait AtLocation {
1932 /// Indicates a "boring" constraint that the user probably
1933 /// woudln't want to see highlights.
1934 fn boring(self) -> Locations;
1936 /// Indicates an "interesting" edge, which is of significance only
1937 /// for diagnostics.
1938 fn interesting(self) -> Locations;
1941 impl AtLocation for Location {
1942 fn boring(self) -> Locations {
1943 Locations::Boring(self)
1946 fn interesting(self) -> Locations {
1947 Locations::Interesting(self)
1951 trait NormalizeLocation: fmt::Debug + Copy {
1952 fn to_locations(self) -> Locations;
1955 impl NormalizeLocation for Locations {
1956 fn to_locations(self) -> Locations {
1961 impl NormalizeLocation for Location {
1962 fn to_locations(self) -> Locations {