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::{OutlivesConstraintSet, OutlivesConstraint};
8 use crate::borrow_check::nll::member_constraints::MemberConstraintSet;
9 use crate::borrow_check::nll::facts::AllFacts;
10 use crate::borrow_check::nll::region_infer::values::LivenessValues;
11 use crate::borrow_check::nll::region_infer::values::PlaceholderIndex;
12 use crate::borrow_check::nll::region_infer::values::PlaceholderIndices;
13 use crate::borrow_check::nll::region_infer::values::RegionValueElements;
14 use crate::borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
15 use crate::borrow_check::nll::renumber;
16 use crate::borrow_check::nll::type_check::free_region_relations::{
17 CreateResult, UniversalRegionRelations,
19 use crate::borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
20 use crate::borrow_check::nll::ToRegionVid;
21 use crate::dataflow::move_paths::MoveData;
22 use crate::dataflow::FlowAtLocation;
23 use crate::dataflow::MaybeInitializedPlaces;
26 use rustc::hir::def_id::DefId;
27 use rustc::infer::canonical::QueryRegionConstraints;
28 use rustc::infer::outlives::env::RegionBoundPairs;
29 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
30 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
31 use rustc::mir::interpret::{InterpError::BoundsCheck, ConstValue};
32 use rustc::mir::tcx::PlaceTy;
33 use rustc::mir::visit::{PlaceContext, Visitor, 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::adjustment::{PointerCast};
40 use rustc::ty::fold::TypeFoldable;
41 use rustc::ty::subst::{Subst, SubstsRef, UnpackedKind, UserSubsts};
43 self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, UserType,
44 CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
45 UserTypeAnnotationIndex,
47 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
48 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
49 use rustc::ty::layout::VariantIdx;
51 use std::{fmt, iter, mem};
52 use syntax_pos::{Span, DUMMY_SP};
54 macro_rules! span_mirbug {
55 ($context:expr, $elem:expr, $($message:tt)*) => ({
56 $crate::borrow_check::nll::type_check::mirbug(
60 "broken MIR in {:?} ({:?}): {}",
63 format_args!($($message)*),
69 macro_rules! span_mirbug_and_err {
70 ($context:expr, $elem:expr, $($message:tt)*) => ({
72 span_mirbug!($context, $elem, $($message)*);
78 mod constraint_conversion;
79 pub mod free_region_relations;
84 /// Type checks the given `mir` in the context of the inference
85 /// context `infcx`. Returns any region constraints that have yet to
86 /// be proven. This result is includes liveness constraints that
87 /// ensure that regions appearing in the types of all local variables
88 /// are live at all points where that local variable may later be
91 /// This phase of type-check ought to be infallible -- this is because
92 /// the original, HIR-based type-check succeeded. So if any errors
93 /// occur here, we will get a `bug!` reported.
97 /// - `infcx` -- inference context to use
98 /// - `param_env` -- parameter environment to use for trait solving
99 /// - `mir` -- MIR to type-check
100 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
101 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
102 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
103 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
104 /// to outlive; should represent the fn body
105 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
106 /// the types of the input parameters found in the MIR itself will be equated with these
107 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
108 /// the type for the RETURN_PLACE will be equated with this
109 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
110 /// constraints for the regions in the types of variables
111 /// - `flow_inits` -- results of a maybe-init dataflow analysis
112 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
113 pub(crate) fn type_check<'tcx>(
114 infcx: &InferCtxt<'_, 'tcx>,
115 param_env: ty::ParamEnv<'tcx>,
118 universal_regions: &Rc<UniversalRegions<'tcx>>,
119 location_table: &LocationTable,
120 borrow_set: &BorrowSet<'tcx>,
121 all_facts: &mut Option<AllFacts>,
122 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'_, 'tcx>>,
123 move_data: &MoveData<'tcx>,
124 elements: &Rc<RegionValueElements>,
125 ) -> MirTypeckResults<'tcx> {
126 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
127 let mut constraints = MirTypeckRegionConstraints {
128 placeholder_indices: PlaceholderIndices::default(),
129 placeholder_index_to_region: IndexVec::default(),
130 liveness_constraints: LivenessValues::new(elements.clone()),
131 outlives_constraints: OutlivesConstraintSet::default(),
132 member_constraints: MemberConstraintSet::default(),
133 closure_bounds_mapping: Default::default(),
134 type_tests: Vec::default(),
138 universal_region_relations,
140 normalized_inputs_and_output,
141 } = free_region_relations::create(
144 Some(implicit_region_bound),
149 let mut borrowck_context = BorrowCheckContext {
154 constraints: &mut constraints,
163 implicit_region_bound,
164 &mut borrowck_context,
165 &universal_region_relations,
167 cx.equate_inputs_and_outputs(body, universal_regions, &normalized_inputs_and_output);
168 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
170 translate_outlives_facts(cx.borrowck_context);
176 universal_region_relations,
180 fn type_check_internal<'a, 'tcx, R>(
181 infcx: &'a InferCtxt<'a, 'tcx>,
183 param_env: ty::ParamEnv<'tcx>,
184 body: &'a Body<'tcx>,
185 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
186 implicit_region_bound: ty::Region<'tcx>,
187 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
188 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
189 mut extra: impl FnMut(&mut TypeChecker<'a, '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, body);
203 verifier.visit_body(body);
204 verifier.errors_reported
207 if !errors_reported {
208 // if verifier failed, don't do further checks to avoid ICEs
209 checker.typeck_mir(body);
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.outlives().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, 'tcx> {
257 cx: &'a mut TypeChecker<'b, 'tcx>,
258 body: &'b Body<'tcx>,
261 errors_reported: bool,
264 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, '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.body, 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_body(&mut self, body: &Body<'tcx>) {
374 self.sanitize_type(&"return type", body.return_ty());
375 for local_decl in &body.local_decls {
376 self.sanitize_type(local_decl, local_decl.ty);
378 if self.errors_reported {
381 self.super_body(body);
385 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
386 fn new(cx: &'a mut TypeChecker<'b, 'tcx>, body: &'b Body<'tcx>) -> Self {
389 mir_def_id: cx.mir_def_id,
391 last_span: body.span,
392 errors_reported: false,
396 fn tcx(&self) -> TyCtxt<'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);
453 place.iterate(|place_base, place_projection| {
454 let mut place_ty = match place_base {
455 PlaceBase::Local(index) =>
456 PlaceTy::from_ty(self.body.local_decls[*index].ty),
457 PlaceBase::Static(box Static { kind, ty: sty }) => {
458 let sty = self.sanitize_type(place, sty);
460 |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
464 if let Err(terr) = verifier.cx.eq_types(
467 location.to_locations(),
468 ConstraintCategory::Boring,
473 "bad promoted type ({:?}: {:?}): {:?}",
481 StaticKind::Promoted(promoted) => {
482 if !self.errors_reported {
483 let promoted_body = &self.body.promoted[*promoted];
484 self.sanitize_promoted(promoted_body, location);
486 let promoted_ty = promoted_body.return_ty();
487 check_err(self, place, promoted_ty, sty);
490 StaticKind::Static(def_id) => {
491 let ty = self.tcx().type_of(*def_id);
492 let ty = self.cx.normalize(ty, location);
494 check_err(self, place, ty, sty);
497 PlaceTy::from_ty(sty)
501 // FIXME use place_projection.is_empty() when is available
502 if let Place::Base(_) = place {
503 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
504 let tcx = self.tcx();
505 let trait_ref = ty::TraitRef {
506 def_id: tcx.lang_items().copy_trait().unwrap(),
507 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
510 // In order to have a Copy operand, the type T of the
511 // value must be Copy. Note that we prove that T: Copy,
512 // rather than using the `is_copy_modulo_regions`
513 // test. This is important because
514 // `is_copy_modulo_regions` ignores the resulting region
515 // obligations and assumes they pass. This can result in
516 // bounds from Copy impls being unsoundly ignored (e.g.,
517 // #29149). Note that we decide to use Copy before knowing
518 // whether the bounds fully apply: in effect, the rule is
519 // that if a value of some type could implement Copy, then
521 self.cx.prove_trait_ref(
523 location.to_locations(),
524 ConstraintCategory::CopyBound,
529 for proj in place_projection {
530 if place_ty.variant_index.is_none() {
531 if place_ty.ty.references_error() {
532 assert!(self.errors_reported);
533 return PlaceTy::from_ty(self.tcx().types.err);
536 place_ty = self.sanitize_projection(place_ty, &proj.elem, place, location)
543 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
544 // Determine the constraints from the promoted MIR by running the type
545 // checker on the promoted MIR, then transfer the constraints back to
546 // the main MIR, changing the locations to the provided location.
548 let parent_body = mem::replace(&mut self.body, promoted_body);
550 let all_facts = &mut None;
551 let mut constraints = Default::default();
552 let mut closure_bounds = Default::default();
553 // Don't try to add borrow_region facts for the promoted MIR
554 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
556 // Use a new sets of constraints and closure bounds so that we can
557 // modify their locations.
559 &mut self.cx.borrowck_context.constraints.outlives_constraints,
563 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
567 self.visit_body(promoted_body);
569 if !self.errors_reported {
570 // if verifier failed, don't do further checks to avoid ICEs
571 self.cx.typeck_mir(promoted_body);
574 self.body = parent_body;
575 // Merge the outlives constraints back in, at the given location.
576 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
578 &mut self.cx.borrowck_context.constraints.outlives_constraints,
582 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
586 let locations = location.to_locations();
587 for constraint in constraints.outlives().iter() {
588 let mut constraint = *constraint;
589 constraint.locations = locations;
590 if let ConstraintCategory::Return
591 | ConstraintCategory::UseAsConst
592 | ConstraintCategory::UseAsStatic = constraint.category
594 // "Returning" from a promoted is an assigment to a
595 // temporary from the user's point of view.
596 constraint.category = ConstraintCategory::Boring;
598 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
601 if !closure_bounds.is_empty() {
602 let combined_bounds_mapping = closure_bounds
604 .flat_map(|(_, value)| value)
606 let existing = self.cx.borrowck_context
608 .closure_bounds_mapping
609 .insert(location, combined_bounds_mapping);
612 "Multiple promoteds/closures at the same location."
617 fn sanitize_projection(
620 pi: &PlaceElem<'tcx>,
624 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
625 let tcx = self.tcx();
626 let base_ty = base.ty;
628 ProjectionElem::Deref => {
629 let deref_ty = base_ty.builtin_deref(true);
631 deref_ty.map(|t| t.ty).unwrap_or_else(|| {
632 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
636 ProjectionElem::Index(i) => {
637 let index_ty = Place::from(i).ty(self.body, tcx).ty;
638 if index_ty != tcx.types.usize {
640 span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
644 base_ty.builtin_index().unwrap_or_else(|| {
645 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
650 ProjectionElem::ConstantIndex { .. } => {
651 // consider verifying in-bounds
653 base_ty.builtin_index().unwrap_or_else(|| {
654 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
658 ProjectionElem::Subslice { from, to } => PlaceTy::from_ty(
660 ty::Array(inner, size) => {
661 let size = size.unwrap_usize(tcx);
662 let min_size = (from as u64) + (to as u64);
663 if let Some(rest_size) = size.checked_sub(min_size) {
664 tcx.mk_array(inner, rest_size)
666 span_mirbug_and_err!(
669 "taking too-small slice of {:?}",
674 ty::Slice(..) => base_ty,
675 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
678 ProjectionElem::Downcast(maybe_name, index) => match base_ty.sty {
679 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
680 if index.as_usize() >= adt_def.variants.len() {
682 span_mirbug_and_err!(
685 "cast to variant #{:?} but enum only has {:?}",
687 adt_def.variants.len()
693 variant_index: Some(index),
697 // We do not need to handle generators here, because this runs
698 // before the generator transform stage.
700 let ty = if let Some(name) = maybe_name {
701 span_mirbug_and_err!(
704 "can't downcast {:?} as {:?}",
709 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
714 ProjectionElem::Field(field, fty) => {
715 let fty = self.sanitize_type(place, fty);
716 match self.field_ty(place, base, field, location) {
717 Ok(ty) => if let Err(terr) = self.cx.eq_types(
720 location.to_locations(),
721 ConstraintCategory::Boring,
726 "bad field access ({:?}: {:?}): {:?}",
732 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
735 "accessed field #{} but variant only has {}",
740 PlaceTy::from_ty(fty)
745 fn error(&mut self) -> Ty<'tcx> {
746 self.errors_reported = true;
752 parent: &dyn fmt::Debug,
753 base_ty: PlaceTy<'tcx>,
756 ) -> Result<Ty<'tcx>, FieldAccessError> {
757 let tcx = self.tcx();
759 let (variant, substs) = match base_ty {
760 PlaceTy { ty, variant_index: Some(variant_index) } => match ty.sty {
761 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
762 ty::Generator(def_id, substs, _) => {
763 let mut variants = substs.state_tys(def_id, tcx);
764 let mut variant = match variants.nth(variant_index.into()) {
767 bug!("variant_index of generator out of range: {:?}/{:?}",
769 substs.state_tys(def_id, tcx).count())
772 return match variant.nth(field.index()) {
774 None => Err(FieldAccessError::OutOfRange {
775 field_count: variant.count(),
779 _ => bug!("can't have downcast of non-adt non-generator type"),
781 PlaceTy { ty, variant_index: None } => match ty.sty {
782 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
783 (&adt_def.variants[VariantIdx::new(0)], substs),
784 ty::Closure(def_id, substs) => {
785 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
787 None => Err(FieldAccessError::OutOfRange {
788 field_count: substs.upvar_tys(def_id, tcx).count(),
792 ty::Generator(def_id, substs, _) => {
793 // Only prefix fields (upvars and current state) are
794 // accessible without a variant index.
795 return match substs.prefix_tys(def_id, tcx).nth(field.index()) {
797 None => Err(FieldAccessError::OutOfRange {
798 field_count: substs.prefix_tys(def_id, tcx).count(),
803 return match tys.get(field.index()) {
804 Some(&ty) => Ok(ty.expect_ty()),
805 None => Err(FieldAccessError::OutOfRange {
806 field_count: tys.len(),
811 return Ok(span_mirbug_and_err!(
814 "can't project out of {:?}",
821 if let Some(field) = variant.fields.get(field.index()) {
822 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
824 Err(FieldAccessError::OutOfRange {
825 field_count: variant.fields.len(),
831 /// The MIR type checker. Visits the MIR and enforces all the
832 /// constraints needed for it to be valid and well-typed. Along the
833 /// way, it accrues region constraints -- these can later be used by
834 /// NLL region checking.
835 struct TypeChecker<'a, 'tcx> {
836 infcx: &'a InferCtxt<'a, 'tcx>,
837 param_env: ty::ParamEnv<'tcx>,
839 body: &'a Body<'tcx>,
840 /// User type annotations are shared between the main MIR and the MIR of
841 /// all of the promoted items.
842 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
844 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
845 implicit_region_bound: ty::Region<'tcx>,
846 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
847 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
848 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
851 struct BorrowCheckContext<'a, 'tcx> {
852 universal_regions: &'a UniversalRegions<'tcx>,
853 location_table: &'a LocationTable,
854 all_facts: &'a mut Option<AllFacts>,
855 borrow_set: &'a BorrowSet<'tcx>,
856 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
859 crate struct MirTypeckResults<'tcx> {
860 crate constraints: MirTypeckRegionConstraints<'tcx>,
861 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
864 /// A collection of region constraints that must be satisfied for the
865 /// program to be considered well-typed.
866 crate struct MirTypeckRegionConstraints<'tcx> {
867 /// Maps from a `ty::Placeholder` to the corresponding
868 /// `PlaceholderIndex` bit that we will use for it.
870 /// To keep everything in sync, do not insert this set
871 /// directly. Instead, use the `placeholder_region` helper.
872 crate placeholder_indices: PlaceholderIndices,
874 /// Each time we add a placeholder to `placeholder_indices`, we
875 /// also create a corresponding "representative" region vid for
876 /// that wraps it. This vector tracks those. This way, when we
877 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
878 /// the same underlying `RegionVid`.
879 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
881 /// In general, the type-checker is not responsible for enforcing
882 /// liveness constraints; this job falls to the region inferencer,
883 /// which performs a liveness analysis. However, in some limited
884 /// cases, the MIR type-checker creates temporary regions that do
885 /// not otherwise appear in the MIR -- in particular, the
886 /// late-bound regions that it instantiates at call-sites -- and
887 /// hence it must report on their liveness constraints.
888 crate liveness_constraints: LivenessValues<RegionVid>,
890 crate outlives_constraints: OutlivesConstraintSet,
892 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
894 crate closure_bounds_mapping:
895 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
897 crate type_tests: Vec<TypeTest<'tcx>>,
900 impl MirTypeckRegionConstraints<'tcx> {
901 fn placeholder_region(
903 infcx: &InferCtxt<'_, 'tcx>,
904 placeholder: ty::PlaceholderRegion,
905 ) -> ty::Region<'tcx> {
906 let placeholder_index = self.placeholder_indices.insert(placeholder);
907 match self.placeholder_index_to_region.get(placeholder_index) {
910 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
911 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
912 self.placeholder_index_to_region.push(region);
919 /// The `Locations` type summarizes *where* region constraints are
920 /// required to hold. Normally, this is at a particular point which
921 /// created the obligation, but for constraints that the user gave, we
922 /// want the constraint to hold at all points.
923 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
925 /// Indicates that a type constraint should always be true. This
926 /// is particularly important in the new borrowck analysis for
927 /// things like the type of the return slot. Consider this
931 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
933 /// return &y; // error
937 /// Here, we wind up with the signature from the return type being
938 /// something like `&'1 u32` where `'1` is a universal region. But
939 /// the type of the return slot `_0` is something like `&'2 u32`
940 /// where `'2` is an existential region variable. The type checker
941 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
942 /// older NLL analysis, we required this only at the entry point
943 /// to the function. By the nature of the constraints, this wound
944 /// up propagating to all points reachable from start (because
945 /// `'1` -- as a universal region -- is live everywhere). In the
946 /// newer analysis, though, this doesn't work: `_0` is considered
947 /// dead at the start (it has no usable value) and hence this type
948 /// equality is basically a no-op. Then, later on, when we do `_0
949 /// = &'3 y`, that region `'3` never winds up related to the
950 /// universal region `'1` and hence no error occurs. Therefore, we
951 /// use Locations::All instead, which ensures that the `'1` and
952 /// `'2` are equal everything. We also use this for other
953 /// user-given type annotations; e.g., if the user wrote `let mut
954 /// x: &'static u32 = ...`, we would ensure that all values
955 /// assigned to `x` are of `'static` lifetime.
957 /// The span points to the place the constraint arose. For example,
958 /// it points to the type in a user-given type annotation. If
959 /// there's no sensible span then it's DUMMY_SP.
962 /// An outlives constraint that only has to hold at a single location,
963 /// usually it represents a point where references flow from one spot to
964 /// another (e.g., `x = y`)
969 pub fn from_location(&self) -> Option<Location> {
971 Locations::All(_) => None,
972 Locations::Single(from_location) => Some(*from_location),
976 /// Gets a span representing the location.
977 pub fn span(&self, body: &Body<'_>) -> Span {
979 Locations::All(span) => *span,
980 Locations::Single(l) => body.source_info(*l).span,
985 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
987 infcx: &'a InferCtxt<'a, 'tcx>,
988 body: &'a Body<'tcx>,
990 param_env: ty::ParamEnv<'tcx>,
991 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
992 implicit_region_bound: ty::Region<'tcx>,
993 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
994 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
996 let mut checker = Self {
1001 user_type_annotations: &body.user_type_annotations,
1004 implicit_region_bound,
1006 reported_errors: Default::default(),
1007 universal_region_relations,
1009 checker.check_user_type_annotations();
1013 /// Equate the inferred type and the annotated type for user type annotations
1014 fn check_user_type_annotations(&mut self) {
1016 "check_user_type_annotations: user_type_annotations={:?}",
1017 self.user_type_annotations
1019 for user_annotation in self.user_type_annotations {
1020 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1021 let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
1025 UserType::Ty(mut ty) => {
1026 ty = self.normalize(ty, Locations::All(span));
1028 if let Err(terr) = self.eq_types(
1031 Locations::All(span),
1032 ConstraintCategory::BoringNoLocation,
1037 "bad user type ({:?} = {:?}): {:?}",
1044 self.prove_predicate(
1045 ty::Predicate::WellFormed(inferred_ty),
1046 Locations::All(span),
1047 ConstraintCategory::TypeAnnotation,
1050 UserType::TypeOf(def_id, user_substs) => {
1051 if let Err(terr) = self.fully_perform_op(
1052 Locations::All(span),
1053 ConstraintCategory::BoringNoLocation,
1054 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1055 inferred_ty, def_id, user_substs,
1061 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1073 /// Given some operation `op` that manipulates types, proves
1074 /// predicates, or otherwise uses the inference context, executes
1075 /// `op` and then executes all the further obligations that `op`
1076 /// returns. This will yield a set of outlives constraints amongst
1077 /// regions which are extracted and stored as having occurred at
1080 /// **Any `rustc::infer` operations that might generate region
1081 /// constraints should occur within this method so that those
1082 /// constraints can be properly localized!**
1083 fn fully_perform_op<R>(
1085 locations: Locations,
1086 category: ConstraintCategory,
1087 op: impl type_op::TypeOp<'tcx, Output = R>,
1089 let (r, opt_data) = op.fully_perform(self.infcx)?;
1091 if let Some(data) = &opt_data {
1092 self.push_region_constraints(locations, category, data);
1098 fn push_region_constraints(
1100 locations: Locations,
1101 category: ConstraintCategory,
1102 data: &QueryRegionConstraints<'tcx>,
1105 "push_region_constraints: constraints generated at {:?} are {:#?}",
1109 constraint_conversion::ConstraintConversion::new(
1111 self.borrowck_context.universal_regions,
1112 self.region_bound_pairs,
1113 Some(self.implicit_region_bound),
1117 &mut self.borrowck_context.constraints,
1118 ).convert_all(data);
1121 /// Convenient wrapper around `relate_tys::relate_types` -- see
1122 /// that fn for docs.
1128 locations: Locations,
1129 category: ConstraintCategory,
1131 relate_tys::relate_types(
1138 Some(self.borrowck_context),
1146 locations: Locations,
1147 category: ConstraintCategory,
1149 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1152 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1153 /// variables in `sub` with their inferred definitions and try
1154 /// again. This is used for opaque types in places (e.g., `let x:
1155 /// impl Foo = ..`).
1156 fn sub_types_or_anon(
1160 locations: Locations,
1161 category: ConstraintCategory,
1163 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1164 if let ty::Opaque(..) = sup.sty {
1165 // When you have `let x: impl Foo = ...` in a closure,
1166 // the resulting inferend values are stored with the
1167 // def-id of the base function.
1168 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1169 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1181 locations: Locations,
1182 category: ConstraintCategory,
1184 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1187 fn relate_type_and_user_type(
1191 user_ty: &UserTypeProjection,
1192 locations: Locations,
1193 category: ConstraintCategory,
1196 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1197 a, v, user_ty, locations,
1200 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1201 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1203 let tcx = self.infcx.tcx;
1205 for proj in &user_ty.projs {
1206 let projected_ty = curr_projected_ty.projection_ty_core(tcx, proj, |this, field, &()| {
1207 let ty = this.field_ty(tcx, field);
1208 self.normalize(ty, locations)
1210 curr_projected_ty = projected_ty;
1212 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1213 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1215 let ty = curr_projected_ty.ty;
1216 self.relate_types(a, v, ty, locations, category)?;
1221 fn eq_opaque_type_and_type(
1223 revealed_ty: Ty<'tcx>,
1225 anon_owner_def_id: DefId,
1226 locations: Locations,
1227 category: ConstraintCategory,
1230 "eq_opaque_type_and_type( \
1233 revealed_ty, anon_ty
1235 let infcx = self.infcx;
1236 let tcx = infcx.tcx;
1237 let param_env = self.param_env;
1238 let body = self.body;
1239 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1240 let opaque_type_map = self.fully_perform_op(
1245 let mut obligations = ObligationAccumulator::default();
1247 let dummy_body_id = ObligationCause::dummy().body_id;
1248 let (output_ty, opaque_type_map) =
1249 obligations.add(infcx.instantiate_opaque_types(
1254 locations.span(body),
1257 "eq_opaque_type_and_type: \
1258 instantiated output_ty={:?} \
1259 opaque_type_map={:#?} \
1261 output_ty, opaque_type_map, revealed_ty
1263 obligations.add(infcx
1264 .at(&ObligationCause::dummy(), param_env)
1265 .eq(output_ty, revealed_ty)?);
1267 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1268 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1269 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1270 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1272 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1273 opaque_decl.concrete_ty,
1274 infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty),
1277 obligations.add(infcx
1278 .at(&ObligationCause::dummy(), param_env)
1279 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1282 debug!("eq_opaque_type_and_type: equated");
1285 value: Some(opaque_type_map),
1286 obligations: obligations.into_vec(),
1289 || "input_output".to_string(),
1293 let universal_region_relations = self.universal_region_relations;
1295 // Finally, if we instantiated the anon types successfully, we
1296 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1297 // prove that `T: Iterator` where `T` is the type we
1298 // instantiated it with).
1299 if let Some(opaque_type_map) = opaque_type_map {
1300 for (opaque_def_id, opaque_decl) in opaque_type_map {
1301 self.fully_perform_op(
1303 ConstraintCategory::OpaqueType,
1306 infcx.constrain_opaque_type(
1309 universal_region_relations,
1313 obligations: vec![],
1316 || "opaque_type_map".to_string(),
1324 fn tcx(&self) -> TyCtxt<'tcx> {
1328 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1329 debug!("check_stmt: {:?}", stmt);
1330 let tcx = self.tcx();
1332 StatementKind::Assign(ref place, ref rv) => {
1333 // Assignments to temporaries are not "interesting";
1334 // they are not caused by the user, but rather artifacts
1335 // of lowering. Assignments to other sorts of places *are* interesting
1337 let category = match *place {
1338 Place::Base(PlaceBase::Local(RETURN_PLACE)) => if let BorrowCheckContext {
1341 defining_ty: DefiningTy::Const(def_id, _),
1345 } = self.borrowck_context
1347 if tcx.is_static(*def_id) {
1348 ConstraintCategory::UseAsStatic
1350 ConstraintCategory::UseAsConst
1353 ConstraintCategory::Return
1355 Place::Base(PlaceBase::Local(l))
1356 if !body.local_decls[l].is_user_variable.is_some() => {
1357 ConstraintCategory::Boring
1359 _ => ConstraintCategory::Assignment,
1362 let place_ty = place.ty(body, tcx).ty;
1363 let rv_ty = rv.ty(body, tcx);
1365 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1370 "bad assignment ({:?} = {:?}): {:?}",
1377 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1378 if let Err(terr) = self.relate_type_and_user_type(
1380 ty::Variance::Invariant,
1381 &UserTypeProjection { base: annotation_index, projs: vec![], },
1382 location.to_locations(),
1383 ConstraintCategory::Boring,
1385 let annotation = &self.user_type_annotations[annotation_index];
1389 "bad user type on rvalue ({:?} = {:?}): {:?}",
1397 self.check_rvalue(body, rv, location);
1398 if !self.tcx().features().unsized_locals {
1399 let trait_ref = ty::TraitRef {
1400 def_id: tcx.lang_items().sized_trait().unwrap(),
1401 substs: tcx.mk_substs_trait(place_ty, &[]),
1403 self.prove_trait_ref(
1405 location.to_locations(),
1406 ConstraintCategory::SizedBound,
1410 StatementKind::SetDiscriminant {
1414 let place_type = place.ty(body, tcx).ty;
1415 let adt = match place_type.sty {
1416 ty::Adt(adt, _) if adt.is_enum() => adt,
1419 stmt.source_info.span,
1420 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1426 if variant_index.as_usize() >= adt.variants.len() {
1428 stmt.source_info.span,
1429 "bad set discriminant ({:?} = {:?}): value of of range",
1435 StatementKind::AscribeUserType(ref place, variance, box ref projection) => {
1436 let place_ty = place.ty(body, tcx).ty;
1437 if let Err(terr) = self.relate_type_and_user_type(
1441 Locations::All(stmt.source_info.span),
1442 ConstraintCategory::TypeAnnotation,
1444 let annotation = &self.user_type_annotations[projection.base];
1448 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1456 StatementKind::FakeRead(..)
1457 | StatementKind::StorageLive(..)
1458 | StatementKind::StorageDead(..)
1459 | StatementKind::InlineAsm { .. }
1460 | StatementKind::Retag { .. }
1461 | StatementKind::Nop => {}
1465 fn check_terminator(
1468 term: &Terminator<'tcx>,
1469 term_location: Location,
1471 debug!("check_terminator: {:?}", term);
1472 let tcx = self.tcx();
1474 TerminatorKind::Goto { .. }
1475 | TerminatorKind::Resume
1476 | TerminatorKind::Abort
1477 | TerminatorKind::Return
1478 | TerminatorKind::GeneratorDrop
1479 | TerminatorKind::Unreachable
1480 | TerminatorKind::Drop { .. }
1481 | TerminatorKind::FalseEdges { .. }
1482 | TerminatorKind::FalseUnwind { .. } => {
1483 // no checks needed for these
1486 TerminatorKind::DropAndReplace {
1492 let place_ty = location.ty(body, tcx).ty;
1493 let rv_ty = value.ty(body, tcx);
1495 let locations = term_location.to_locations();
1497 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1502 "bad DropAndReplace ({:?} = {:?}): {:?}",
1509 TerminatorKind::SwitchInt {
1514 let discr_ty = discr.ty(body, tcx);
1515 if let Err(terr) = self.sub_types(
1518 term_location.to_locations(),
1519 ConstraintCategory::Assignment,
1524 "bad SwitchInt ({:?} on {:?}): {:?}",
1530 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1531 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1533 // FIXME: check the values
1535 TerminatorKind::Call {
1542 let func_ty = func.ty(body, tcx);
1543 debug!("check_terminator: call, func_ty={:?}", func_ty);
1544 let sig = match func_ty.sty {
1545 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1547 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1551 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1552 term.source_info.span,
1553 LateBoundRegionConversionTime::FnCall,
1556 let sig = self.normalize(sig, term_location);
1557 self.check_call_dest(body, term, &sig, destination, term_location);
1559 self.prove_predicates(
1560 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1561 term_location.to_locations(),
1562 ConstraintCategory::Boring,
1565 // The ordinary liveness rules will ensure that all
1566 // regions in the type of the callee are live here. We
1567 // then further constrain the late-bound regions that
1568 // were instantiated at the call site to be live as
1569 // well. The resulting is that all the input (and
1570 // output) types in the signature must be live, since
1571 // all the inputs that fed into it were live.
1572 for &late_bound_region in map.values() {
1573 let region_vid = self.borrowck_context
1575 .to_region_vid(late_bound_region);
1576 self.borrowck_context
1578 .liveness_constraints
1579 .add_element(region_vid, term_location);
1582 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1584 TerminatorKind::Assert {
1585 ref cond, ref msg, ..
1587 let cond_ty = cond.ty(body, tcx);
1588 if cond_ty != tcx.types.bool {
1589 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1592 if let BoundsCheck { ref len, ref index } = *msg {
1593 if len.ty(body, tcx) != tcx.types.usize {
1594 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1596 if index.ty(body, tcx) != tcx.types.usize {
1597 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1601 TerminatorKind::Yield { ref value, .. } => {
1602 let value_ty = value.ty(body, tcx);
1603 match body.yield_ty {
1604 None => span_mirbug!(self, term, "yield in non-generator"),
1606 if let Err(terr) = self.sub_types(
1609 term_location.to_locations(),
1610 ConstraintCategory::Yield,
1615 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1630 term: &Terminator<'tcx>,
1631 sig: &ty::FnSig<'tcx>,
1632 destination: &Option<(Place<'tcx>, BasicBlock)>,
1633 term_location: Location,
1635 let tcx = self.tcx();
1636 match *destination {
1637 Some((ref dest, _target_block)) => {
1638 let dest_ty = dest.ty(body, tcx).ty;
1639 let category = match *dest {
1640 Place::Base(PlaceBase::Local(RETURN_PLACE)) => {
1641 if let BorrowCheckContext {
1644 defining_ty: DefiningTy::Const(def_id, _),
1648 } = self.borrowck_context
1650 if tcx.is_static(*def_id) {
1651 ConstraintCategory::UseAsStatic
1653 ConstraintCategory::UseAsConst
1656 ConstraintCategory::Return
1659 Place::Base(PlaceBase::Local(l))
1660 if !body.local_decls[l].is_user_variable.is_some() => {
1661 ConstraintCategory::Boring
1663 _ => ConstraintCategory::Assignment,
1666 let locations = term_location.to_locations();
1669 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1674 "call dest mismatch ({:?} <- {:?}): {:?}",
1681 // When `#![feature(unsized_locals)]` is not enabled,
1682 // this check is done at `check_local`.
1683 if self.tcx().features().unsized_locals {
1684 let span = term.source_info.span;
1685 self.ensure_place_sized(dest_ty, span);
1689 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1690 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1696 fn check_call_inputs(
1699 term: &Terminator<'tcx>,
1700 sig: &ty::FnSig<'tcx>,
1701 args: &[Operand<'tcx>],
1702 term_location: Location,
1703 from_hir_call: bool,
1705 debug!("check_call_inputs({:?}, {:?})", sig, args);
1706 // Do not count the `VaListImpl` argument as a "true" argument to
1707 // a C-variadic function.
1708 let inputs = if sig.c_variadic {
1709 &sig.inputs()[..sig.inputs().len() - 1]
1713 if args.len() < inputs.len() || (args.len() > inputs.len() && !sig.c_variadic) {
1714 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1716 for (n, (fn_arg, op_arg)) in inputs.iter().zip(args).enumerate() {
1717 let op_arg_ty = op_arg.ty(body, self.tcx());
1718 let category = if from_hir_call {
1719 ConstraintCategory::CallArgument
1721 ConstraintCategory::Boring
1724 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1729 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1739 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1740 let is_cleanup = block_data.is_cleanup;
1741 self.last_span = block_data.terminator().source_info.span;
1742 match block_data.terminator().kind {
1743 TerminatorKind::Goto { target } => {
1744 self.assert_iscleanup(body, block_data, target, is_cleanup)
1746 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1747 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1749 TerminatorKind::Resume => if !is_cleanup {
1750 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1752 TerminatorKind::Abort => if !is_cleanup {
1753 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1755 TerminatorKind::Return => if is_cleanup {
1756 span_mirbug!(self, block_data, "return on cleanup block")
1758 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1759 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1761 TerminatorKind::Yield { resume, drop, .. } => {
1763 span_mirbug!(self, block_data, "yield in cleanup block")
1765 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1766 if let Some(drop) = drop {
1767 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1770 TerminatorKind::Unreachable => {}
1771 TerminatorKind::Drop { target, unwind, .. }
1772 | TerminatorKind::DropAndReplace { target, unwind, .. }
1773 | TerminatorKind::Assert {
1778 self.assert_iscleanup(body, block_data, target, is_cleanup);
1779 if let Some(unwind) = unwind {
1781 span_mirbug!(self, block_data, "unwind on cleanup block")
1783 self.assert_iscleanup(body, block_data, unwind, true);
1786 TerminatorKind::Call {
1791 if let &Some((_, target)) = destination {
1792 self.assert_iscleanup(body, block_data, target, is_cleanup);
1794 if let Some(cleanup) = cleanup {
1796 span_mirbug!(self, block_data, "cleanup on cleanup block")
1798 self.assert_iscleanup(body, block_data, cleanup, true);
1801 TerminatorKind::FalseEdges {
1805 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1806 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1808 TerminatorKind::FalseUnwind {
1812 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1813 if let Some(unwind) = unwind {
1818 "cleanup in cleanup block via false unwind"
1821 self.assert_iscleanup(body, block_data, unwind, true);
1827 fn assert_iscleanup(
1830 ctxt: &dyn fmt::Debug,
1834 if body[bb].is_cleanup != iscleanuppad {
1838 "cleanuppad mismatch: {:?} should be {:?}",
1845 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1846 match body.local_kind(local) {
1847 LocalKind::ReturnPointer | LocalKind::Arg => {
1848 // return values of normal functions are required to be
1849 // sized by typeck, but return values of ADT constructors are
1850 // not because we don't include a `Self: Sized` bounds on them.
1852 // Unbound parts of arguments were never required to be Sized
1853 // - maybe we should make that a warning.
1856 LocalKind::Var | LocalKind::Temp => {}
1859 // When `#![feature(unsized_locals)]` is enabled, only function calls
1860 // and nullary ops are checked in `check_call_dest`.
1861 if !self.tcx().features().unsized_locals {
1862 let span = local_decl.source_info.span;
1863 let ty = local_decl.ty;
1864 self.ensure_place_sized(ty, span);
1868 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1869 let tcx = self.tcx();
1871 // Erase the regions from `ty` to get a global type. The
1872 // `Sized` bound in no way depends on precise regions, so this
1873 // shouldn't affect `is_sized`.
1874 let gcx = tcx.global_tcx();
1875 let erased_ty = tcx.erase_regions(&ty);
1876 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1877 // in current MIR construction, all non-control-flow rvalue
1878 // expressions evaluate through `as_temp` or `into` a return
1879 // slot or local, so to find all unsized rvalues it is enough
1880 // to check all temps, return slots and locals.
1881 if let None = self.reported_errors.replace((ty, span)) {
1882 let mut diag = struct_span_err!(
1886 "cannot move a value of type {0}: the size of {0} \
1887 cannot be statically determined",
1891 // While this is located in `nll::typeck` this error is not
1892 // an NLL error, it's a required check to prevent creation
1893 // of unsized rvalues in certain cases:
1894 // * operand of a box expression
1895 // * callee in a call expression
1901 fn aggregate_field_ty(
1903 ak: &AggregateKind<'tcx>,
1906 ) -> Result<Ty<'tcx>, FieldAccessError> {
1907 let tcx = self.tcx();
1910 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1911 let variant = &def.variants[variant_index];
1912 let adj_field_index = active_field_index.unwrap_or(field_index);
1913 if let Some(field) = variant.fields.get(adj_field_index) {
1914 Ok(self.normalize(field.ty(tcx, substs), location))
1916 Err(FieldAccessError::OutOfRange {
1917 field_count: variant.fields.len(),
1921 AggregateKind::Closure(def_id, substs) => {
1922 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1924 None => Err(FieldAccessError::OutOfRange {
1925 field_count: substs.upvar_tys(def_id, tcx).count(),
1929 AggregateKind::Generator(def_id, substs, _) => {
1930 // It doesn't make sense to look at a field beyond the prefix;
1931 // these require a variant index, and are not initialized in
1932 // aggregate rvalues.
1933 match substs.prefix_tys(def_id, tcx).nth(field_index) {
1935 None => Err(FieldAccessError::OutOfRange {
1936 field_count: substs.prefix_tys(def_id, tcx).count(),
1940 AggregateKind::Array(ty) => Ok(ty),
1941 AggregateKind::Tuple => {
1942 unreachable!("This should have been covered in check_rvalues");
1947 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1948 let tcx = self.tcx();
1951 Rvalue::Aggregate(ak, ops) => {
1952 self.check_aggregate_rvalue(body, rvalue, ak, ops, location)
1955 Rvalue::Repeat(operand, len) => if *len > 1 {
1956 let operand_ty = operand.ty(body, tcx);
1958 let trait_ref = ty::TraitRef {
1959 def_id: tcx.lang_items().copy_trait().unwrap(),
1960 substs: tcx.mk_substs_trait(operand_ty, &[]),
1963 self.prove_trait_ref(
1965 location.to_locations(),
1966 ConstraintCategory::CopyBound,
1970 Rvalue::NullaryOp(_, ty) => {
1971 // Even with unsized locals cannot box an unsized value.
1972 if self.tcx().features().unsized_locals {
1973 let span = body.source_info(location).span;
1974 self.ensure_place_sized(ty, span);
1977 let trait_ref = ty::TraitRef {
1978 def_id: tcx.lang_items().sized_trait().unwrap(),
1979 substs: tcx.mk_substs_trait(ty, &[]),
1982 self.prove_trait_ref(
1984 location.to_locations(),
1985 ConstraintCategory::SizedBound,
1989 Rvalue::Cast(cast_kind, op, ty) => {
1991 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1992 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1994 // The type that we see in the fcx is like
1995 // `foo::<'a, 'b>`, where `foo` is the path to a
1996 // function definition. When we extract the
1997 // signature, it comes from the `fn_sig` query,
1998 // and hence may contain unnormalized results.
1999 let fn_sig = self.normalize(fn_sig, location);
2001 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2003 if let Err(terr) = self.eq_types(
2006 location.to_locations(),
2007 ConstraintCategory::Cast,
2012 "equating {:?} with {:?} yields {:?}",
2020 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2021 let sig = match op.ty(body, tcx).sty {
2022 ty::Closure(def_id, substs) => {
2023 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
2027 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2029 if let Err(terr) = self.eq_types(
2032 location.to_locations(),
2033 ConstraintCategory::Cast,
2038 "equating {:?} with {:?} yields {:?}",
2046 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2047 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2049 // The type that we see in the fcx is like
2050 // `foo::<'a, 'b>`, where `foo` is the path to a
2051 // function definition. When we extract the
2052 // signature, it comes from the `fn_sig` query,
2053 // and hence may contain unnormalized results.
2054 let fn_sig = self.normalize(fn_sig, location);
2056 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2058 if let Err(terr) = self.eq_types(
2061 location.to_locations(),
2062 ConstraintCategory::Cast,
2067 "equating {:?} with {:?} yields {:?}",
2075 CastKind::Pointer(PointerCast::Unsize) => {
2077 let trait_ref = ty::TraitRef {
2078 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2079 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2082 self.prove_trait_ref(
2084 location.to_locations(),
2085 ConstraintCategory::Cast,
2089 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2090 let ty_from = match op.ty(body, tcx).sty {
2091 ty::RawPtr(ty::TypeAndMut {
2093 mutbl: hir::MutMutable,
2099 "unexpected base type for cast {:?}",
2105 let ty_to = match ty.sty {
2106 ty::RawPtr(ty::TypeAndMut {
2108 mutbl: hir::MutImmutable,
2114 "unexpected target type for cast {:?}",
2120 if let Err(terr) = self.sub_types(
2123 location.to_locations(),
2124 ConstraintCategory::Cast,
2129 "relating {:?} with {:?} yields {:?}",
2138 if let ty::Ref(_, mut ty_from, _) = op.ty(body, tcx).sty {
2139 let (mut ty_to, mutability) = if let ty::RawPtr(ty::TypeAndMut {
2148 "invalid cast types {:?} -> {:?}",
2155 // Handle the direct cast from `&[T; N]` to `*const T` by unwrapping
2156 // any array we find.
2157 while let ty::Array(ty_elem_from, _) = ty_from.sty {
2158 ty_from = ty_elem_from;
2159 if let ty::Array(ty_elem_to, _) = ty_to.sty {
2166 if let hir::MutMutable = mutability {
2167 if let Err(terr) = self.eq_types(
2170 location.to_locations(),
2171 ConstraintCategory::Cast,
2176 "equating {:?} with {:?} yields {:?}",
2183 if let Err(terr) = self.sub_types(
2186 location.to_locations(),
2187 ConstraintCategory::Cast,
2192 "relating {:?} with {:?} yields {:?}",
2204 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2205 self.add_reborrow_constraint(body, location, region, borrowed_place);
2208 Rvalue::BinaryOp(BinOp::Eq, left, right)
2209 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2210 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2211 | Rvalue::BinaryOp(BinOp::Le, left, right)
2212 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2213 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2214 let ty_left = left.ty(body, tcx);
2215 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.sty {
2216 let ty_right = right.ty(body, tcx);
2217 let common_ty = self.infcx.next_ty_var(
2218 TypeVariableOrigin {
2219 kind: TypeVariableOriginKind::MiscVariable,
2220 span: body.source_info(location).span,
2226 location.to_locations(),
2227 ConstraintCategory::Boring
2228 ).unwrap_or_else(|err| {
2229 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2231 if let Err(terr) = self.sub_types(
2234 location.to_locations(),
2235 ConstraintCategory::Boring
2240 "unexpected comparison types {:?} and {:?} yields {:?}",
2251 | Rvalue::BinaryOp(..)
2252 | Rvalue::CheckedBinaryOp(..)
2253 | Rvalue::UnaryOp(..)
2254 | Rvalue::Discriminant(..) => {}
2258 /// If this rvalue supports a user-given type annotation, then
2259 /// extract and return it. This represents the final type of the
2260 /// rvalue and will be unified with the inferred type.
2261 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2264 | Rvalue::Repeat(..)
2268 | Rvalue::BinaryOp(..)
2269 | Rvalue::CheckedBinaryOp(..)
2270 | Rvalue::NullaryOp(..)
2271 | Rvalue::UnaryOp(..)
2272 | Rvalue::Discriminant(..) => None,
2274 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2275 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2276 AggregateKind::Array(_) => None,
2277 AggregateKind::Tuple => None,
2278 AggregateKind::Closure(_, _) => None,
2279 AggregateKind::Generator(_, _, _) => None,
2284 fn check_aggregate_rvalue(
2287 rvalue: &Rvalue<'tcx>,
2288 aggregate_kind: &AggregateKind<'tcx>,
2289 operands: &[Operand<'tcx>],
2292 let tcx = self.tcx();
2294 self.prove_aggregate_predicates(aggregate_kind, location);
2296 if *aggregate_kind == AggregateKind::Tuple {
2297 // tuple rvalue field type is always the type of the op. Nothing to check here.
2301 for (i, operand) in operands.iter().enumerate() {
2302 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2303 Ok(field_ty) => field_ty,
2304 Err(FieldAccessError::OutOfRange { field_count }) => {
2308 "accessed field #{} but variant only has {}",
2315 let operand_ty = operand.ty(body, tcx);
2317 if let Err(terr) = self.sub_types(
2320 location.to_locations(),
2321 ConstraintCategory::Boring,
2326 "{:?} is not a subtype of {:?}: {:?}",
2335 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2339 /// - `location`: the location `L` where the borrow expression occurs
2340 /// - `borrow_region`: the region `'a` associated with the borrow
2341 /// - `borrowed_place`: the place `P` being borrowed
2342 fn add_reborrow_constraint(
2346 borrow_region: ty::Region<'tcx>,
2347 borrowed_place: &Place<'tcx>,
2349 // These constraints are only meaningful during borrowck:
2350 let BorrowCheckContext {
2356 } = self.borrowck_context;
2358 // In Polonius mode, we also push a `borrow_region` fact
2359 // linking the loan to the region (in some cases, though,
2360 // there is no loan associated with this borrow expression --
2361 // that occurs when we are borrowing an unsafe place, for
2363 if let Some(all_facts) = all_facts {
2364 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2365 let region_vid = borrow_region.to_region_vid();
2366 all_facts.borrow_region.push((
2369 location_table.mid_index(location),
2374 // If we are reborrowing the referent of another reference, we
2375 // need to add outlives relationships. In a case like `&mut
2376 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2377 // need to ensure that `'b: 'a`.
2379 let mut borrowed_place = borrowed_place;
2382 "add_reborrow_constraint({:?}, {:?}, {:?})",
2383 location, borrow_region, borrowed_place
2385 while let Place::Projection(box Projection { base, elem }) = borrowed_place {
2386 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2389 ProjectionElem::Deref => {
2390 let tcx = self.infcx.tcx;
2391 let base_ty = base.ty(body, tcx).ty;
2393 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2395 ty::Ref(ref_region, _, mutbl) => {
2396 constraints.outlives_constraints.push(OutlivesConstraint {
2397 sup: ref_region.to_region_vid(),
2398 sub: borrow_region.to_region_vid(),
2399 locations: location.to_locations(),
2400 category: ConstraintCategory::Boring,
2404 hir::Mutability::MutImmutable => {
2405 // Immutable reference. We don't need the base
2406 // to be valid for the entire lifetime of
2410 hir::Mutability::MutMutable => {
2411 // Mutable reference. We *do* need the base
2412 // to be valid, because after the base becomes
2413 // invalid, someone else can use our mutable deref.
2415 // This is in order to make the following function
2418 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2423 // As otherwise you could clone `&mut T` using the
2424 // following function:
2426 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2427 // let my_clone = unsafe_deref(&'a x);
2436 // deref of raw pointer, guaranteed to be valid
2439 ty::Adt(def, _) if def.is_box() => {
2440 // deref of `Box`, need the base to be valid - propagate
2442 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2445 ProjectionElem::Field(..)
2446 | ProjectionElem::Downcast(..)
2447 | ProjectionElem::Index(..)
2448 | ProjectionElem::ConstantIndex { .. }
2449 | ProjectionElem::Subslice { .. } => {
2450 // other field access
2454 // The "propagate" case. We need to check that our base is valid
2455 // for the borrow's lifetime.
2456 borrowed_place = base;
2460 fn prove_aggregate_predicates(
2462 aggregate_kind: &AggregateKind<'tcx>,
2465 let tcx = self.tcx();
2468 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2469 aggregate_kind, location
2472 let instantiated_predicates = match aggregate_kind {
2473 AggregateKind::Adt(def, _, substs, _, _) => {
2474 tcx.predicates_of(def.did).instantiate(tcx, substs)
2477 // For closures, we have some **extra requirements** we
2479 // have to check. In particular, in their upvars and
2480 // signatures, closures often reference various regions
2481 // from the surrounding function -- we call those the
2482 // closure's free regions. When we borrow-check (and hence
2483 // region-check) closures, we may find that the closure
2484 // requires certain relationships between those free
2485 // regions. However, because those free regions refer to
2486 // portions of the CFG of their caller, the closure is not
2487 // in a position to verify those relationships. In that
2488 // case, the requirements get "propagated" to us, and so
2489 // we have to solve them here where we instantiate the
2492 // Despite the opacity of the previous parapgrah, this is
2493 // actually relatively easy to understand in terms of the
2494 // desugaring. A closure gets desugared to a struct, and
2495 // these extra requirements are basically like where
2496 // clauses on the struct.
2497 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2498 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2499 self.prove_closure_bounds(tcx, *def_id, substs, location)
2502 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2505 self.normalize_and_prove_instantiated_predicates(
2506 instantiated_predicates,
2507 location.to_locations(),
2511 fn prove_closure_bounds(
2515 substs: SubstsRef<'tcx>,
2517 ) -> ty::InstantiatedPredicates<'tcx> {
2518 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2519 let closure_constraints = QueryRegionConstraints {
2520 outlives: closure_region_requirements.apply_requirements(tcx, def_id, substs),
2522 // Presently, closures never propagate member
2523 // constraints to their parents -- they are enforced
2524 // locally. This is largely a non-issue as member
2525 // constraints only come from `-> impl Trait` and
2526 // friends which don't appear (thus far...) in
2528 member_constraints: vec![],
2531 let bounds_mapping = closure_constraints
2535 .filter_map(|(idx, constraint)| {
2536 let ty::OutlivesPredicate(k1, r2) =
2537 constraint.no_bound_vars().unwrap_or_else(|| {
2538 bug!("query_constraint {:?} contained bound vars", constraint,);
2542 UnpackedKind::Lifetime(r1) => {
2543 // constraint is r1: r2
2544 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2545 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2546 let outlives_requirements =
2547 &closure_region_requirements.outlives_requirements[idx];
2551 outlives_requirements.category,
2552 outlives_requirements.blame_span,
2556 UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2561 let existing = self.borrowck_context
2563 .closure_bounds_mapping
2564 .insert(location, bounds_mapping);
2567 "Multiple closures at the same location."
2570 self.push_region_constraints(
2571 location.to_locations(),
2572 ConstraintCategory::ClosureBounds,
2573 &closure_constraints,
2577 tcx.predicates_of(def_id).instantiate(tcx, substs)
2582 trait_ref: ty::TraitRef<'tcx>,
2583 locations: Locations,
2584 category: ConstraintCategory,
2586 self.prove_predicates(
2587 Some(ty::Predicate::Trait(
2588 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2595 fn normalize_and_prove_instantiated_predicates(
2597 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2598 locations: Locations,
2600 for predicate in instantiated_predicates.predicates {
2601 let predicate = self.normalize(predicate, locations);
2602 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2606 fn prove_predicates(
2608 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2609 locations: Locations,
2610 category: ConstraintCategory,
2612 for predicate in predicates {
2614 "prove_predicates(predicate={:?}, locations={:?})",
2615 predicate, locations,
2618 self.prove_predicate(predicate, locations, category);
2624 predicate: ty::Predicate<'tcx>,
2625 locations: Locations,
2626 category: ConstraintCategory,
2629 "prove_predicate(predicate={:?}, location={:?})",
2630 predicate, locations,
2633 let param_env = self.param_env;
2634 self.fully_perform_op(
2637 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2638 ).unwrap_or_else(|NoSolution| {
2639 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2643 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2644 self.last_span = body.span;
2645 debug!("run_on_mir: {:?}", body.span);
2647 for (local, local_decl) in body.local_decls.iter_enumerated() {
2648 self.check_local(body, local, local_decl);
2651 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2652 let mut location = Location {
2656 for stmt in &block_data.statements {
2657 if !stmt.source_info.span.is_dummy() {
2658 self.last_span = stmt.source_info.span;
2660 self.check_stmt(body, stmt, location);
2661 location.statement_index += 1;
2664 self.check_terminator(body, block_data.terminator(), location);
2665 self.check_iscleanup(body, block_data);
2669 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2671 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2673 debug!("normalize(value={:?}, location={:?})", value, location);
2674 let param_env = self.param_env;
2675 self.fully_perform_op(
2676 location.to_locations(),
2677 ConstraintCategory::Boring,
2678 param_env.and(type_op::normalize::Normalize::new(value)),
2679 ).unwrap_or_else(|NoSolution| {
2680 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2686 trait NormalizeLocation: fmt::Debug + Copy {
2687 fn to_locations(self) -> Locations;
2690 impl NormalizeLocation for Locations {
2691 fn to_locations(self) -> Locations {
2696 impl NormalizeLocation for Location {
2697 fn to_locations(self) -> Locations {
2698 Locations::Single(self)
2702 #[derive(Debug, Default)]
2703 struct ObligationAccumulator<'tcx> {
2704 obligations: PredicateObligations<'tcx>,
2707 impl<'tcx> ObligationAccumulator<'tcx> {
2708 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2709 let InferOk { value, obligations } = value;
2710 self.obligations.extend(obligations);
2714 fn into_vec(self) -> PredicateObligations<'tcx> {