1 //! This pass type-checks the MIR to ensure it is not broken.
3 #![allow(unreachable_code)]
5 use crate::borrow_check::borrow_set::BorrowSet;
6 use crate::borrow_check::location::LocationTable;
7 use crate::borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
8 use crate::borrow_check::nll::facts::AllFacts;
9 use crate::borrow_check::nll::region_infer::values::LivenessValues;
10 use crate::borrow_check::nll::region_infer::values::PlaceholderIndex;
11 use crate::borrow_check::nll::region_infer::values::PlaceholderIndices;
12 use crate::borrow_check::nll::region_infer::values::RegionValueElements;
13 use crate::borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
14 use crate::borrow_check::nll::renumber;
15 use crate::borrow_check::nll::type_check::free_region_relations::{
16 CreateResult, UniversalRegionRelations,
18 use crate::borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
19 use crate::borrow_check::nll::ToRegionVid;
20 use crate::dataflow::move_paths::MoveData;
21 use crate::dataflow::FlowAtLocation;
22 use crate::dataflow::MaybeInitializedPlaces;
23 use crate::transform::{MirPass, MirSource};
26 use rustc::hir::def_id::DefId;
27 use rustc::infer::canonical::QueryRegionConstraint;
28 use rustc::infer::outlives::env::RegionBoundPairs;
29 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
30 use rustc::infer::type_variable::TypeVariableOrigin;
31 use rustc::mir::interpret::{InterpError::BoundsCheck, ConstValue};
32 use rustc::mir::tcx::PlaceTy;
33 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
35 use rustc::traits::query::type_op;
36 use rustc::traits::query::type_op::custom::CustomTypeOp;
37 use rustc::traits::query::{Fallible, NoSolution};
38 use rustc::traits::{ObligationCause, PredicateObligations};
39 use rustc::ty::fold::TypeFoldable;
40 use rustc::ty::subst::{Subst, SubstsRef, UnpackedKind, UserSubsts};
42 self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, UserType,
43 CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
44 UserTypeAnnotationIndex,
46 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
47 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
48 use rustc::ty::layout::VariantIdx;
50 use std::{fmt, iter, mem};
51 use syntax_pos::{Span, DUMMY_SP};
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 liberated, 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 pub(crate) fn type_check<'gcx, 'tcx>(
113 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
114 param_env: ty::ParamEnv<'gcx>,
117 universal_regions: &Rc<UniversalRegions<'tcx>>,
118 location_table: &LocationTable,
119 borrow_set: &BorrowSet<'tcx>,
120 all_facts: &mut Option<AllFacts>,
121 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
122 move_data: &MoveData<'tcx>,
123 elements: &Rc<RegionValueElements>,
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 placeholder_indices: PlaceholderIndices::default(),
128 placeholder_index_to_region: IndexVec::default(),
129 liveness_constraints: LivenessValues::new(elements.clone()),
130 outlives_constraints: ConstraintSet::default(),
131 closure_bounds_mapping: Default::default(),
132 type_tests: Vec::default(),
136 universal_region_relations,
138 normalized_inputs_and_output,
139 } = free_region_relations::create(
142 Some(implicit_region_bound),
147 let mut borrowck_context = BorrowCheckContext {
152 constraints: &mut constraints,
161 Some(implicit_region_bound),
162 Some(&mut borrowck_context),
163 Some(&universal_region_relations),
165 cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
166 liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
170 .map(|bcx| translate_outlives_facts(bcx));
176 universal_region_relations,
180 fn type_check_internal<'a, 'gcx, 'tcx, R>(
181 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
183 param_env: ty::ParamEnv<'gcx>,
185 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
186 implicit_region_bound: Option<ty::Region<'tcx>>,
187 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
188 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
189 mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
191 let mut checker = TypeChecker::new(
197 implicit_region_bound,
199 universal_region_relations,
201 let errors_reported = {
202 let mut verifier = TypeVerifier::new(&mut checker, mir);
203 verifier.visit_mir(mir);
204 verifier.errors_reported
207 if !errors_reported {
208 // if verifier failed, don't do further checks to avoid ICEs
209 checker.typeck_mir(mir);
215 fn translate_outlives_facts(cx: &mut BorrowCheckContext<'_, '_>) {
216 if let Some(facts) = cx.all_facts {
217 let location_table = cx.location_table;
220 .extend(cx.constraints.outlives_constraints.iter().flat_map(
221 |constraint: &OutlivesConstraint| {
222 if let Some(from_location) = constraint.locations.from_location() {
223 Either::Left(iter::once((
226 location_table.mid_index(from_location),
232 .map(move |location| (constraint.sup, constraint.sub, location)),
240 fn mirbug(tcx: TyCtxt<'_, '_, '_>, span: Span, msg: &str) {
241 // We sometimes see MIR failures (notably predicate failures) due to
242 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
243 // to avoid reporting bugs in those cases.
244 tcx.sess.diagnostic().delay_span_bug(span, msg);
247 enum FieldAccessError {
248 OutOfRange { field_count: usize },
251 /// Verifies that MIR types are sane to not crash further checks.
253 /// The sanitize_XYZ methods here take an MIR object and compute its
254 /// type, calling `span_mirbug` and returning an error type if there
256 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
257 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
261 errors_reported: bool,
264 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
265 fn visit_span(&mut self, span: &Span) {
266 if !span.is_dummy() {
267 self.last_span = *span;
271 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext<'_>, location: Location) {
272 self.sanitize_place(place, location, context);
275 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
276 self.super_constant(constant, location);
277 self.sanitize_constant(constant, location);
278 self.sanitize_type(constant, constant.ty);
280 if let Some(annotation_index) = constant.user_ty {
281 if let Err(terr) = self.cx.relate_type_and_user_type(
283 ty::Variance::Invariant,
284 &UserTypeProjection { base: annotation_index, projs: vec![], },
285 location.to_locations(),
286 ConstraintCategory::Boring,
288 let annotation = &self.cx.user_type_annotations[annotation_index];
292 "bad constant user type {:?} vs {:?}: {:?}",
299 if let ConstValue::Unevaluated(def_id, substs) = constant.literal.val {
300 if let Err(terr) = self.cx.fully_perform_op(
301 location.to_locations(),
302 ConstraintCategory::Boring,
303 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
304 constant.ty, def_id, UserSubsts { substs, user_self_ty: None },
310 "bad constant type {:?} ({:?})",
316 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
317 let tcx = self.tcx();
319 let instantiated_predicates = tcx
320 .predicates_of(def_id)
321 .instantiate(tcx, substs);
322 self.cx.normalize_and_prove_instantiated_predicates(
323 instantiated_predicates,
324 location.to_locations(),
330 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
331 self.super_rvalue(rvalue, location);
332 let rval_ty = rvalue.ty(self.mir, self.tcx());
333 self.sanitize_type(rvalue, rval_ty);
336 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
337 self.super_local_decl(local, local_decl);
338 self.sanitize_type(local_decl, local_decl.ty);
340 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
341 let ty = if !local_decl.is_nonref_binding() {
342 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
343 // reference so we can check the type annotation for the remaining type.
344 if let ty::Ref(_, rty, _) = local_decl.ty.sty {
347 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
353 if let Err(terr) = self.cx.relate_type_and_user_type(
355 ty::Variance::Invariant,
357 Locations::All(*span),
358 ConstraintCategory::TypeAnnotation,
363 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
373 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
374 self.sanitize_type(&"return type", mir.return_ty());
375 for local_decl in &mir.local_decls {
376 self.sanitize_type(local_decl, local_decl.ty);
378 if self.errors_reported {
385 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
386 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'b Mir<'tcx>) -> Self {
389 mir_def_id: cx.mir_def_id,
392 errors_reported: false,
396 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
400 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
401 if ty.has_escaping_bound_vars() || ty.references_error() {
402 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
408 /// Checks that the constant's `ty` field matches up with what would be
409 /// expected from its literal. Unevaluated constants and well-formed
410 /// constraints are checked by `visit_constant`.
411 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
413 "sanitize_constant(constant={:?}, location={:?})",
417 let literal = constant.literal;
419 if let ConstValue::Unevaluated(..) = literal.val {
423 debug!("sanitize_constant: expected_ty={:?}", literal.ty);
425 if let Err(terr) = self.cx.eq_types(
428 location.to_locations(),
429 ConstraintCategory::Boring,
434 "constant {:?} should have type {:?} but has {:?} ({:?})",
443 /// Checks that the types internal to the `place` match up with
444 /// what would be expected.
449 context: PlaceContext<'_>,
451 debug!("sanitize_place: {:?}", place);
452 let place_ty = match place {
453 Place::Base(PlaceBase::Local(index)) =>
454 PlaceTy::from_ty(self.mir.local_decls[*index].ty),
455 Place::Base(PlaceBase::Static(box Static { kind, ty: sty })) => {
456 let sty = self.sanitize_type(place, sty);
458 |verifier: &mut TypeVerifier<'a, 'b, 'gcx, 'tcx>,
462 if let Err(terr) = verifier.cx.eq_types(
465 location.to_locations(),
466 ConstraintCategory::Boring,
471 "bad promoted type ({:?}: {:?}): {:?}",
479 StaticKind::Promoted(promoted) => {
480 if !self.errors_reported {
481 let promoted_mir = &self.mir.promoted[*promoted];
482 self.sanitize_promoted(promoted_mir, location);
484 let promoted_ty = promoted_mir.return_ty();
485 check_err(self, place, promoted_ty, sty);
488 StaticKind::Static(def_id) => {
489 let ty = self.tcx().type_of(*def_id);
490 let ty = self.cx.normalize(ty, location);
492 check_err(self, place, ty, sty);
495 PlaceTy::from_ty(sty)
497 Place::Projection(ref proj) => {
498 let base_context = if context.is_mutating_use() {
499 PlaceContext::MutatingUse(MutatingUseContext::Projection)
501 PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
503 let base_ty = self.sanitize_place(&proj.base, location, base_context);
504 if base_ty.variant_index.is_none() {
505 if base_ty.ty.references_error() {
506 assert!(self.errors_reported);
507 return PlaceTy::from_ty(self.tcx().types.err);
510 self.sanitize_projection(base_ty, &proj.elem, place, location)
513 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
514 let tcx = self.tcx();
515 let trait_ref = ty::TraitRef {
516 def_id: tcx.lang_items().copy_trait().unwrap(),
517 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
520 // In order to have a Copy operand, the type T of the
521 // value must be Copy. Note that we prove that T: Copy,
522 // rather than using the `is_copy_modulo_regions`
523 // test. This is important because
524 // `is_copy_modulo_regions` ignores the resulting region
525 // obligations and assumes they pass. This can result in
526 // bounds from Copy impls being unsoundly ignored (e.g.,
527 // #29149). Note that we decide to use Copy before knowing
528 // whether the bounds fully apply: in effect, the rule is
529 // that if a value of some type could implement Copy, then
531 self.cx.prove_trait_ref(
533 location.to_locations(),
534 ConstraintCategory::CopyBound,
540 fn sanitize_promoted(&mut self, promoted_mir: &'b Mir<'tcx>, location: Location) {
541 // Determine the constraints from the promoted MIR by running the type
542 // checker on the promoted MIR, then transfer the constraints back to
543 // the main MIR, changing the locations to the provided location.
545 let parent_mir = mem::replace(&mut self.mir, promoted_mir);
547 let all_facts = &mut None;
548 let mut constraints = Default::default();
549 let mut closure_bounds = Default::default();
550 if let Some(ref mut bcx) = self.cx.borrowck_context {
551 // Don't try to add borrow_region facts for the promoted MIR
552 mem::swap(bcx.all_facts, all_facts);
554 // Use a new sets of constraints and closure bounds so that we can
555 // modify their locations.
556 mem::swap(&mut bcx.constraints.outlives_constraints, &mut constraints);
557 mem::swap(&mut bcx.constraints.closure_bounds_mapping, &mut closure_bounds);
560 self.visit_mir(promoted_mir);
562 if !self.errors_reported {
563 // if verifier failed, don't do further checks to avoid ICEs
564 self.cx.typeck_mir(promoted_mir);
567 self.mir = parent_mir;
568 // Merge the outlives constraints back in, at the given location.
569 if let Some(ref mut base_bcx) = self.cx.borrowck_context {
570 mem::swap(base_bcx.all_facts, all_facts);
571 mem::swap(&mut base_bcx.constraints.outlives_constraints, &mut constraints);
572 mem::swap(&mut base_bcx.constraints.closure_bounds_mapping, &mut closure_bounds);
574 let locations = location.to_locations();
575 for constraint in constraints.iter() {
576 let mut constraint = *constraint;
577 constraint.locations = locations;
578 if let ConstraintCategory::Return
579 | ConstraintCategory::UseAsConst
580 | ConstraintCategory::UseAsStatic = constraint.category
582 // "Returning" from a promoted is an assigment to a
583 // temporary from the user's point of view.
584 constraint.category = ConstraintCategory::Boring;
586 base_bcx.constraints.outlives_constraints.push(constraint)
589 if !closure_bounds.is_empty() {
590 let combined_bounds_mapping = closure_bounds
592 .flat_map(|(_, value)| value)
594 let existing = base_bcx
596 .closure_bounds_mapping
597 .insert(location, combined_bounds_mapping);
600 "Multiple promoteds/closures at the same location."
606 fn sanitize_projection(
609 pi: &PlaceElem<'tcx>,
613 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
614 let tcx = self.tcx();
615 let base_ty = base.ty;
617 ProjectionElem::Deref => {
618 let deref_ty = base_ty.builtin_deref(true);
620 deref_ty.map(|t| t.ty).unwrap_or_else(|| {
621 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
625 ProjectionElem::Index(i) => {
626 let index_ty = Place::Base(PlaceBase::Local(i)).ty(self.mir, tcx).ty;
627 if index_ty != tcx.types.usize {
629 span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
633 base_ty.builtin_index().unwrap_or_else(|| {
634 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
639 ProjectionElem::ConstantIndex { .. } => {
640 // consider verifying in-bounds
642 base_ty.builtin_index().unwrap_or_else(|| {
643 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
647 ProjectionElem::Subslice { from, to } => PlaceTy::from_ty(
649 ty::Array(inner, size) => {
650 let size = size.unwrap_usize(tcx);
651 let min_size = (from as u64) + (to as u64);
652 if let Some(rest_size) = size.checked_sub(min_size) {
653 tcx.mk_array(inner, rest_size)
655 span_mirbug_and_err!(
658 "taking too-small slice of {:?}",
663 ty::Slice(..) => base_ty,
664 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
667 ProjectionElem::Downcast(maybe_name, index) => match base_ty.sty {
668 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
669 if index.as_usize() >= adt_def.variants.len() {
671 span_mirbug_and_err!(
674 "cast to variant #{:?} but enum only has {:?}",
676 adt_def.variants.len()
682 variant_index: Some(index),
687 let ty = if let Some(name) = maybe_name {
688 span_mirbug_and_err!(
691 "can't downcast {:?} as {:?}",
696 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
701 ProjectionElem::Field(field, fty) => {
702 let fty = self.sanitize_type(place, fty);
703 match self.field_ty(place, base, field, location) {
704 Ok(ty) => if let Err(terr) = self.cx.eq_types(
707 location.to_locations(),
708 ConstraintCategory::Boring,
713 "bad field access ({:?}: {:?}): {:?}",
719 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
722 "accessed field #{} but variant only has {}",
727 PlaceTy::from_ty(fty)
732 fn error(&mut self) -> Ty<'tcx> {
733 self.errors_reported = true;
739 parent: &dyn fmt::Debug,
740 base_ty: PlaceTy<'tcx>,
743 ) -> Result<Ty<'tcx>, FieldAccessError> {
744 let tcx = self.tcx();
746 let (variant, substs) = match base_ty {
747 PlaceTy { ty, variant_index: Some(variant_index) } => {
749 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
750 _ => bug!("can't have downcast of non-adt type"),
753 PlaceTy { ty, variant_index: None } => match ty.sty {
754 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
755 (&adt_def.variants[VariantIdx::new(0)], substs),
756 ty::Closure(def_id, substs) => {
757 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
759 None => Err(FieldAccessError::OutOfRange {
760 field_count: substs.upvar_tys(def_id, tcx).count(),
764 ty::Generator(def_id, substs, _) => {
765 // Try pre-transform fields first (upvars and current state)
766 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
770 // Then try `field_tys` which contains all the fields, but it
771 // requires the final optimized MIR.
772 return match substs.field_tys(def_id, tcx).nth(field.index()) {
774 None => Err(FieldAccessError::OutOfRange {
775 field_count: substs.field_tys(def_id, tcx).count(),
780 return match tys.get(field.index()) {
782 None => Err(FieldAccessError::OutOfRange {
783 field_count: tys.len(),
788 return Ok(span_mirbug_and_err!(
791 "can't project out of {:?}",
798 if let Some(field) = variant.fields.get(field.index()) {
799 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
801 Err(FieldAccessError::OutOfRange {
802 field_count: variant.fields.len(),
808 /// The MIR type checker. Visits the MIR and enforces all the
809 /// constraints needed for it to be valid and well-typed. Along the
810 /// way, it accrues region constraints -- these can later be used by
811 /// NLL region checking.
812 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
813 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
814 param_env: ty::ParamEnv<'gcx>,
816 /// User type annotations are shared between the main MIR and the MIR of
817 /// all of the promoted items.
818 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
820 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
821 implicit_region_bound: Option<ty::Region<'tcx>>,
822 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
823 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
824 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
827 struct BorrowCheckContext<'a, 'tcx: 'a> {
828 universal_regions: &'a UniversalRegions<'tcx>,
829 location_table: &'a LocationTable,
830 all_facts: &'a mut Option<AllFacts>,
831 borrow_set: &'a BorrowSet<'tcx>,
832 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
835 crate struct MirTypeckResults<'tcx> {
836 crate constraints: MirTypeckRegionConstraints<'tcx>,
837 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
840 /// A collection of region constraints that must be satisfied for the
841 /// program to be considered well-typed.
842 crate struct MirTypeckRegionConstraints<'tcx> {
843 /// Maps from a `ty::Placeholder` to the corresponding
844 /// `PlaceholderIndex` bit that we will use for it.
846 /// To keep everything in sync, do not insert this set
847 /// directly. Instead, use the `placeholder_region` helper.
848 crate placeholder_indices: PlaceholderIndices,
850 /// Each time we add a placeholder to `placeholder_indices`, we
851 /// also create a corresponding "representative" region vid for
852 /// that wraps it. This vector tracks those. This way, when we
853 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
854 /// the same underlying `RegionVid`.
855 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
857 /// In general, the type-checker is not responsible for enforcing
858 /// liveness constraints; this job falls to the region inferencer,
859 /// which performs a liveness analysis. However, in some limited
860 /// cases, the MIR type-checker creates temporary regions that do
861 /// not otherwise appear in the MIR -- in particular, the
862 /// late-bound regions that it instantiates at call-sites -- and
863 /// hence it must report on their liveness constraints.
864 crate liveness_constraints: LivenessValues<RegionVid>,
866 crate outlives_constraints: ConstraintSet,
868 crate closure_bounds_mapping:
869 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
871 crate type_tests: Vec<TypeTest<'tcx>>,
874 impl MirTypeckRegionConstraints<'tcx> {
875 fn placeholder_region(
877 infcx: &InferCtxt<'_, '_, 'tcx>,
878 placeholder: ty::PlaceholderRegion,
879 ) -> ty::Region<'tcx> {
880 let placeholder_index = self.placeholder_indices.insert(placeholder);
881 match self.placeholder_index_to_region.get(placeholder_index) {
884 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
885 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
886 self.placeholder_index_to_region.push(region);
893 /// The `Locations` type summarizes *where* region constraints are
894 /// required to hold. Normally, this is at a particular point which
895 /// created the obligation, but for constraints that the user gave, we
896 /// want the constraint to hold at all points.
897 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
899 /// Indicates that a type constraint should always be true. This
900 /// is particularly important in the new borrowck analysis for
901 /// things like the type of the return slot. Consider this
905 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
907 /// return &y; // error
911 /// Here, we wind up with the signature from the return type being
912 /// something like `&'1 u32` where `'1` is a universal region. But
913 /// the type of the return slot `_0` is something like `&'2 u32`
914 /// where `'2` is an existential region variable. The type checker
915 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
916 /// older NLL analysis, we required this only at the entry point
917 /// to the function. By the nature of the constraints, this wound
918 /// up propagating to all points reachable from start (because
919 /// `'1` -- as a universal region -- is live everywhere). In the
920 /// newer analysis, though, this doesn't work: `_0` is considered
921 /// dead at the start (it has no usable value) and hence this type
922 /// equality is basically a no-op. Then, later on, when we do `_0
923 /// = &'3 y`, that region `'3` never winds up related to the
924 /// universal region `'1` and hence no error occurs. Therefore, we
925 /// use Locations::All instead, which ensures that the `'1` and
926 /// `'2` are equal everything. We also use this for other
927 /// user-given type annotations; e.g., if the user wrote `let mut
928 /// x: &'static u32 = ...`, we would ensure that all values
929 /// assigned to `x` are of `'static` lifetime.
931 /// The span points to the place the constraint arose. For example,
932 /// it points to the type in a user-given type annotation. If
933 /// there's no sensible span then it's DUMMY_SP.
936 /// An outlives constraint that only has to hold at a single location,
937 /// usually it represents a point where references flow from one spot to
938 /// another (e.g., `x = y`)
943 pub fn from_location(&self) -> Option<Location> {
945 Locations::All(_) => None,
946 Locations::Single(from_location) => Some(*from_location),
950 /// Gets a span representing the location.
951 pub fn span(&self, mir: &Mir<'_>) -> Span {
953 Locations::All(span) => *span,
954 Locations::Single(l) => mir.source_info(*l).span,
959 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
961 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
964 param_env: ty::ParamEnv<'gcx>,
965 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
966 implicit_region_bound: Option<ty::Region<'tcx>>,
967 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
968 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
970 let mut checker = Self {
974 user_type_annotations: &mir.user_type_annotations,
977 implicit_region_bound,
979 reported_errors: Default::default(),
980 universal_region_relations,
982 checker.check_user_type_annotations();
986 /// Equate the inferred type and the annotated type for user type annotations
987 fn check_user_type_annotations(&mut self) {
989 "check_user_type_annotations: user_type_annotations={:?}",
990 self.user_type_annotations
992 for user_annotation in self.user_type_annotations {
993 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
994 let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
998 UserType::Ty(mut ty) => {
999 ty = self.normalize(ty, Locations::All(span));
1001 if let Err(terr) = self.eq_types(
1004 Locations::All(span),
1005 ConstraintCategory::BoringNoLocation,
1010 "bad user type ({:?} = {:?}): {:?}",
1017 self.prove_predicate(
1018 ty::Predicate::WellFormed(inferred_ty),
1019 Locations::All(span),
1020 ConstraintCategory::TypeAnnotation,
1023 UserType::TypeOf(def_id, user_substs) => {
1024 if let Err(terr) = self.fully_perform_op(
1025 Locations::All(span),
1026 ConstraintCategory::BoringNoLocation,
1027 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1028 inferred_ty, def_id, user_substs,
1034 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1046 /// Given some operation `op` that manipulates types, proves
1047 /// predicates, or otherwise uses the inference context, executes
1048 /// `op` and then executes all the further obligations that `op`
1049 /// returns. This will yield a set of outlives constraints amongst
1050 /// regions which are extracted and stored as having occurred at
1053 /// **Any `rustc::infer` operations that might generate region
1054 /// constraints should occur within this method so that those
1055 /// constraints can be properly localized!**
1056 fn fully_perform_op<R>(
1058 locations: Locations,
1059 category: ConstraintCategory,
1060 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
1062 let (r, opt_data) = op.fully_perform(self.infcx)?;
1064 if let Some(data) = &opt_data {
1065 self.push_region_constraints(locations, category, data);
1071 fn push_region_constraints(
1073 locations: Locations,
1074 category: ConstraintCategory,
1075 data: &[QueryRegionConstraint<'tcx>],
1078 "push_region_constraints: constraints generated at {:?} are {:#?}",
1082 if let Some(ref mut borrowck_context) = self.borrowck_context {
1083 constraint_conversion::ConstraintConversion::new(
1085 borrowck_context.universal_regions,
1086 self.region_bound_pairs,
1087 self.implicit_region_bound,
1091 &mut borrowck_context.constraints,
1092 ).convert_all(&data);
1096 /// Convenient wrapper around `relate_tys::relate_types` -- see
1097 /// that fn for docs.
1103 locations: Locations,
1104 category: ConstraintCategory,
1106 relate_tys::relate_types(
1113 self.borrowck_context.as_mut().map(|x| &mut **x),
1121 locations: Locations,
1122 category: ConstraintCategory,
1124 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1127 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1128 /// variables in `sub` with their inferred definitions and try
1129 /// again. This is used for opaque types in places (e.g., `let x:
1130 /// impl Foo = ..`).
1131 fn sub_types_or_anon(
1135 locations: Locations,
1136 category: ConstraintCategory,
1138 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1139 if let ty::Opaque(..) = sup.sty {
1140 // When you have `let x: impl Foo = ...` in a closure,
1141 // the resulting inferend values are stored with the
1142 // def-id of the base function.
1143 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1144 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1156 locations: Locations,
1157 category: ConstraintCategory,
1159 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1162 fn relate_type_and_user_type(
1166 user_ty: &UserTypeProjection,
1167 locations: Locations,
1168 category: ConstraintCategory,
1171 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1172 a, v, user_ty, locations,
1175 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1176 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1178 let tcx = self.infcx.tcx;
1180 for proj in &user_ty.projs {
1181 let projected_ty = curr_projected_ty.projection_ty_core(tcx, proj, |this, field, &()| {
1182 let ty = this.field_ty(tcx, field);
1183 self.normalize(ty, locations)
1185 curr_projected_ty = projected_ty;
1187 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1188 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1190 let ty = curr_projected_ty.ty;
1191 self.relate_types(a, v, ty, locations, category)?;
1196 fn eq_opaque_type_and_type(
1198 revealed_ty: Ty<'tcx>,
1200 anon_owner_def_id: DefId,
1201 locations: Locations,
1202 category: ConstraintCategory,
1205 "eq_opaque_type_and_type( \
1208 revealed_ty, anon_ty
1210 let infcx = self.infcx;
1211 let tcx = infcx.tcx;
1212 let param_env = self.param_env;
1213 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1214 let opaque_type_map = self.fully_perform_op(
1219 let mut obligations = ObligationAccumulator::default();
1221 let dummy_body_id = ObligationCause::dummy().body_id;
1222 let (output_ty, opaque_type_map) =
1223 obligations.add(infcx.instantiate_opaque_types(
1230 "eq_opaque_type_and_type: \
1231 instantiated output_ty={:?} \
1232 opaque_type_map={:#?} \
1234 output_ty, opaque_type_map, revealed_ty
1236 obligations.add(infcx
1237 .at(&ObligationCause::dummy(), param_env)
1238 .eq(output_ty, revealed_ty)?);
1240 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1241 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1242 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1243 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1245 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1246 opaque_decl.concrete_ty,
1247 infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1250 obligations.add(infcx
1251 .at(&ObligationCause::dummy(), param_env)
1252 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1255 debug!("eq_opaque_type_and_type: equated");
1258 value: Some(opaque_type_map),
1259 obligations: obligations.into_vec(),
1262 || "input_output".to_string(),
1266 let universal_region_relations = match self.universal_region_relations {
1268 None => return Ok(()),
1271 // Finally, if we instantiated the anon types successfully, we
1272 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1273 // prove that `T: Iterator` where `T` is the type we
1274 // instantiated it with).
1275 if let Some(opaque_type_map) = opaque_type_map {
1276 for (opaque_def_id, opaque_decl) in opaque_type_map {
1277 self.fully_perform_op(
1279 ConstraintCategory::OpaqueType,
1282 infcx.constrain_opaque_type(
1285 universal_region_relations,
1289 obligations: vec![],
1292 || "opaque_type_map".to_string(),
1300 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1304 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1305 debug!("check_stmt: {:?}", stmt);
1306 let tcx = self.tcx();
1308 StatementKind::Assign(ref place, ref rv) => {
1309 // Assignments to temporaries are not "interesting";
1310 // they are not caused by the user, but rather artifacts
1311 // of lowering. Assignments to other sorts of places *are* interesting
1313 let category = match *place {
1314 Place::Base(PlaceBase::Local(RETURN_PLACE)) => if let Some(BorrowCheckContext {
1317 defining_ty: DefiningTy::Const(def_id, _),
1321 }) = self.borrowck_context
1323 if tcx.is_static(*def_id).is_some() {
1324 ConstraintCategory::UseAsStatic
1326 ConstraintCategory::UseAsConst
1329 ConstraintCategory::Return
1331 Place::Base(PlaceBase::Local(l))
1332 if !mir.local_decls[l].is_user_variable.is_some() => {
1333 ConstraintCategory::Boring
1335 _ => ConstraintCategory::Assignment,
1338 let place_ty = place.ty(mir, tcx).ty;
1339 let rv_ty = rv.ty(mir, tcx);
1341 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1346 "bad assignment ({:?} = {:?}): {:?}",
1353 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1354 if let Err(terr) = self.relate_type_and_user_type(
1356 ty::Variance::Invariant,
1357 &UserTypeProjection { base: annotation_index, projs: vec![], },
1358 location.to_locations(),
1359 ConstraintCategory::Boring,
1361 let annotation = &self.user_type_annotations[annotation_index];
1365 "bad user type on rvalue ({:?} = {:?}): {:?}",
1373 self.check_rvalue(mir, rv, location);
1374 if !self.tcx().features().unsized_locals {
1375 let trait_ref = ty::TraitRef {
1376 def_id: tcx.lang_items().sized_trait().unwrap(),
1377 substs: tcx.mk_substs_trait(place_ty, &[]),
1379 self.prove_trait_ref(
1381 location.to_locations(),
1382 ConstraintCategory::SizedBound,
1386 StatementKind::SetDiscriminant {
1390 let place_type = place.ty(mir, tcx).ty;
1391 let adt = match place_type.sty {
1392 ty::Adt(adt, _) if adt.is_enum() => adt,
1395 stmt.source_info.span,
1396 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1402 if variant_index.as_usize() >= adt.variants.len() {
1404 stmt.source_info.span,
1405 "bad set discriminant ({:?} = {:?}): value of of range",
1411 StatementKind::AscribeUserType(ref place, variance, box ref projection) => {
1412 let place_ty = place.ty(mir, tcx).ty;
1413 if let Err(terr) = self.relate_type_and_user_type(
1417 Locations::All(stmt.source_info.span),
1418 ConstraintCategory::TypeAnnotation,
1420 let annotation = &self.user_type_annotations[projection.base];
1424 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1432 StatementKind::FakeRead(..)
1433 | StatementKind::StorageLive(..)
1434 | StatementKind::StorageDead(..)
1435 | StatementKind::InlineAsm { .. }
1436 | StatementKind::Retag { .. }
1437 | StatementKind::Nop => {}
1441 fn check_terminator(
1444 term: &Terminator<'tcx>,
1445 term_location: Location,
1447 debug!("check_terminator: {:?}", term);
1448 let tcx = self.tcx();
1450 TerminatorKind::Goto { .. }
1451 | TerminatorKind::Resume
1452 | TerminatorKind::Abort
1453 | TerminatorKind::Return
1454 | TerminatorKind::GeneratorDrop
1455 | TerminatorKind::Unreachable
1456 | TerminatorKind::Drop { .. }
1457 | TerminatorKind::FalseEdges { .. }
1458 | TerminatorKind::FalseUnwind { .. } => {
1459 // no checks needed for these
1462 TerminatorKind::DropAndReplace {
1468 let place_ty = location.ty(mir, tcx).ty;
1469 let rv_ty = value.ty(mir, tcx);
1471 let locations = term_location.to_locations();
1473 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1478 "bad DropAndReplace ({:?} = {:?}): {:?}",
1485 TerminatorKind::SwitchInt {
1490 let discr_ty = discr.ty(mir, tcx);
1491 if let Err(terr) = self.sub_types(
1494 term_location.to_locations(),
1495 ConstraintCategory::Assignment,
1500 "bad SwitchInt ({:?} on {:?}): {:?}",
1506 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1507 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1509 // FIXME: check the values
1511 TerminatorKind::Call {
1518 let func_ty = func.ty(mir, tcx);
1519 debug!("check_terminator: call, func_ty={:?}", func_ty);
1520 let sig = match func_ty.sty {
1521 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1523 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1527 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1528 term.source_info.span,
1529 LateBoundRegionConversionTime::FnCall,
1532 let sig = self.normalize(sig, term_location);
1533 self.check_call_dest(mir, term, &sig, destination, term_location);
1535 self.prove_predicates(
1536 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1537 term_location.to_locations(),
1538 ConstraintCategory::Boring,
1541 // The ordinary liveness rules will ensure that all
1542 // regions in the type of the callee are live here. We
1543 // then further constrain the late-bound regions that
1544 // were instantiated at the call site to be live as
1545 // well. The resulting is that all the input (and
1546 // output) types in the signature must be live, since
1547 // all the inputs that fed into it were live.
1548 for &late_bound_region in map.values() {
1549 if let Some(ref mut borrowck_context) = self.borrowck_context {
1550 let region_vid = borrowck_context
1552 .to_region_vid(late_bound_region);
1555 .liveness_constraints
1556 .add_element(region_vid, term_location);
1560 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1562 TerminatorKind::Assert {
1563 ref cond, ref msg, ..
1565 let cond_ty = cond.ty(mir, tcx);
1566 if cond_ty != tcx.types.bool {
1567 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1570 if let BoundsCheck { ref len, ref index } = *msg {
1571 if len.ty(mir, tcx) != tcx.types.usize {
1572 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1574 if index.ty(mir, tcx) != tcx.types.usize {
1575 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1579 TerminatorKind::Yield { ref value, .. } => {
1580 let value_ty = value.ty(mir, tcx);
1581 match mir.yield_ty {
1582 None => span_mirbug!(self, term, "yield in non-generator"),
1584 if let Err(terr) = self.sub_types(
1587 term_location.to_locations(),
1588 ConstraintCategory::Yield,
1593 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1608 term: &Terminator<'tcx>,
1609 sig: &ty::FnSig<'tcx>,
1610 destination: &Option<(Place<'tcx>, BasicBlock)>,
1611 term_location: Location,
1613 let tcx = self.tcx();
1614 match *destination {
1615 Some((ref dest, _target_block)) => {
1616 let dest_ty = dest.ty(mir, tcx).ty;
1617 let category = match *dest {
1618 Place::Base(PlaceBase::Local(RETURN_PLACE)) => {
1619 if let Some(BorrowCheckContext {
1622 defining_ty: DefiningTy::Const(def_id, _),
1626 }) = self.borrowck_context
1628 if tcx.is_static(*def_id).is_some() {
1629 ConstraintCategory::UseAsStatic
1631 ConstraintCategory::UseAsConst
1634 ConstraintCategory::Return
1637 Place::Base(PlaceBase::Local(l))
1638 if !mir.local_decls[l].is_user_variable.is_some() => {
1639 ConstraintCategory::Boring
1641 _ => ConstraintCategory::Assignment,
1644 let locations = term_location.to_locations();
1647 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1652 "call dest mismatch ({:?} <- {:?}): {:?}",
1659 // When `#![feature(unsized_locals)]` is not enabled,
1660 // this check is done at `check_local`.
1661 if self.tcx().features().unsized_locals {
1662 let span = term.source_info.span;
1663 self.ensure_place_sized(dest_ty, span);
1667 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1668 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1674 fn check_call_inputs(
1677 term: &Terminator<'tcx>,
1678 sig: &ty::FnSig<'tcx>,
1679 args: &[Operand<'tcx>],
1680 term_location: Location,
1681 from_hir_call: bool,
1683 debug!("check_call_inputs({:?}, {:?})", sig, args);
1684 // Do not count the `VaList` argument as a "true" argument to
1685 // a C-variadic function.
1686 let inputs = if sig.c_variadic {
1687 &sig.inputs()[..sig.inputs().len() - 1]
1691 if args.len() < inputs.len() || (args.len() > inputs.len() && !sig.c_variadic) {
1692 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1694 for (n, (fn_arg, op_arg)) in inputs.iter().zip(args).enumerate() {
1695 let op_arg_ty = op_arg.ty(mir, self.tcx());
1696 let category = if from_hir_call {
1697 ConstraintCategory::CallArgument
1699 ConstraintCategory::Boring
1702 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1707 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1717 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1718 let is_cleanup = block_data.is_cleanup;
1719 self.last_span = block_data.terminator().source_info.span;
1720 match block_data.terminator().kind {
1721 TerminatorKind::Goto { target } => {
1722 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1724 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1725 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1727 TerminatorKind::Resume => if !is_cleanup {
1728 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1730 TerminatorKind::Abort => if !is_cleanup {
1731 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1733 TerminatorKind::Return => if is_cleanup {
1734 span_mirbug!(self, block_data, "return on cleanup block")
1736 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1737 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1739 TerminatorKind::Yield { resume, drop, .. } => {
1741 span_mirbug!(self, block_data, "yield in cleanup block")
1743 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1744 if let Some(drop) = drop {
1745 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1748 TerminatorKind::Unreachable => {}
1749 TerminatorKind::Drop { target, unwind, .. }
1750 | TerminatorKind::DropAndReplace { target, unwind, .. }
1751 | TerminatorKind::Assert {
1756 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1757 if let Some(unwind) = unwind {
1759 span_mirbug!(self, block_data, "unwind on cleanup block")
1761 self.assert_iscleanup(mir, block_data, unwind, true);
1764 TerminatorKind::Call {
1769 if let &Some((_, target)) = destination {
1770 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1772 if let Some(cleanup) = cleanup {
1774 span_mirbug!(self, block_data, "cleanup on cleanup block")
1776 self.assert_iscleanup(mir, block_data, cleanup, true);
1779 TerminatorKind::FalseEdges {
1781 ref imaginary_targets,
1783 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1784 for target in imaginary_targets {
1785 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1788 TerminatorKind::FalseUnwind {
1792 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1793 if let Some(unwind) = unwind {
1798 "cleanup in cleanup block via false unwind"
1801 self.assert_iscleanup(mir, block_data, unwind, true);
1807 fn assert_iscleanup(
1810 ctxt: &dyn fmt::Debug,
1814 if mir[bb].is_cleanup != iscleanuppad {
1818 "cleanuppad mismatch: {:?} should be {:?}",
1825 fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1826 match mir.local_kind(local) {
1827 LocalKind::ReturnPointer | LocalKind::Arg => {
1828 // return values of normal functions are required to be
1829 // sized by typeck, but return values of ADT constructors are
1830 // not because we don't include a `Self: Sized` bounds on them.
1832 // Unbound parts of arguments were never required to be Sized
1833 // - maybe we should make that a warning.
1836 LocalKind::Var | LocalKind::Temp => {}
1839 // When `#![feature(unsized_locals)]` is enabled, only function calls
1840 // and nullary ops are checked in `check_call_dest`.
1841 if !self.tcx().features().unsized_locals {
1842 let span = local_decl.source_info.span;
1843 let ty = local_decl.ty;
1844 self.ensure_place_sized(ty, span);
1848 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1849 let tcx = self.tcx();
1851 // Erase the regions from `ty` to get a global type. The
1852 // `Sized` bound in no way depends on precise regions, so this
1853 // shouldn't affect `is_sized`.
1854 let gcx = tcx.global_tcx();
1855 let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1856 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1857 // in current MIR construction, all non-control-flow rvalue
1858 // expressions evaluate through `as_temp` or `into` a return
1859 // slot or local, so to find all unsized rvalues it is enough
1860 // to check all temps, return slots and locals.
1861 if let None = self.reported_errors.replace((ty, span)) {
1862 let mut diag = struct_span_err!(
1866 "cannot move a value of type {0}: the size of {0} \
1867 cannot be statically determined",
1871 // While this is located in `nll::typeck` this error is not
1872 // an NLL error, it's a required check to prevent creation
1873 // of unsized rvalues in certain cases:
1874 // * operand of a box expression
1875 // * callee in a call expression
1881 fn aggregate_field_ty(
1883 ak: &AggregateKind<'tcx>,
1886 ) -> Result<Ty<'tcx>, FieldAccessError> {
1887 let tcx = self.tcx();
1890 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1891 let variant = &def.variants[variant_index];
1892 let adj_field_index = active_field_index.unwrap_or(field_index);
1893 if let Some(field) = variant.fields.get(adj_field_index) {
1894 Ok(self.normalize(field.ty(tcx, substs), location))
1896 Err(FieldAccessError::OutOfRange {
1897 field_count: variant.fields.len(),
1901 AggregateKind::Closure(def_id, substs) => {
1902 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1904 None => Err(FieldAccessError::OutOfRange {
1905 field_count: substs.upvar_tys(def_id, tcx).count(),
1909 AggregateKind::Generator(def_id, substs, _) => {
1910 // Try pre-transform fields first (upvars and current state)
1911 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1914 // Then try `field_tys` which contains all the fields, but it
1915 // requires the final optimized MIR.
1916 match substs.field_tys(def_id, tcx).nth(field_index) {
1918 None => Err(FieldAccessError::OutOfRange {
1919 field_count: substs.field_tys(def_id, tcx).count(),
1924 AggregateKind::Array(ty) => Ok(ty),
1925 AggregateKind::Tuple => {
1926 unreachable!("This should have been covered in check_rvalues");
1931 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1932 let tcx = self.tcx();
1935 Rvalue::Aggregate(ak, ops) => {
1936 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1939 Rvalue::Repeat(operand, len) => if *len > 1 {
1940 let operand_ty = operand.ty(mir, tcx);
1942 let trait_ref = ty::TraitRef {
1943 def_id: tcx.lang_items().copy_trait().unwrap(),
1944 substs: tcx.mk_substs_trait(operand_ty, &[]),
1947 self.prove_trait_ref(
1949 location.to_locations(),
1950 ConstraintCategory::CopyBound,
1954 Rvalue::NullaryOp(_, ty) => {
1955 // Even with unsized locals cannot box an unsized value.
1956 if self.tcx().features().unsized_locals {
1957 let span = mir.source_info(location).span;
1958 self.ensure_place_sized(ty, span);
1961 let trait_ref = ty::TraitRef {
1962 def_id: tcx.lang_items().sized_trait().unwrap(),
1963 substs: tcx.mk_substs_trait(ty, &[]),
1966 self.prove_trait_ref(
1968 location.to_locations(),
1969 ConstraintCategory::SizedBound,
1973 Rvalue::Cast(cast_kind, op, ty) => {
1975 CastKind::ReifyFnPointer => {
1976 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1978 // The type that we see in the fcx is like
1979 // `foo::<'a, 'b>`, where `foo` is the path to a
1980 // function definition. When we extract the
1981 // signature, it comes from the `fn_sig` query,
1982 // and hence may contain unnormalized results.
1983 let fn_sig = self.normalize(fn_sig, location);
1985 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1987 if let Err(terr) = self.eq_types(
1990 location.to_locations(),
1991 ConstraintCategory::Cast,
1996 "equating {:?} with {:?} yields {:?}",
2004 CastKind::ClosureFnPointer(unsafety) => {
2005 let sig = match op.ty(mir, tcx).sty {
2006 ty::Closure(def_id, substs) => {
2007 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
2011 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2013 if let Err(terr) = self.eq_types(
2016 location.to_locations(),
2017 ConstraintCategory::Cast,
2022 "equating {:?} with {:?} yields {:?}",
2030 CastKind::UnsafeFnPointer => {
2031 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
2033 // The type that we see in the fcx is like
2034 // `foo::<'a, 'b>`, where `foo` is the path to a
2035 // function definition. When we extract the
2036 // signature, it comes from the `fn_sig` query,
2037 // and hence may contain unnormalized results.
2038 let fn_sig = self.normalize(fn_sig, location);
2040 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2042 if let Err(terr) = self.eq_types(
2045 location.to_locations(),
2046 ConstraintCategory::Cast,
2051 "equating {:?} with {:?} yields {:?}",
2059 CastKind::Unsize => {
2061 let trait_ref = ty::TraitRef {
2062 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2063 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
2066 self.prove_trait_ref(
2068 location.to_locations(),
2069 ConstraintCategory::Cast,
2073 CastKind::MutToConstPointer => {
2074 let ty_from = match op.ty(mir, tcx).sty {
2075 ty::RawPtr(ty::TypeAndMut {
2077 mutbl: hir::MutMutable,
2083 "unexpected base type for cast {:?}",
2089 let ty_to = match ty.sty {
2090 ty::RawPtr(ty::TypeAndMut {
2092 mutbl: hir::MutImmutable,
2098 "unexpected target type for cast {:?}",
2104 if let Err(terr) = self.sub_types(
2107 location.to_locations(),
2108 ConstraintCategory::Cast,
2113 "relating {:?} with {:?} yields {:?}",
2122 if let ty::Ref(_, mut ty_from, _) = op.ty(mir, tcx).sty {
2123 let (mut ty_to, mutability) = if let ty::RawPtr(ty::TypeAndMut {
2132 "invalid cast types {:?} -> {:?}",
2139 // Handle the direct cast from `&[T; N]` to `*const T` by unwrapping
2140 // any array we find.
2141 while let ty::Array(ty_elem_from, _) = ty_from.sty {
2142 ty_from = ty_elem_from;
2143 if let ty::Array(ty_elem_to, _) = ty_to.sty {
2150 if let hir::MutMutable = mutability {
2151 if let Err(terr) = self.eq_types(
2154 location.to_locations(),
2155 ConstraintCategory::Cast,
2160 "equating {:?} with {:?} yields {:?}",
2167 if let Err(terr) = self.sub_types(
2170 location.to_locations(),
2171 ConstraintCategory::Cast,
2176 "relating {:?} with {:?} yields {:?}",
2188 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2189 self.add_reborrow_constraint(mir, location, region, borrowed_place);
2192 Rvalue::BinaryOp(BinOp::Eq, left, right)
2193 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2194 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2195 | Rvalue::BinaryOp(BinOp::Le, left, right)
2196 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2197 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2198 let ty_left = left.ty(mir, tcx);
2199 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.sty {
2200 let ty_right = right.ty(mir, tcx);
2201 let common_ty = self.infcx.next_ty_var(
2202 TypeVariableOrigin::MiscVariable(mir.source_info(location).span),
2207 location.to_locations(),
2208 ConstraintCategory::Boring
2209 ).unwrap_or_else(|err| {
2210 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2212 if let Err(terr) = self.sub_types(
2215 location.to_locations(),
2216 ConstraintCategory::Boring
2221 "unexpected comparison types {:?} and {:?} yields {:?}",
2232 | Rvalue::BinaryOp(..)
2233 | Rvalue::CheckedBinaryOp(..)
2234 | Rvalue::UnaryOp(..)
2235 | Rvalue::Discriminant(..) => {}
2239 /// If this rvalue supports a user-given type annotation, then
2240 /// extract and return it. This represents the final type of the
2241 /// rvalue and will be unified with the inferred type.
2242 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2245 | Rvalue::Repeat(..)
2249 | Rvalue::BinaryOp(..)
2250 | Rvalue::CheckedBinaryOp(..)
2251 | Rvalue::NullaryOp(..)
2252 | Rvalue::UnaryOp(..)
2253 | Rvalue::Discriminant(..) => None,
2255 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2256 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2257 AggregateKind::Array(_) => None,
2258 AggregateKind::Tuple => None,
2259 AggregateKind::Closure(_, _) => None,
2260 AggregateKind::Generator(_, _, _) => None,
2265 fn check_aggregate_rvalue(
2268 rvalue: &Rvalue<'tcx>,
2269 aggregate_kind: &AggregateKind<'tcx>,
2270 operands: &[Operand<'tcx>],
2273 let tcx = self.tcx();
2275 self.prove_aggregate_predicates(aggregate_kind, location);
2277 if *aggregate_kind == AggregateKind::Tuple {
2278 // tuple rvalue field type is always the type of the op. Nothing to check here.
2282 for (i, operand) in operands.iter().enumerate() {
2283 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2284 Ok(field_ty) => field_ty,
2285 Err(FieldAccessError::OutOfRange { field_count }) => {
2289 "accessed field #{} but variant only has {}",
2296 let operand_ty = operand.ty(mir, tcx);
2298 if let Err(terr) = self.sub_types(
2301 location.to_locations(),
2302 ConstraintCategory::Boring,
2307 "{:?} is not a subtype of {:?}: {:?}",
2316 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2320 /// - `location`: the location `L` where the borrow expression occurs
2321 /// - `borrow_region`: the region `'a` associated with the borrow
2322 /// - `borrowed_place`: the place `P` being borrowed
2323 fn add_reborrow_constraint(
2327 borrow_region: ty::Region<'tcx>,
2328 borrowed_place: &Place<'tcx>,
2330 // These constraints are only meaningful during borrowck:
2331 let BorrowCheckContext {
2337 } = match self.borrowck_context {
2338 Some(ref mut borrowck_context) => borrowck_context,
2342 // In Polonius mode, we also push a `borrow_region` fact
2343 // linking the loan to the region (in some cases, though,
2344 // there is no loan associated with this borrow expression --
2345 // that occurs when we are borrowing an unsafe place, for
2347 if let Some(all_facts) = all_facts {
2348 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2349 let region_vid = borrow_region.to_region_vid();
2350 all_facts.borrow_region.push((
2353 location_table.mid_index(location),
2358 // If we are reborrowing the referent of another reference, we
2359 // need to add outlives relationships. In a case like `&mut
2360 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2361 // need to ensure that `'b: 'a`.
2363 let mut borrowed_place = borrowed_place;
2366 "add_reborrow_constraint({:?}, {:?}, {:?})",
2367 location, borrow_region, borrowed_place
2369 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2370 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2373 ProjectionElem::Deref => {
2374 let tcx = self.infcx.tcx;
2375 let base_ty = base.ty(mir, tcx).ty;
2377 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2379 ty::Ref(ref_region, _, mutbl) => {
2380 constraints.outlives_constraints.push(OutlivesConstraint {
2381 sup: ref_region.to_region_vid(),
2382 sub: borrow_region.to_region_vid(),
2383 locations: location.to_locations(),
2384 category: ConstraintCategory::Boring,
2388 hir::Mutability::MutImmutable => {
2389 // Immutable reference. We don't need the base
2390 // to be valid for the entire lifetime of
2394 hir::Mutability::MutMutable => {
2395 // Mutable reference. We *do* need the base
2396 // to be valid, because after the base becomes
2397 // invalid, someone else can use our mutable deref.
2399 // This is in order to make the following function
2402 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2407 // As otherwise you could clone `&mut T` using the
2408 // following function:
2410 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2411 // let my_clone = unsafe_deref(&'a x);
2420 // deref of raw pointer, guaranteed to be valid
2423 ty::Adt(def, _) if def.is_box() => {
2424 // deref of `Box`, need the base to be valid - propagate
2426 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2429 ProjectionElem::Field(..)
2430 | ProjectionElem::Downcast(..)
2431 | ProjectionElem::Index(..)
2432 | ProjectionElem::ConstantIndex { .. }
2433 | ProjectionElem::Subslice { .. } => {
2434 // other field access
2438 // The "propagate" case. We need to check that our base is valid
2439 // for the borrow's lifetime.
2440 borrowed_place = base;
2444 fn prove_aggregate_predicates(
2446 aggregate_kind: &AggregateKind<'tcx>,
2449 let tcx = self.tcx();
2452 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2453 aggregate_kind, location
2456 let instantiated_predicates = match aggregate_kind {
2457 AggregateKind::Adt(def, _, substs, _, _) => {
2458 tcx.predicates_of(def.did).instantiate(tcx, substs)
2461 // For closures, we have some **extra requirements** we
2463 // have to check. In particular, in their upvars and
2464 // signatures, closures often reference various regions
2465 // from the surrounding function -- we call those the
2466 // closure's free regions. When we borrow-check (and hence
2467 // region-check) closures, we may find that the closure
2468 // requires certain relationships between those free
2469 // regions. However, because those free regions refer to
2470 // portions of the CFG of their caller, the closure is not
2471 // in a position to verify those relationships. In that
2472 // case, the requirements get "propagated" to us, and so
2473 // we have to solve them here where we instantiate the
2476 // Despite the opacity of the previous parapgrah, this is
2477 // actually relatively easy to understand in terms of the
2478 // desugaring. A closure gets desugared to a struct, and
2479 // these extra requirements are basically like where
2480 // clauses on the struct.
2481 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2482 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2483 self.prove_closure_bounds(tcx, *def_id, substs, location)
2486 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2489 self.normalize_and_prove_instantiated_predicates(
2490 instantiated_predicates,
2491 location.to_locations(),
2495 fn prove_closure_bounds(
2497 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2499 substs: SubstsRef<'tcx>,
2501 ) -> ty::InstantiatedPredicates<'tcx> {
2502 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2503 let closure_constraints =
2504 closure_region_requirements.apply_requirements(tcx, def_id, substs);
2506 if let Some(ref mut borrowck_context) = self.borrowck_context {
2507 let bounds_mapping = closure_constraints
2510 .filter_map(|(idx, constraint)| {
2511 let ty::OutlivesPredicate(k1, r2) =
2512 constraint.no_bound_vars().unwrap_or_else(|| {
2513 bug!("query_constraint {:?} contained bound vars", constraint,);
2517 UnpackedKind::Lifetime(r1) => {
2518 // constraint is r1: r2
2519 let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
2520 let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
2521 let outlives_requirements =
2522 &closure_region_requirements.outlives_requirements[idx];
2526 outlives_requirements.category,
2527 outlives_requirements.blame_span,
2531 UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2536 let existing = borrowck_context
2538 .closure_bounds_mapping
2539 .insert(location, bounds_mapping);
2542 "Multiple closures at the same location."
2546 self.push_region_constraints(
2547 location.to_locations(),
2548 ConstraintCategory::ClosureBounds,
2549 &closure_constraints,
2553 tcx.predicates_of(def_id).instantiate(tcx, substs)
2558 trait_ref: ty::TraitRef<'tcx>,
2559 locations: Locations,
2560 category: ConstraintCategory,
2562 self.prove_predicates(
2563 Some(ty::Predicate::Trait(
2564 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2571 fn normalize_and_prove_instantiated_predicates(
2573 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2574 locations: Locations,
2576 for predicate in instantiated_predicates.predicates {
2577 let predicate = self.normalize(predicate, locations);
2578 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2582 fn prove_predicates(
2584 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2585 locations: Locations,
2586 category: ConstraintCategory,
2588 for predicate in predicates {
2590 "prove_predicates(predicate={:?}, locations={:?})",
2591 predicate, locations,
2594 self.prove_predicate(predicate, locations, category);
2600 predicate: ty::Predicate<'tcx>,
2601 locations: Locations,
2602 category: ConstraintCategory,
2605 "prove_predicate(predicate={:?}, location={:?})",
2606 predicate, locations,
2609 let param_env = self.param_env;
2610 self.fully_perform_op(
2613 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2614 ).unwrap_or_else(|NoSolution| {
2615 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2619 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2620 self.last_span = mir.span;
2621 debug!("run_on_mir: {:?}", mir.span);
2623 for (local, local_decl) in mir.local_decls.iter_enumerated() {
2624 self.check_local(mir, local, local_decl);
2627 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2628 let mut location = Location {
2632 for stmt in &block_data.statements {
2633 if !stmt.source_info.span.is_dummy() {
2634 self.last_span = stmt.source_info.span;
2636 self.check_stmt(mir, stmt, location);
2637 location.statement_index += 1;
2640 self.check_terminator(mir, block_data.terminator(), location);
2641 self.check_iscleanup(mir, block_data);
2645 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2647 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2649 debug!("normalize(value={:?}, location={:?})", value, location);
2650 let param_env = self.param_env;
2651 self.fully_perform_op(
2652 location.to_locations(),
2653 ConstraintCategory::Boring,
2654 param_env.and(type_op::normalize::Normalize::new(value)),
2655 ).unwrap_or_else(|NoSolution| {
2656 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2662 pub struct TypeckMir;
2664 impl MirPass for TypeckMir {
2665 fn run_pass<'a, 'tcx>(
2667 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2668 src: MirSource<'tcx>,
2669 mir: &mut Mir<'tcx>,
2671 let def_id = src.def_id();
2672 debug!("run_pass: {:?}", def_id);
2674 // When NLL is enabled, the borrow checker runs the typeck
2675 // itself, so we don't need this MIR pass anymore.
2676 if tcx.use_mir_borrowck() {
2680 if tcx.sess.err_count() > 0 {
2681 // compiling a broken program can obviously result in a
2682 // broken MIR, so try not to report duplicate errors.
2686 if tcx.is_constructor(def_id) {
2687 // We just assume that the automatically generated struct/variant constructors are
2688 // correct. See the comment in the `mir_borrowck` implementation for an
2689 // explanation why we need this.
2693 let param_env = tcx.param_env(def_id);
2694 tcx.infer_ctxt().enter(|infcx| {
2695 type_check_internal(
2707 // For verification purposes, we just ignore the resulting
2708 // region constraint sets. Not our problem. =)
2713 trait NormalizeLocation: fmt::Debug + Copy {
2714 fn to_locations(self) -> Locations;
2717 impl NormalizeLocation for Locations {
2718 fn to_locations(self) -> Locations {
2723 impl NormalizeLocation for Location {
2724 fn to_locations(self) -> Locations {
2725 Locations::Single(self)
2729 #[derive(Debug, Default)]
2730 struct ObligationAccumulator<'tcx> {
2731 obligations: PredicateObligations<'tcx>,
2734 impl<'tcx> ObligationAccumulator<'tcx> {
2735 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2736 let InferOk { value, obligations } = value;
2737 self.obligations.extend(obligations);
2741 fn into_vec(self) -> PredicateObligations<'tcx> {