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;
25 use rustc::hir::def_id::DefId;
26 use rustc::infer::canonical::QueryRegionConstraint;
27 use rustc::infer::outlives::env::RegionBoundPairs;
28 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
29 use rustc::infer::type_variable::TypeVariableOrigin;
30 use rustc::mir::interpret::{InterpError::BoundsCheck, ConstValue};
31 use rustc::mir::tcx::PlaceTy;
32 use rustc::mir::visit::{PlaceContext, Visitor, NonMutatingUseContext};
34 use rustc::traits::query::type_op;
35 use rustc::traits::query::type_op::custom::CustomTypeOp;
36 use rustc::traits::query::{Fallible, NoSolution};
37 use rustc::traits::{ObligationCause, PredicateObligations};
38 use rustc::ty::adjustment::{PointerCast};
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 implicit_region_bound,
162 &mut borrowck_context,
163 &universal_region_relations,
165 cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
166 liveness::generate(&mut cx, mir, elements, flow_inits, move_data, location_table);
168 translate_outlives_facts(cx.borrowck_context);
174 universal_region_relations,
178 fn type_check_internal<'a, 'gcx, 'tcx, R>(
179 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
181 param_env: ty::ParamEnv<'gcx>,
183 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
184 implicit_region_bound: ty::Region<'tcx>,
185 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
186 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
187 mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
189 let mut checker = TypeChecker::new(
195 implicit_region_bound,
197 universal_region_relations,
199 let errors_reported = {
200 let mut verifier = TypeVerifier::new(&mut checker, mir);
201 verifier.visit_mir(mir);
202 verifier.errors_reported
205 if !errors_reported {
206 // if verifier failed, don't do further checks to avoid ICEs
207 checker.typeck_mir(mir);
213 fn translate_outlives_facts(cx: &mut BorrowCheckContext<'_, '_>) {
214 if let Some(facts) = cx.all_facts {
215 let location_table = cx.location_table;
218 .extend(cx.constraints.outlives_constraints.iter().flat_map(
219 |constraint: &OutlivesConstraint| {
220 if let Some(from_location) = constraint.locations.from_location() {
221 Either::Left(iter::once((
224 location_table.mid_index(from_location),
230 .map(move |location| (constraint.sup, constraint.sub, location)),
238 fn mirbug(tcx: TyCtxt<'_, '_, '_>, span: Span, msg: &str) {
239 // We sometimes see MIR failures (notably predicate failures) due to
240 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
241 // to avoid reporting bugs in those cases.
242 tcx.sess.diagnostic().delay_span_bug(span, msg);
245 enum FieldAccessError {
246 OutOfRange { field_count: usize },
249 /// Verifies that MIR types are sane to not crash further checks.
251 /// The sanitize_XYZ methods here take an MIR object and compute its
252 /// type, calling `span_mirbug` and returning an error type if there
254 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
255 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
259 errors_reported: bool,
262 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
263 fn visit_span(&mut self, span: &Span) {
264 if !span.is_dummy() {
265 self.last_span = *span;
269 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
270 self.sanitize_place(place, location, context);
273 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
274 self.super_constant(constant, location);
275 self.sanitize_constant(constant, location);
276 self.sanitize_type(constant, constant.ty);
278 if let Some(annotation_index) = constant.user_ty {
279 if let Err(terr) = self.cx.relate_type_and_user_type(
281 ty::Variance::Invariant,
282 &UserTypeProjection { base: annotation_index, projs: vec![], },
283 location.to_locations(),
284 ConstraintCategory::Boring,
286 let annotation = &self.cx.user_type_annotations[annotation_index];
290 "bad constant user type {:?} vs {:?}: {:?}",
297 if let ConstValue::Unevaluated(def_id, substs) = constant.literal.val {
298 if let Err(terr) = self.cx.fully_perform_op(
299 location.to_locations(),
300 ConstraintCategory::Boring,
301 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
302 constant.ty, def_id, UserSubsts { substs, user_self_ty: None },
308 "bad constant type {:?} ({:?})",
314 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
315 let tcx = self.tcx();
317 let instantiated_predicates = tcx
318 .predicates_of(def_id)
319 .instantiate(tcx, substs);
320 self.cx.normalize_and_prove_instantiated_predicates(
321 instantiated_predicates,
322 location.to_locations(),
328 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
329 self.super_rvalue(rvalue, location);
330 let rval_ty = rvalue.ty(self.mir, self.tcx());
331 self.sanitize_type(rvalue, rval_ty);
334 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
335 self.super_local_decl(local, local_decl);
336 self.sanitize_type(local_decl, local_decl.ty);
338 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
339 let ty = if !local_decl.is_nonref_binding() {
340 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
341 // reference so we can check the type annotation for the remaining type.
342 if let ty::Ref(_, rty, _) = local_decl.ty.sty {
345 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
351 if let Err(terr) = self.cx.relate_type_and_user_type(
353 ty::Variance::Invariant,
355 Locations::All(*span),
356 ConstraintCategory::TypeAnnotation,
361 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
371 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
372 self.sanitize_type(&"return type", mir.return_ty());
373 for local_decl in &mir.local_decls {
374 self.sanitize_type(local_decl, local_decl.ty);
376 if self.errors_reported {
383 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
384 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'b Mir<'tcx>) -> Self {
387 mir_def_id: cx.mir_def_id,
390 errors_reported: false,
394 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
398 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
399 if ty.has_escaping_bound_vars() || ty.references_error() {
400 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
406 /// Checks that the constant's `ty` field matches up with what would be
407 /// expected from its literal. Unevaluated constants and well-formed
408 /// constraints are checked by `visit_constant`.
409 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
411 "sanitize_constant(constant={:?}, location={:?})",
415 let literal = constant.literal;
417 if let ConstValue::Unevaluated(..) = literal.val {
421 debug!("sanitize_constant: expected_ty={:?}", literal.ty);
423 if let Err(terr) = self.cx.eq_types(
426 location.to_locations(),
427 ConstraintCategory::Boring,
432 "constant {:?} should have type {:?} but has {:?} ({:?})",
441 /// Checks that the types internal to the `place` match up with
442 /// what would be expected.
447 context: PlaceContext,
449 debug!("sanitize_place: {:?}", place);
451 place.iterate(|place_base, place_projection| {
452 let mut place_ty = match place_base {
453 PlaceBase::Local(index) =>
454 PlaceTy::from_ty(self.mir.local_decls[*index].ty),
455 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)
499 // FIXME use place_projection.is_empty() when is available
500 if let Place::Base(_) = place {
501 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
502 let tcx = self.tcx();
503 let trait_ref = ty::TraitRef {
504 def_id: tcx.lang_items().copy_trait().unwrap(),
505 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
508 // In order to have a Copy operand, the type T of the
509 // value must be Copy. Note that we prove that T: Copy,
510 // rather than using the `is_copy_modulo_regions`
511 // test. This is important because
512 // `is_copy_modulo_regions` ignores the resulting region
513 // obligations and assumes they pass. This can result in
514 // bounds from Copy impls being unsoundly ignored (e.g.,
515 // #29149). Note that we decide to use Copy before knowing
516 // whether the bounds fully apply: in effect, the rule is
517 // that if a value of some type could implement Copy, then
519 self.cx.prove_trait_ref(
521 location.to_locations(),
522 ConstraintCategory::CopyBound,
527 for proj in place_projection {
528 if place_ty.variant_index.is_none() {
529 if place_ty.ty.references_error() {
530 assert!(self.errors_reported);
531 return PlaceTy::from_ty(self.tcx().types.err);
534 place_ty = self.sanitize_projection(place_ty, &proj.elem, place, location)
541 fn sanitize_promoted(&mut self, promoted_mir: &'b Mir<'tcx>, location: Location) {
542 // Determine the constraints from the promoted MIR by running the type
543 // checker on the promoted MIR, then transfer the constraints back to
544 // the main MIR, changing the locations to the provided location.
546 let parent_mir = mem::replace(&mut self.mir, promoted_mir);
548 let all_facts = &mut None;
549 let mut constraints = Default::default();
550 let mut closure_bounds = Default::default();
551 // Don't try to add borrow_region facts for the promoted MIR
552 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
554 // Use a new sets of constraints and closure bounds so that we can
555 // modify their locations.
557 &mut self.cx.borrowck_context.constraints.outlives_constraints,
561 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
565 self.visit_mir(promoted_mir);
567 if !self.errors_reported {
568 // if verifier failed, don't do further checks to avoid ICEs
569 self.cx.typeck_mir(promoted_mir);
572 self.mir = parent_mir;
573 // Merge the outlives constraints back in, at the given location.
574 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
576 &mut self.cx.borrowck_context.constraints.outlives_constraints,
580 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
584 let locations = location.to_locations();
585 for constraint in constraints.iter() {
586 let mut constraint = *constraint;
587 constraint.locations = locations;
588 if let ConstraintCategory::Return
589 | ConstraintCategory::UseAsConst
590 | ConstraintCategory::UseAsStatic = constraint.category
592 // "Returning" from a promoted is an assigment to a
593 // temporary from the user's point of view.
594 constraint.category = ConstraintCategory::Boring;
596 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
599 if !closure_bounds.is_empty() {
600 let combined_bounds_mapping = closure_bounds
602 .flat_map(|(_, value)| value)
604 let existing = self.cx.borrowck_context
606 .closure_bounds_mapping
607 .insert(location, combined_bounds_mapping);
610 "Multiple promoteds/closures at the same location."
615 fn sanitize_projection(
618 pi: &PlaceElem<'tcx>,
622 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
623 let tcx = self.tcx();
624 let base_ty = base.ty;
626 ProjectionElem::Deref => {
627 let deref_ty = base_ty.builtin_deref(true);
629 deref_ty.map(|t| t.ty).unwrap_or_else(|| {
630 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
634 ProjectionElem::Index(i) => {
635 let index_ty = Place::Base(PlaceBase::Local(i)).ty(self.mir, tcx).ty;
636 if index_ty != tcx.types.usize {
638 span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
642 base_ty.builtin_index().unwrap_or_else(|| {
643 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
648 ProjectionElem::ConstantIndex { .. } => {
649 // consider verifying in-bounds
651 base_ty.builtin_index().unwrap_or_else(|| {
652 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
656 ProjectionElem::Subslice { from, to } => PlaceTy::from_ty(
658 ty::Array(inner, size) => {
659 let size = size.unwrap_usize(tcx);
660 let min_size = (from as u64) + (to as u64);
661 if let Some(rest_size) = size.checked_sub(min_size) {
662 tcx.mk_array(inner, rest_size)
664 span_mirbug_and_err!(
667 "taking too-small slice of {:?}",
672 ty::Slice(..) => base_ty,
673 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
676 ProjectionElem::Downcast(maybe_name, index) => match base_ty.sty {
677 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
678 if index.as_usize() >= adt_def.variants.len() {
680 span_mirbug_and_err!(
683 "cast to variant #{:?} but enum only has {:?}",
685 adt_def.variants.len()
691 variant_index: Some(index),
695 // We do not need to handle generators here, because this runs
696 // before the generator transform stage.
698 let ty = if let Some(name) = maybe_name {
699 span_mirbug_and_err!(
702 "can't downcast {:?} as {:?}",
707 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
712 ProjectionElem::Field(field, fty) => {
713 let fty = self.sanitize_type(place, fty);
714 match self.field_ty(place, base, field, location) {
715 Ok(ty) => if let Err(terr) = self.cx.eq_types(
718 location.to_locations(),
719 ConstraintCategory::Boring,
724 "bad field access ({:?}: {:?}): {:?}",
730 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
733 "accessed field #{} but variant only has {}",
738 PlaceTy::from_ty(fty)
743 fn error(&mut self) -> Ty<'tcx> {
744 self.errors_reported = true;
750 parent: &dyn fmt::Debug,
751 base_ty: PlaceTy<'tcx>,
754 ) -> Result<Ty<'tcx>, FieldAccessError> {
755 let tcx = self.tcx();
757 let (variant, substs) = match base_ty {
758 PlaceTy { ty, variant_index: Some(variant_index) } => match ty.sty {
759 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
760 ty::Generator(def_id, substs, _) => {
761 let mut variants = substs.state_tys(def_id, tcx);
762 let mut variant = match variants.nth(variant_index.into()) {
765 bug!("variant_index of generator out of range: {:?}/{:?}",
767 substs.state_tys(def_id, tcx).count())
770 return match variant.nth(field.index()) {
772 None => Err(FieldAccessError::OutOfRange {
773 field_count: variant.count(),
777 _ => bug!("can't have downcast of non-adt non-generator type"),
779 PlaceTy { ty, variant_index: None } => match ty.sty {
780 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
781 (&adt_def.variants[VariantIdx::new(0)], substs),
782 ty::Closure(def_id, substs) => {
783 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
785 None => Err(FieldAccessError::OutOfRange {
786 field_count: substs.upvar_tys(def_id, tcx).count(),
790 ty::Generator(def_id, substs, _) => {
791 // Only prefix fields (upvars and current state) are
792 // accessible without a variant index.
793 return match substs.prefix_tys(def_id, tcx).nth(field.index()) {
795 None => Err(FieldAccessError::OutOfRange {
796 field_count: substs.prefix_tys(def_id, tcx).count(),
801 return match tys.get(field.index()) {
802 Some(&ty) => Ok(ty.expect_ty()),
803 None => Err(FieldAccessError::OutOfRange {
804 field_count: tys.len(),
809 return Ok(span_mirbug_and_err!(
812 "can't project out of {:?}",
819 if let Some(field) = variant.fields.get(field.index()) {
820 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
822 Err(FieldAccessError::OutOfRange {
823 field_count: variant.fields.len(),
829 /// The MIR type checker. Visits the MIR and enforces all the
830 /// constraints needed for it to be valid and well-typed. Along the
831 /// way, it accrues region constraints -- these can later be used by
832 /// NLL region checking.
833 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
834 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
835 param_env: ty::ParamEnv<'gcx>,
837 /// User type annotations are shared between the main MIR and the MIR of
838 /// all of the promoted items.
839 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
841 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
842 implicit_region_bound: ty::Region<'tcx>,
843 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
844 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
845 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
848 struct BorrowCheckContext<'a, 'tcx: 'a> {
849 universal_regions: &'a UniversalRegions<'tcx>,
850 location_table: &'a LocationTable,
851 all_facts: &'a mut Option<AllFacts>,
852 borrow_set: &'a BorrowSet<'tcx>,
853 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
856 crate struct MirTypeckResults<'tcx> {
857 crate constraints: MirTypeckRegionConstraints<'tcx>,
858 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
861 /// A collection of region constraints that must be satisfied for the
862 /// program to be considered well-typed.
863 crate struct MirTypeckRegionConstraints<'tcx> {
864 /// Maps from a `ty::Placeholder` to the corresponding
865 /// `PlaceholderIndex` bit that we will use for it.
867 /// To keep everything in sync, do not insert this set
868 /// directly. Instead, use the `placeholder_region` helper.
869 crate placeholder_indices: PlaceholderIndices,
871 /// Each time we add a placeholder to `placeholder_indices`, we
872 /// also create a corresponding "representative" region vid for
873 /// that wraps it. This vector tracks those. This way, when we
874 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
875 /// the same underlying `RegionVid`.
876 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
878 /// In general, the type-checker is not responsible for enforcing
879 /// liveness constraints; this job falls to the region inferencer,
880 /// which performs a liveness analysis. However, in some limited
881 /// cases, the MIR type-checker creates temporary regions that do
882 /// not otherwise appear in the MIR -- in particular, the
883 /// late-bound regions that it instantiates at call-sites -- and
884 /// hence it must report on their liveness constraints.
885 crate liveness_constraints: LivenessValues<RegionVid>,
887 crate outlives_constraints: ConstraintSet,
889 crate closure_bounds_mapping:
890 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
892 crate type_tests: Vec<TypeTest<'tcx>>,
895 impl MirTypeckRegionConstraints<'tcx> {
896 fn placeholder_region(
898 infcx: &InferCtxt<'_, '_, 'tcx>,
899 placeholder: ty::PlaceholderRegion,
900 ) -> ty::Region<'tcx> {
901 let placeholder_index = self.placeholder_indices.insert(placeholder);
902 match self.placeholder_index_to_region.get(placeholder_index) {
905 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
906 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
907 self.placeholder_index_to_region.push(region);
914 /// The `Locations` type summarizes *where* region constraints are
915 /// required to hold. Normally, this is at a particular point which
916 /// created the obligation, but for constraints that the user gave, we
917 /// want the constraint to hold at all points.
918 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
920 /// Indicates that a type constraint should always be true. This
921 /// is particularly important in the new borrowck analysis for
922 /// things like the type of the return slot. Consider this
926 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
928 /// return &y; // error
932 /// Here, we wind up with the signature from the return type being
933 /// something like `&'1 u32` where `'1` is a universal region. But
934 /// the type of the return slot `_0` is something like `&'2 u32`
935 /// where `'2` is an existential region variable. The type checker
936 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
937 /// older NLL analysis, we required this only at the entry point
938 /// to the function. By the nature of the constraints, this wound
939 /// up propagating to all points reachable from start (because
940 /// `'1` -- as a universal region -- is live everywhere). In the
941 /// newer analysis, though, this doesn't work: `_0` is considered
942 /// dead at the start (it has no usable value) and hence this type
943 /// equality is basically a no-op. Then, later on, when we do `_0
944 /// = &'3 y`, that region `'3` never winds up related to the
945 /// universal region `'1` and hence no error occurs. Therefore, we
946 /// use Locations::All instead, which ensures that the `'1` and
947 /// `'2` are equal everything. We also use this for other
948 /// user-given type annotations; e.g., if the user wrote `let mut
949 /// x: &'static u32 = ...`, we would ensure that all values
950 /// assigned to `x` are of `'static` lifetime.
952 /// The span points to the place the constraint arose. For example,
953 /// it points to the type in a user-given type annotation. If
954 /// there's no sensible span then it's DUMMY_SP.
957 /// An outlives constraint that only has to hold at a single location,
958 /// usually it represents a point where references flow from one spot to
959 /// another (e.g., `x = y`)
964 pub fn from_location(&self) -> Option<Location> {
966 Locations::All(_) => None,
967 Locations::Single(from_location) => Some(*from_location),
971 /// Gets a span representing the location.
972 pub fn span(&self, mir: &Mir<'_>) -> Span {
974 Locations::All(span) => *span,
975 Locations::Single(l) => mir.source_info(*l).span,
980 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
982 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
985 param_env: ty::ParamEnv<'gcx>,
986 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
987 implicit_region_bound: ty::Region<'tcx>,
988 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
989 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
991 let mut checker = Self {
995 user_type_annotations: &mir.user_type_annotations,
998 implicit_region_bound,
1000 reported_errors: Default::default(),
1001 universal_region_relations,
1003 checker.check_user_type_annotations();
1007 /// Equate the inferred type and the annotated type for user type annotations
1008 fn check_user_type_annotations(&mut self) {
1010 "check_user_type_annotations: user_type_annotations={:?}",
1011 self.user_type_annotations
1013 for user_annotation in self.user_type_annotations {
1014 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1015 let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
1019 UserType::Ty(mut ty) => {
1020 ty = self.normalize(ty, Locations::All(span));
1022 if let Err(terr) = self.eq_types(
1025 Locations::All(span),
1026 ConstraintCategory::BoringNoLocation,
1031 "bad user type ({:?} = {:?}): {:?}",
1038 self.prove_predicate(
1039 ty::Predicate::WellFormed(inferred_ty),
1040 Locations::All(span),
1041 ConstraintCategory::TypeAnnotation,
1044 UserType::TypeOf(def_id, user_substs) => {
1045 if let Err(terr) = self.fully_perform_op(
1046 Locations::All(span),
1047 ConstraintCategory::BoringNoLocation,
1048 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1049 inferred_ty, def_id, user_substs,
1055 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1067 /// Given some operation `op` that manipulates types, proves
1068 /// predicates, or otherwise uses the inference context, executes
1069 /// `op` and then executes all the further obligations that `op`
1070 /// returns. This will yield a set of outlives constraints amongst
1071 /// regions which are extracted and stored as having occurred at
1074 /// **Any `rustc::infer` operations that might generate region
1075 /// constraints should occur within this method so that those
1076 /// constraints can be properly localized!**
1077 fn fully_perform_op<R>(
1079 locations: Locations,
1080 category: ConstraintCategory,
1081 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
1083 let (r, opt_data) = op.fully_perform(self.infcx)?;
1085 if let Some(data) = &opt_data {
1086 self.push_region_constraints(locations, category, data);
1092 fn push_region_constraints(
1094 locations: Locations,
1095 category: ConstraintCategory,
1096 data: &[QueryRegionConstraint<'tcx>],
1099 "push_region_constraints: constraints generated at {:?} are {:#?}",
1103 constraint_conversion::ConstraintConversion::new(
1105 self.borrowck_context.universal_regions,
1106 self.region_bound_pairs,
1107 Some(self.implicit_region_bound),
1111 &mut self.borrowck_context.constraints,
1112 ).convert_all(&data);
1115 /// Convenient wrapper around `relate_tys::relate_types` -- see
1116 /// that fn for docs.
1122 locations: Locations,
1123 category: ConstraintCategory,
1125 relate_tys::relate_types(
1132 Some(self.borrowck_context),
1140 locations: Locations,
1141 category: ConstraintCategory,
1143 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1146 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1147 /// variables in `sub` with their inferred definitions and try
1148 /// again. This is used for opaque types in places (e.g., `let x:
1149 /// impl Foo = ..`).
1150 fn sub_types_or_anon(
1154 locations: Locations,
1155 category: ConstraintCategory,
1157 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1158 if let ty::Opaque(..) = sup.sty {
1159 // When you have `let x: impl Foo = ...` in a closure,
1160 // the resulting inferend values are stored with the
1161 // def-id of the base function.
1162 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1163 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1175 locations: Locations,
1176 category: ConstraintCategory,
1178 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1181 fn relate_type_and_user_type(
1185 user_ty: &UserTypeProjection,
1186 locations: Locations,
1187 category: ConstraintCategory,
1190 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1191 a, v, user_ty, locations,
1194 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1195 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1197 let tcx = self.infcx.tcx;
1199 for proj in &user_ty.projs {
1200 let projected_ty = curr_projected_ty.projection_ty_core(tcx, proj, |this, field, &()| {
1201 let ty = this.field_ty(tcx, field);
1202 self.normalize(ty, locations)
1204 curr_projected_ty = projected_ty;
1206 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1207 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1209 let ty = curr_projected_ty.ty;
1210 self.relate_types(a, v, ty, locations, category)?;
1215 fn eq_opaque_type_and_type(
1217 revealed_ty: Ty<'tcx>,
1219 anon_owner_def_id: DefId,
1220 locations: Locations,
1221 category: ConstraintCategory,
1224 "eq_opaque_type_and_type( \
1227 revealed_ty, anon_ty
1229 let infcx = self.infcx;
1230 let tcx = infcx.tcx;
1231 let param_env = self.param_env;
1232 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1233 let opaque_type_map = self.fully_perform_op(
1238 let mut obligations = ObligationAccumulator::default();
1240 let dummy_body_id = ObligationCause::dummy().body_id;
1241 let (output_ty, opaque_type_map) =
1242 obligations.add(infcx.instantiate_opaque_types(
1249 "eq_opaque_type_and_type: \
1250 instantiated output_ty={:?} \
1251 opaque_type_map={:#?} \
1253 output_ty, opaque_type_map, revealed_ty
1255 obligations.add(infcx
1256 .at(&ObligationCause::dummy(), param_env)
1257 .eq(output_ty, revealed_ty)?);
1259 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1260 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1261 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1262 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1264 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1265 opaque_decl.concrete_ty,
1266 infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1269 obligations.add(infcx
1270 .at(&ObligationCause::dummy(), param_env)
1271 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1274 debug!("eq_opaque_type_and_type: equated");
1277 value: Some(opaque_type_map),
1278 obligations: obligations.into_vec(),
1281 || "input_output".to_string(),
1285 let universal_region_relations = self.universal_region_relations;
1287 // Finally, if we instantiated the anon types successfully, we
1288 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1289 // prove that `T: Iterator` where `T` is the type we
1290 // instantiated it with).
1291 if let Some(opaque_type_map) = opaque_type_map {
1292 for (opaque_def_id, opaque_decl) in opaque_type_map {
1293 self.fully_perform_op(
1295 ConstraintCategory::OpaqueType,
1298 infcx.constrain_opaque_type(
1301 universal_region_relations,
1305 obligations: vec![],
1308 || "opaque_type_map".to_string(),
1316 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1320 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1321 debug!("check_stmt: {:?}", stmt);
1322 let tcx = self.tcx();
1324 StatementKind::Assign(ref place, ref rv) => {
1325 // Assignments to temporaries are not "interesting";
1326 // they are not caused by the user, but rather artifacts
1327 // of lowering. Assignments to other sorts of places *are* interesting
1329 let category = match *place {
1330 Place::Base(PlaceBase::Local(RETURN_PLACE)) => if let BorrowCheckContext {
1333 defining_ty: DefiningTy::Const(def_id, _),
1337 } = self.borrowck_context
1339 if tcx.is_static(*def_id) {
1340 ConstraintCategory::UseAsStatic
1342 ConstraintCategory::UseAsConst
1345 ConstraintCategory::Return
1347 Place::Base(PlaceBase::Local(l))
1348 if !mir.local_decls[l].is_user_variable.is_some() => {
1349 ConstraintCategory::Boring
1351 _ => ConstraintCategory::Assignment,
1354 let place_ty = place.ty(mir, tcx).ty;
1355 let rv_ty = rv.ty(mir, tcx);
1357 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1362 "bad assignment ({:?} = {:?}): {:?}",
1369 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1370 if let Err(terr) = self.relate_type_and_user_type(
1372 ty::Variance::Invariant,
1373 &UserTypeProjection { base: annotation_index, projs: vec![], },
1374 location.to_locations(),
1375 ConstraintCategory::Boring,
1377 let annotation = &self.user_type_annotations[annotation_index];
1381 "bad user type on rvalue ({:?} = {:?}): {:?}",
1389 self.check_rvalue(mir, rv, location);
1390 if !self.tcx().features().unsized_locals {
1391 let trait_ref = ty::TraitRef {
1392 def_id: tcx.lang_items().sized_trait().unwrap(),
1393 substs: tcx.mk_substs_trait(place_ty, &[]),
1395 self.prove_trait_ref(
1397 location.to_locations(),
1398 ConstraintCategory::SizedBound,
1402 StatementKind::SetDiscriminant {
1406 let place_type = place.ty(mir, tcx).ty;
1407 let adt = match place_type.sty {
1408 ty::Adt(adt, _) if adt.is_enum() => adt,
1411 stmt.source_info.span,
1412 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1418 if variant_index.as_usize() >= adt.variants.len() {
1420 stmt.source_info.span,
1421 "bad set discriminant ({:?} = {:?}): value of of range",
1427 StatementKind::AscribeUserType(ref place, variance, box ref projection) => {
1428 let place_ty = place.ty(mir, tcx).ty;
1429 if let Err(terr) = self.relate_type_and_user_type(
1433 Locations::All(stmt.source_info.span),
1434 ConstraintCategory::TypeAnnotation,
1436 let annotation = &self.user_type_annotations[projection.base];
1440 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1448 StatementKind::FakeRead(..)
1449 | StatementKind::StorageLive(..)
1450 | StatementKind::StorageDead(..)
1451 | StatementKind::InlineAsm { .. }
1452 | StatementKind::Retag { .. }
1453 | StatementKind::Nop => {}
1457 fn check_terminator(
1460 term: &Terminator<'tcx>,
1461 term_location: Location,
1463 debug!("check_terminator: {:?}", term);
1464 let tcx = self.tcx();
1466 TerminatorKind::Goto { .. }
1467 | TerminatorKind::Resume
1468 | TerminatorKind::Abort
1469 | TerminatorKind::Return
1470 | TerminatorKind::GeneratorDrop
1471 | TerminatorKind::Unreachable
1472 | TerminatorKind::Drop { .. }
1473 | TerminatorKind::FalseEdges { .. }
1474 | TerminatorKind::FalseUnwind { .. } => {
1475 // no checks needed for these
1478 TerminatorKind::DropAndReplace {
1484 let place_ty = location.ty(mir, tcx).ty;
1485 let rv_ty = value.ty(mir, tcx);
1487 let locations = term_location.to_locations();
1489 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1494 "bad DropAndReplace ({:?} = {:?}): {:?}",
1501 TerminatorKind::SwitchInt {
1506 let discr_ty = discr.ty(mir, tcx);
1507 if let Err(terr) = self.sub_types(
1510 term_location.to_locations(),
1511 ConstraintCategory::Assignment,
1516 "bad SwitchInt ({:?} on {:?}): {:?}",
1522 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1523 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1525 // FIXME: check the values
1527 TerminatorKind::Call {
1534 let func_ty = func.ty(mir, tcx);
1535 debug!("check_terminator: call, func_ty={:?}", func_ty);
1536 let sig = match func_ty.sty {
1537 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1539 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1543 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1544 term.source_info.span,
1545 LateBoundRegionConversionTime::FnCall,
1548 let sig = self.normalize(sig, term_location);
1549 self.check_call_dest(mir, term, &sig, destination, term_location);
1551 self.prove_predicates(
1552 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1553 term_location.to_locations(),
1554 ConstraintCategory::Boring,
1557 // The ordinary liveness rules will ensure that all
1558 // regions in the type of the callee are live here. We
1559 // then further constrain the late-bound regions that
1560 // were instantiated at the call site to be live as
1561 // well. The resulting is that all the input (and
1562 // output) types in the signature must be live, since
1563 // all the inputs that fed into it were live.
1564 for &late_bound_region in map.values() {
1565 let region_vid = self.borrowck_context
1567 .to_region_vid(late_bound_region);
1568 self.borrowck_context
1570 .liveness_constraints
1571 .add_element(region_vid, term_location);
1574 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1576 TerminatorKind::Assert {
1577 ref cond, ref msg, ..
1579 let cond_ty = cond.ty(mir, tcx);
1580 if cond_ty != tcx.types.bool {
1581 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1584 if let BoundsCheck { ref len, ref index } = *msg {
1585 if len.ty(mir, tcx) != tcx.types.usize {
1586 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1588 if index.ty(mir, tcx) != tcx.types.usize {
1589 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1593 TerminatorKind::Yield { ref value, .. } => {
1594 let value_ty = value.ty(mir, tcx);
1595 match mir.yield_ty {
1596 None => span_mirbug!(self, term, "yield in non-generator"),
1598 if let Err(terr) = self.sub_types(
1601 term_location.to_locations(),
1602 ConstraintCategory::Yield,
1607 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1622 term: &Terminator<'tcx>,
1623 sig: &ty::FnSig<'tcx>,
1624 destination: &Option<(Place<'tcx>, BasicBlock)>,
1625 term_location: Location,
1627 let tcx = self.tcx();
1628 match *destination {
1629 Some((ref dest, _target_block)) => {
1630 let dest_ty = dest.ty(mir, tcx).ty;
1631 let category = match *dest {
1632 Place::Base(PlaceBase::Local(RETURN_PLACE)) => {
1633 if let BorrowCheckContext {
1636 defining_ty: DefiningTy::Const(def_id, _),
1640 } = self.borrowck_context
1642 if tcx.is_static(*def_id) {
1643 ConstraintCategory::UseAsStatic
1645 ConstraintCategory::UseAsConst
1648 ConstraintCategory::Return
1651 Place::Base(PlaceBase::Local(l))
1652 if !mir.local_decls[l].is_user_variable.is_some() => {
1653 ConstraintCategory::Boring
1655 _ => ConstraintCategory::Assignment,
1658 let locations = term_location.to_locations();
1661 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1666 "call dest mismatch ({:?} <- {:?}): {:?}",
1673 // When `#![feature(unsized_locals)]` is not enabled,
1674 // this check is done at `check_local`.
1675 if self.tcx().features().unsized_locals {
1676 let span = term.source_info.span;
1677 self.ensure_place_sized(dest_ty, span);
1681 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1682 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1688 fn check_call_inputs(
1691 term: &Terminator<'tcx>,
1692 sig: &ty::FnSig<'tcx>,
1693 args: &[Operand<'tcx>],
1694 term_location: Location,
1695 from_hir_call: bool,
1697 debug!("check_call_inputs({:?}, {:?})", sig, args);
1698 // Do not count the `VaList` argument as a "true" argument to
1699 // a C-variadic function.
1700 let inputs = if sig.c_variadic {
1701 &sig.inputs()[..sig.inputs().len() - 1]
1705 if args.len() < inputs.len() || (args.len() > inputs.len() && !sig.c_variadic) {
1706 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1708 for (n, (fn_arg, op_arg)) in inputs.iter().zip(args).enumerate() {
1709 let op_arg_ty = op_arg.ty(mir, self.tcx());
1710 let category = if from_hir_call {
1711 ConstraintCategory::CallArgument
1713 ConstraintCategory::Boring
1716 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1721 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1731 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1732 let is_cleanup = block_data.is_cleanup;
1733 self.last_span = block_data.terminator().source_info.span;
1734 match block_data.terminator().kind {
1735 TerminatorKind::Goto { target } => {
1736 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1738 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1739 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1741 TerminatorKind::Resume => if !is_cleanup {
1742 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1744 TerminatorKind::Abort => if !is_cleanup {
1745 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1747 TerminatorKind::Return => if is_cleanup {
1748 span_mirbug!(self, block_data, "return on cleanup block")
1750 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1751 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1753 TerminatorKind::Yield { resume, drop, .. } => {
1755 span_mirbug!(self, block_data, "yield in cleanup block")
1757 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1758 if let Some(drop) = drop {
1759 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1762 TerminatorKind::Unreachable => {}
1763 TerminatorKind::Drop { target, unwind, .. }
1764 | TerminatorKind::DropAndReplace { target, unwind, .. }
1765 | TerminatorKind::Assert {
1770 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1771 if let Some(unwind) = unwind {
1773 span_mirbug!(self, block_data, "unwind on cleanup block")
1775 self.assert_iscleanup(mir, block_data, unwind, true);
1778 TerminatorKind::Call {
1783 if let &Some((_, target)) = destination {
1784 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1786 if let Some(cleanup) = cleanup {
1788 span_mirbug!(self, block_data, "cleanup on cleanup block")
1790 self.assert_iscleanup(mir, block_data, cleanup, true);
1793 TerminatorKind::FalseEdges {
1795 ref imaginary_targets,
1797 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1798 for target in imaginary_targets {
1799 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1802 TerminatorKind::FalseUnwind {
1806 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1807 if let Some(unwind) = unwind {
1812 "cleanup in cleanup block via false unwind"
1815 self.assert_iscleanup(mir, block_data, unwind, true);
1821 fn assert_iscleanup(
1824 ctxt: &dyn fmt::Debug,
1828 if mir[bb].is_cleanup != iscleanuppad {
1832 "cleanuppad mismatch: {:?} should be {:?}",
1839 fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1840 match mir.local_kind(local) {
1841 LocalKind::ReturnPointer | LocalKind::Arg => {
1842 // return values of normal functions are required to be
1843 // sized by typeck, but return values of ADT constructors are
1844 // not because we don't include a `Self: Sized` bounds on them.
1846 // Unbound parts of arguments were never required to be Sized
1847 // - maybe we should make that a warning.
1850 LocalKind::Var | LocalKind::Temp => {}
1853 // When `#![feature(unsized_locals)]` is enabled, only function calls
1854 // and nullary ops are checked in `check_call_dest`.
1855 if !self.tcx().features().unsized_locals {
1856 let span = local_decl.source_info.span;
1857 let ty = local_decl.ty;
1858 self.ensure_place_sized(ty, span);
1862 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1863 let tcx = self.tcx();
1865 // Erase the regions from `ty` to get a global type. The
1866 // `Sized` bound in no way depends on precise regions, so this
1867 // shouldn't affect `is_sized`.
1868 let gcx = tcx.global_tcx();
1869 let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1870 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1871 // in current MIR construction, all non-control-flow rvalue
1872 // expressions evaluate through `as_temp` or `into` a return
1873 // slot or local, so to find all unsized rvalues it is enough
1874 // to check all temps, return slots and locals.
1875 if let None = self.reported_errors.replace((ty, span)) {
1876 let mut diag = struct_span_err!(
1880 "cannot move a value of type {0}: the size of {0} \
1881 cannot be statically determined",
1885 // While this is located in `nll::typeck` this error is not
1886 // an NLL error, it's a required check to prevent creation
1887 // of unsized rvalues in certain cases:
1888 // * operand of a box expression
1889 // * callee in a call expression
1895 fn aggregate_field_ty(
1897 ak: &AggregateKind<'tcx>,
1900 ) -> Result<Ty<'tcx>, FieldAccessError> {
1901 let tcx = self.tcx();
1904 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1905 let variant = &def.variants[variant_index];
1906 let adj_field_index = active_field_index.unwrap_or(field_index);
1907 if let Some(field) = variant.fields.get(adj_field_index) {
1908 Ok(self.normalize(field.ty(tcx, substs), location))
1910 Err(FieldAccessError::OutOfRange {
1911 field_count: variant.fields.len(),
1915 AggregateKind::Closure(def_id, substs) => {
1916 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1918 None => Err(FieldAccessError::OutOfRange {
1919 field_count: substs.upvar_tys(def_id, tcx).count(),
1923 AggregateKind::Generator(def_id, substs, _) => {
1924 // It doesn't make sense to look at a field beyond the prefix;
1925 // these require a variant index, and are not initialized in
1926 // aggregate rvalues.
1927 match substs.prefix_tys(def_id, tcx).nth(field_index) {
1929 None => Err(FieldAccessError::OutOfRange {
1930 field_count: substs.prefix_tys(def_id, tcx).count(),
1934 AggregateKind::Array(ty) => Ok(ty),
1935 AggregateKind::Tuple => {
1936 unreachable!("This should have been covered in check_rvalues");
1941 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1942 let tcx = self.tcx();
1945 Rvalue::Aggregate(ak, ops) => {
1946 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1949 Rvalue::Repeat(operand, len) => if *len > 1 {
1950 let operand_ty = operand.ty(mir, tcx);
1952 let trait_ref = ty::TraitRef {
1953 def_id: tcx.lang_items().copy_trait().unwrap(),
1954 substs: tcx.mk_substs_trait(operand_ty, &[]),
1957 self.prove_trait_ref(
1959 location.to_locations(),
1960 ConstraintCategory::CopyBound,
1964 Rvalue::NullaryOp(_, ty) => {
1965 // Even with unsized locals cannot box an unsized value.
1966 if self.tcx().features().unsized_locals {
1967 let span = mir.source_info(location).span;
1968 self.ensure_place_sized(ty, span);
1971 let trait_ref = ty::TraitRef {
1972 def_id: tcx.lang_items().sized_trait().unwrap(),
1973 substs: tcx.mk_substs_trait(ty, &[]),
1976 self.prove_trait_ref(
1978 location.to_locations(),
1979 ConstraintCategory::SizedBound,
1983 Rvalue::Cast(cast_kind, op, ty) => {
1985 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1986 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1988 // The type that we see in the fcx is like
1989 // `foo::<'a, 'b>`, where `foo` is the path to a
1990 // function definition. When we extract the
1991 // signature, it comes from the `fn_sig` query,
1992 // and hence may contain unnormalized results.
1993 let fn_sig = self.normalize(fn_sig, location);
1995 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1997 if let Err(terr) = self.eq_types(
2000 location.to_locations(),
2001 ConstraintCategory::Cast,
2006 "equating {:?} with {:?} yields {:?}",
2014 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2015 let sig = match op.ty(mir, tcx).sty {
2016 ty::Closure(def_id, substs) => {
2017 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
2021 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2023 if let Err(terr) = self.eq_types(
2026 location.to_locations(),
2027 ConstraintCategory::Cast,
2032 "equating {:?} with {:?} yields {:?}",
2040 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2041 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
2043 // The type that we see in the fcx is like
2044 // `foo::<'a, 'b>`, where `foo` is the path to a
2045 // function definition. When we extract the
2046 // signature, it comes from the `fn_sig` query,
2047 // and hence may contain unnormalized results.
2048 let fn_sig = self.normalize(fn_sig, location);
2050 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2052 if let Err(terr) = self.eq_types(
2055 location.to_locations(),
2056 ConstraintCategory::Cast,
2061 "equating {:?} with {:?} yields {:?}",
2069 CastKind::Pointer(PointerCast::Unsize) => {
2071 let trait_ref = ty::TraitRef {
2072 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2073 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
2076 self.prove_trait_ref(
2078 location.to_locations(),
2079 ConstraintCategory::Cast,
2083 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2084 let ty_from = match op.ty(mir, tcx).sty {
2085 ty::RawPtr(ty::TypeAndMut {
2087 mutbl: hir::MutMutable,
2093 "unexpected base type for cast {:?}",
2099 let ty_to = match ty.sty {
2100 ty::RawPtr(ty::TypeAndMut {
2102 mutbl: hir::MutImmutable,
2108 "unexpected target type for cast {:?}",
2114 if let Err(terr) = self.sub_types(
2117 location.to_locations(),
2118 ConstraintCategory::Cast,
2123 "relating {:?} with {:?} yields {:?}",
2132 if let ty::Ref(_, mut ty_from, _) = op.ty(mir, tcx).sty {
2133 let (mut ty_to, mutability) = if let ty::RawPtr(ty::TypeAndMut {
2142 "invalid cast types {:?} -> {:?}",
2149 // Handle the direct cast from `&[T; N]` to `*const T` by unwrapping
2150 // any array we find.
2151 while let ty::Array(ty_elem_from, _) = ty_from.sty {
2152 ty_from = ty_elem_from;
2153 if let ty::Array(ty_elem_to, _) = ty_to.sty {
2160 if let hir::MutMutable = mutability {
2161 if let Err(terr) = self.eq_types(
2164 location.to_locations(),
2165 ConstraintCategory::Cast,
2170 "equating {:?} with {:?} yields {:?}",
2177 if let Err(terr) = self.sub_types(
2180 location.to_locations(),
2181 ConstraintCategory::Cast,
2186 "relating {:?} with {:?} yields {:?}",
2198 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2199 self.add_reborrow_constraint(mir, location, region, borrowed_place);
2202 Rvalue::BinaryOp(BinOp::Eq, left, right)
2203 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2204 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2205 | Rvalue::BinaryOp(BinOp::Le, left, right)
2206 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2207 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2208 let ty_left = left.ty(mir, tcx);
2209 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.sty {
2210 let ty_right = right.ty(mir, tcx);
2211 let common_ty = self.infcx.next_ty_var(
2212 TypeVariableOrigin::MiscVariable(mir.source_info(location).span),
2217 location.to_locations(),
2218 ConstraintCategory::Boring
2219 ).unwrap_or_else(|err| {
2220 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2222 if let Err(terr) = self.sub_types(
2225 location.to_locations(),
2226 ConstraintCategory::Boring
2231 "unexpected comparison types {:?} and {:?} yields {:?}",
2242 | Rvalue::BinaryOp(..)
2243 | Rvalue::CheckedBinaryOp(..)
2244 | Rvalue::UnaryOp(..)
2245 | Rvalue::Discriminant(..) => {}
2249 /// If this rvalue supports a user-given type annotation, then
2250 /// extract and return it. This represents the final type of the
2251 /// rvalue and will be unified with the inferred type.
2252 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2255 | Rvalue::Repeat(..)
2259 | Rvalue::BinaryOp(..)
2260 | Rvalue::CheckedBinaryOp(..)
2261 | Rvalue::NullaryOp(..)
2262 | Rvalue::UnaryOp(..)
2263 | Rvalue::Discriminant(..) => None,
2265 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2266 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2267 AggregateKind::Array(_) => None,
2268 AggregateKind::Tuple => None,
2269 AggregateKind::Closure(_, _) => None,
2270 AggregateKind::Generator(_, _, _) => None,
2275 fn check_aggregate_rvalue(
2278 rvalue: &Rvalue<'tcx>,
2279 aggregate_kind: &AggregateKind<'tcx>,
2280 operands: &[Operand<'tcx>],
2283 let tcx = self.tcx();
2285 self.prove_aggregate_predicates(aggregate_kind, location);
2287 if *aggregate_kind == AggregateKind::Tuple {
2288 // tuple rvalue field type is always the type of the op. Nothing to check here.
2292 for (i, operand) in operands.iter().enumerate() {
2293 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2294 Ok(field_ty) => field_ty,
2295 Err(FieldAccessError::OutOfRange { field_count }) => {
2299 "accessed field #{} but variant only has {}",
2306 let operand_ty = operand.ty(mir, tcx);
2308 if let Err(terr) = self.sub_types(
2311 location.to_locations(),
2312 ConstraintCategory::Boring,
2317 "{:?} is not a subtype of {:?}: {:?}",
2326 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2330 /// - `location`: the location `L` where the borrow expression occurs
2331 /// - `borrow_region`: the region `'a` associated with the borrow
2332 /// - `borrowed_place`: the place `P` being borrowed
2333 fn add_reborrow_constraint(
2337 borrow_region: ty::Region<'tcx>,
2338 borrowed_place: &Place<'tcx>,
2340 // These constraints are only meaningful during borrowck:
2341 let BorrowCheckContext {
2347 } = self.borrowck_context;
2349 // In Polonius mode, we also push a `borrow_region` fact
2350 // linking the loan to the region (in some cases, though,
2351 // there is no loan associated with this borrow expression --
2352 // that occurs when we are borrowing an unsafe place, for
2354 if let Some(all_facts) = all_facts {
2355 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2356 let region_vid = borrow_region.to_region_vid();
2357 all_facts.borrow_region.push((
2360 location_table.mid_index(location),
2365 // If we are reborrowing the referent of another reference, we
2366 // need to add outlives relationships. In a case like `&mut
2367 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2368 // need to ensure that `'b: 'a`.
2370 let mut borrowed_place = borrowed_place;
2373 "add_reborrow_constraint({:?}, {:?}, {:?})",
2374 location, borrow_region, borrowed_place
2376 while let Place::Projection(box Projection { base, elem }) = borrowed_place {
2377 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2380 ProjectionElem::Deref => {
2381 let tcx = self.infcx.tcx;
2382 let base_ty = base.ty(mir, tcx).ty;
2384 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2386 ty::Ref(ref_region, _, mutbl) => {
2387 constraints.outlives_constraints.push(OutlivesConstraint {
2388 sup: ref_region.to_region_vid(),
2389 sub: borrow_region.to_region_vid(),
2390 locations: location.to_locations(),
2391 category: ConstraintCategory::Boring,
2395 hir::Mutability::MutImmutable => {
2396 // Immutable reference. We don't need the base
2397 // to be valid for the entire lifetime of
2401 hir::Mutability::MutMutable => {
2402 // Mutable reference. We *do* need the base
2403 // to be valid, because after the base becomes
2404 // invalid, someone else can use our mutable deref.
2406 // This is in order to make the following function
2409 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2414 // As otherwise you could clone `&mut T` using the
2415 // following function:
2417 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2418 // let my_clone = unsafe_deref(&'a x);
2427 // deref of raw pointer, guaranteed to be valid
2430 ty::Adt(def, _) if def.is_box() => {
2431 // deref of `Box`, need the base to be valid - propagate
2433 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2436 ProjectionElem::Field(..)
2437 | ProjectionElem::Downcast(..)
2438 | ProjectionElem::Index(..)
2439 | ProjectionElem::ConstantIndex { .. }
2440 | ProjectionElem::Subslice { .. } => {
2441 // other field access
2445 // The "propagate" case. We need to check that our base is valid
2446 // for the borrow's lifetime.
2447 borrowed_place = base;
2451 fn prove_aggregate_predicates(
2453 aggregate_kind: &AggregateKind<'tcx>,
2456 let tcx = self.tcx();
2459 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2460 aggregate_kind, location
2463 let instantiated_predicates = match aggregate_kind {
2464 AggregateKind::Adt(def, _, substs, _, _) => {
2465 tcx.predicates_of(def.did).instantiate(tcx, substs)
2468 // For closures, we have some **extra requirements** we
2470 // have to check. In particular, in their upvars and
2471 // signatures, closures often reference various regions
2472 // from the surrounding function -- we call those the
2473 // closure's free regions. When we borrow-check (and hence
2474 // region-check) closures, we may find that the closure
2475 // requires certain relationships between those free
2476 // regions. However, because those free regions refer to
2477 // portions of the CFG of their caller, the closure is not
2478 // in a position to verify those relationships. In that
2479 // case, the requirements get "propagated" to us, and so
2480 // we have to solve them here where we instantiate the
2483 // Despite the opacity of the previous parapgrah, this is
2484 // actually relatively easy to understand in terms of the
2485 // desugaring. A closure gets desugared to a struct, and
2486 // these extra requirements are basically like where
2487 // clauses on the struct.
2488 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2489 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2490 self.prove_closure_bounds(tcx, *def_id, substs, location)
2493 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2496 self.normalize_and_prove_instantiated_predicates(
2497 instantiated_predicates,
2498 location.to_locations(),
2502 fn prove_closure_bounds(
2504 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2506 substs: SubstsRef<'tcx>,
2508 ) -> ty::InstantiatedPredicates<'tcx> {
2509 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2510 let closure_constraints =
2511 closure_region_requirements.apply_requirements(tcx, def_id, substs);
2513 let bounds_mapping = closure_constraints
2516 .filter_map(|(idx, constraint)| {
2517 let ty::OutlivesPredicate(k1, r2) =
2518 constraint.no_bound_vars().unwrap_or_else(|| {
2519 bug!("query_constraint {:?} contained bound vars", constraint,);
2523 UnpackedKind::Lifetime(r1) => {
2524 // constraint is r1: r2
2525 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2526 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2527 let outlives_requirements =
2528 &closure_region_requirements.outlives_requirements[idx];
2532 outlives_requirements.category,
2533 outlives_requirements.blame_span,
2537 UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2542 let existing = self.borrowck_context
2544 .closure_bounds_mapping
2545 .insert(location, bounds_mapping);
2548 "Multiple closures at the same location."
2551 self.push_region_constraints(
2552 location.to_locations(),
2553 ConstraintCategory::ClosureBounds,
2554 &closure_constraints,
2558 tcx.predicates_of(def_id).instantiate(tcx, substs)
2563 trait_ref: ty::TraitRef<'tcx>,
2564 locations: Locations,
2565 category: ConstraintCategory,
2567 self.prove_predicates(
2568 Some(ty::Predicate::Trait(
2569 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2576 fn normalize_and_prove_instantiated_predicates(
2578 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2579 locations: Locations,
2581 for predicate in instantiated_predicates.predicates {
2582 let predicate = self.normalize(predicate, locations);
2583 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2587 fn prove_predicates(
2589 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2590 locations: Locations,
2591 category: ConstraintCategory,
2593 for predicate in predicates {
2595 "prove_predicates(predicate={:?}, locations={:?})",
2596 predicate, locations,
2599 self.prove_predicate(predicate, locations, category);
2605 predicate: ty::Predicate<'tcx>,
2606 locations: Locations,
2607 category: ConstraintCategory,
2610 "prove_predicate(predicate={:?}, location={:?})",
2611 predicate, locations,
2614 let param_env = self.param_env;
2615 self.fully_perform_op(
2618 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2619 ).unwrap_or_else(|NoSolution| {
2620 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2624 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2625 self.last_span = mir.span;
2626 debug!("run_on_mir: {:?}", mir.span);
2628 for (local, local_decl) in mir.local_decls.iter_enumerated() {
2629 self.check_local(mir, local, local_decl);
2632 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2633 let mut location = Location {
2637 for stmt in &block_data.statements {
2638 if !stmt.source_info.span.is_dummy() {
2639 self.last_span = stmt.source_info.span;
2641 self.check_stmt(mir, stmt, location);
2642 location.statement_index += 1;
2645 self.check_terminator(mir, block_data.terminator(), location);
2646 self.check_iscleanup(mir, block_data);
2650 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2652 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2654 debug!("normalize(value={:?}, location={:?})", value, location);
2655 let param_env = self.param_env;
2656 self.fully_perform_op(
2657 location.to_locations(),
2658 ConstraintCategory::Boring,
2659 param_env.and(type_op::normalize::Normalize::new(value)),
2660 ).unwrap_or_else(|NoSolution| {
2661 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2667 trait NormalizeLocation: fmt::Debug + Copy {
2668 fn to_locations(self) -> Locations;
2671 impl NormalizeLocation for Locations {
2672 fn to_locations(self) -> Locations {
2677 impl NormalizeLocation for Location {
2678 fn to_locations(self) -> Locations {
2679 Locations::Single(self)
2683 #[derive(Debug, Default)]
2684 struct ObligationAccumulator<'tcx> {
2685 obligations: PredicateObligations<'tcx>,
2688 impl<'tcx> ObligationAccumulator<'tcx> {
2689 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2690 let InferOk { value, obligations } = value;
2691 self.obligations.extend(obligations);
2695 fn into_vec(self) -> PredicateObligations<'tcx> {