1 //! This pass type-checks the MIR to ensure it is not broken.
4 use std::{fmt, iter, mem};
8 use hir::OpaqueTyOrigin;
9 use rustc_data_structures::frozen::Frozen;
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_data_structures::vec_map::VecMap;
13 use rustc_hir::def::DefKind;
14 use rustc_hir::def_id::LocalDefId;
15 use rustc_hir::lang_items::LangItem;
16 use rustc_index::vec::{Idx, IndexVec};
17 use rustc_infer::infer::canonical::QueryRegionConstraints;
18 use rustc_infer::infer::outlives::env::RegionBoundPairs;
19 use rustc_infer::infer::region_constraints::RegionConstraintData;
20 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
21 use rustc_infer::infer::{
22 InferCtxt, InferOk, LateBoundRegion, LateBoundRegionConversionTime, NllRegionVariableOrigin,
24 use rustc_infer::traits::ObligationCause;
25 use rustc_middle::mir::tcx::PlaceTy;
26 use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
27 use rustc_middle::mir::AssertKind;
28 use rustc_middle::mir::*;
29 use rustc_middle::ty::adjustment::PointerCast;
30 use rustc_middle::ty::cast::CastTy;
31 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef, UserSubsts};
32 use rustc_middle::ty::visit::TypeVisitable;
33 use rustc_middle::ty::{
34 self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, OpaqueHiddenType,
35 OpaqueTypeKey, RegionVid, ToPredicate, Ty, TyCtxt, UserType, UserTypeAnnotationIndex,
37 use rustc_span::def_id::CRATE_DEF_ID;
38 use rustc_span::{Span, DUMMY_SP};
39 use rustc_target::abi::VariantIdx;
40 use rustc_trait_selection::traits::query::type_op;
41 use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
42 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
43 use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
44 use rustc_trait_selection::traits::query::Fallible;
45 use rustc_trait_selection::traits::PredicateObligation;
47 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
48 use rustc_mir_dataflow::move_paths::MoveData;
49 use rustc_mir_dataflow::ResultsCursor;
51 use crate::session_diagnostics::MoveUnsized;
53 borrow_set::BorrowSet,
54 constraints::{OutlivesConstraint, OutlivesConstraintSet},
55 diagnostics::UniverseInfo,
57 location::LocationTable,
58 member_constraints::MemberConstraintSet,
61 region_infer::values::{
62 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
64 region_infer::{ClosureRegionRequirementsExt, TypeTest},
65 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
66 universal_regions::{DefiningTy, UniversalRegions},
70 macro_rules! span_mirbug {
71 ($context:expr, $elem:expr, $($message:tt)*) => ({
72 $crate::type_check::mirbug(
76 "broken MIR in {:?} ({:?}): {}",
77 $context.body().source.def_id(),
79 format_args!($($message)*),
85 macro_rules! span_mirbug_and_err {
86 ($context:expr, $elem:expr, $($message:tt)*) => ({
88 span_mirbug!($context, $elem, $($message)*);
95 mod constraint_conversion;
96 pub mod free_region_relations;
98 pub(crate) mod liveness;
101 /// Type checks the given `mir` in the context of the inference
102 /// context `infcx`. Returns any region constraints that have yet to
103 /// be proven. This result includes liveness constraints that
104 /// ensure that regions appearing in the types of all local variables
105 /// are live at all points where that local variable may later be
108 /// This phase of type-check ought to be infallible -- this is because
109 /// the original, HIR-based type-check succeeded. So if any errors
110 /// occur here, we will get a `bug!` reported.
114 /// - `infcx` -- inference context to use
115 /// - `param_env` -- parameter environment to use for trait solving
116 /// - `body` -- MIR body to type-check
117 /// - `promoted` -- map of promoted constants within `body`
118 /// - `universal_regions` -- the universal regions from `body`s function signature
119 /// - `location_table` -- MIR location map of `body`
120 /// - `borrow_set` -- information about borrows occurring in `body`
121 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
122 /// - `flow_inits` -- results of a maybe-init dataflow analysis
123 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
124 /// - `elements` -- MIR region map
125 pub(crate) fn type_check<'mir, 'tcx>(
126 infcx: &InferCtxt<'_, 'tcx>,
127 param_env: ty::ParamEnv<'tcx>,
129 promoted: &IndexVec<Promoted, Body<'tcx>>,
130 universal_regions: &Rc<UniversalRegions<'tcx>>,
131 location_table: &LocationTable,
132 borrow_set: &BorrowSet<'tcx>,
133 all_facts: &mut Option<AllFacts>,
134 flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
135 move_data: &MoveData<'tcx>,
136 elements: &Rc<RegionValueElements>,
137 upvars: &[Upvar<'tcx>],
139 ) -> MirTypeckResults<'tcx> {
140 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
141 let mut universe_causes = FxHashMap::default();
142 universe_causes.insert(ty::UniverseIndex::from_u32(0), UniverseInfo::other());
143 let mut constraints = MirTypeckRegionConstraints {
144 placeholder_indices: PlaceholderIndices::default(),
145 placeholder_index_to_region: IndexVec::default(),
146 liveness_constraints: LivenessValues::new(elements.clone()),
147 outlives_constraints: OutlivesConstraintSet::default(),
148 member_constraints: MemberConstraintSet::default(),
149 closure_bounds_mapping: Default::default(),
150 type_tests: Vec::default(),
155 universal_region_relations,
157 normalized_inputs_and_output,
158 } = free_region_relations::create(
161 implicit_region_bound,
166 debug!(?normalized_inputs_and_output);
168 for u in ty::UniverseIndex::ROOT..infcx.universe() {
169 let info = UniverseInfo::other();
170 constraints.universe_causes.insert(u, info);
173 let mut borrowck_context = BorrowCheckContext {
178 constraints: &mut constraints,
182 let opaque_type_values = type_check_internal(
188 implicit_region_bound,
189 &mut borrowck_context,
191 debug!("inside extra closure of type_check_internal");
192 cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
203 translate_outlives_facts(&mut cx);
204 let opaque_type_values =
205 infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
209 .map(|(opaque_type_key, decl)| {
211 Locations::All(body.span),
212 ConstraintCategory::OpaqueType,
215 infcx.register_member_constraints(
219 decl.hidden_type.span,
221 Ok(InferOk { value: (), obligations: vec![] })
223 || "opaque_type_map".to_string(),
227 let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
228 // Check that RPITs are only constrained in their outermost
229 // function, otherwise report a mismatched types error.
230 if let OpaqueTyOrigin::FnReturn(parent) | OpaqueTyOrigin::AsyncFn(parent)
231 = infcx.opaque_ty_origin_unchecked(opaque_type_key.def_id, hidden_type.span)
232 && parent.to_def_id() != body.source.def_id()
235 .report_mismatched_types(
236 &ObligationCause::misc(
238 infcx.tcx.hir().local_def_id_to_hir_id(
239 body.source.def_id().expect_local(),
242 infcx.tcx.mk_opaque(opaque_type_key.def_id.to_def_id(), opaque_type_key.substs),
244 ty::error::TypeError::Mismatch,
249 "finalized opaque type {:?} to {:#?}",
251 hidden_type.ty.kind()
253 if hidden_type.has_infer_types_or_consts() {
254 infcx.tcx.sess.delay_span_bug(
255 decl.hidden_type.span,
256 &format!("could not resolve {:#?}", hidden_type.ty.kind()),
258 hidden_type.ty = infcx.tcx.ty_error();
261 (opaque_type_key, (hidden_type, decl.origin))
267 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
271 skip(infcx, body, promoted, region_bound_pairs, borrowck_context, extra),
274 fn type_check_internal<'a, 'tcx, R>(
275 infcx: &'a InferCtxt<'a, 'tcx>,
276 param_env: ty::ParamEnv<'tcx>,
277 body: &'a Body<'tcx>,
278 promoted: &'a IndexVec<Promoted, Body<'tcx>>,
279 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
280 implicit_region_bound: ty::Region<'tcx>,
281 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
282 extra: impl FnOnce(TypeChecker<'a, 'tcx>) -> R,
284 debug!("body: {:#?}", body);
285 let mut checker = TypeChecker::new(
290 implicit_region_bound,
293 let errors_reported = {
294 let mut verifier = TypeVerifier::new(&mut checker, promoted);
295 verifier.visit_body(&body);
296 verifier.errors_reported
299 if !errors_reported {
300 // if verifier failed, don't do further checks to avoid ICEs
301 checker.typeck_mir(body);
307 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
308 let cx = &mut typeck.borrowck_context;
309 if let Some(facts) = cx.all_facts {
310 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
311 let location_table = cx.location_table;
312 facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
313 |constraint: &OutlivesConstraint<'_>| {
314 if let Some(from_location) = constraint.locations.from_location() {
315 Either::Left(iter::once((
318 location_table.mid_index(from_location),
324 .map(move |location| (constraint.sup, constraint.sub, location)),
333 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
334 // We sometimes see MIR failures (notably predicate failures) due to
335 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
336 // to avoid reporting bugs in those cases.
337 tcx.sess.diagnostic().delay_span_bug(span, msg);
340 enum FieldAccessError {
341 OutOfRange { field_count: usize },
344 /// Verifies that MIR types are sane to not crash further checks.
346 /// The sanitize_XYZ methods here take an MIR object and compute its
347 /// type, calling `span_mirbug` and returning an error type if there
349 struct TypeVerifier<'a, 'b, 'tcx> {
350 cx: &'a mut TypeChecker<'b, 'tcx>,
351 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
353 errors_reported: bool,
356 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
357 fn visit_span(&mut self, span: Span) {
358 if !span.is_dummy() {
359 self.last_span = span;
363 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
364 self.sanitize_place(place, location, context);
367 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
368 self.super_constant(constant, location);
369 let ty = self.sanitize_type(constant, constant.literal.ty());
371 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
372 let live_region_vid =
373 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
377 .liveness_constraints
378 .add_element(live_region_vid, location);
381 // HACK(compiler-errors): Constants that are gathered into Body.required_consts
382 // have their locations erased...
383 let locations = if location != Location::START {
384 location.to_locations()
386 Locations::All(constant.span)
389 if let Some(annotation_index) = constant.user_ty {
390 if let Err(terr) = self.cx.relate_type_and_user_type(
391 constant.literal.ty(),
392 ty::Variance::Invariant,
393 &UserTypeProjection { base: annotation_index, projs: vec![] },
395 ConstraintCategory::Boring,
397 let annotation = &self.cx.user_type_annotations[annotation_index];
401 "bad constant user type {:?} vs {:?}: {:?}",
403 constant.literal.ty(),
408 let tcx = self.tcx();
409 let maybe_uneval = match constant.literal {
410 ConstantKind::Ty(ct) => match ct.kind() {
411 ty::ConstKind::Unevaluated(uv) => Some(uv),
416 if let Some(uv) = maybe_uneval {
417 if let Some(promoted) = uv.promoted {
418 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
419 promoted: &Body<'tcx>,
423 verifier.cx.eq_types(ty, san_ty, locations, ConstraintCategory::Boring)
428 "bad promoted type ({:?}: {:?}): {:?}",
436 if !self.errors_reported {
437 let promoted_body = &self.promoted[promoted];
438 self.sanitize_promoted(promoted_body, location);
440 let promoted_ty = promoted_body.return_ty();
441 check_err(self, promoted_body, ty, promoted_ty);
444 if let Err(terr) = self.cx.fully_perform_op(
446 ConstraintCategory::Boring,
447 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
448 constant.literal.ty(),
450 UserSubsts { substs: uv.substs, user_self_ty: None },
456 "bad constant type {:?} ({:?})",
462 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
463 let unnormalized_ty = tcx.type_of(static_def_id);
464 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
465 let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty;
467 if let Err(terr) = self.cx.eq_types(
471 ConstraintCategory::Boring,
473 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
477 if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() {
478 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
479 self.cx.normalize_and_prove_instantiated_predicates(
481 instantiated_predicates,
488 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
489 self.super_rvalue(rvalue, location);
490 let rval_ty = rvalue.ty(self.body(), self.tcx());
491 self.sanitize_type(rvalue, rval_ty);
494 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
495 self.super_local_decl(local, local_decl);
496 self.sanitize_type(local_decl, local_decl.ty);
498 if let Some(user_ty) = &local_decl.user_ty {
499 for (user_ty, span) in user_ty.projections_and_spans() {
500 let ty = if !local_decl.is_nonref_binding() {
501 // If we have a binding of the form `let ref x: T = ..`
502 // then remove the outermost reference so we can check the
503 // type annotation for the remaining type.
504 if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
507 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
513 if let Err(terr) = self.cx.relate_type_and_user_type(
515 ty::Variance::Invariant,
517 Locations::All(*span),
518 ConstraintCategory::TypeAnnotation,
523 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
534 fn visit_body(&mut self, body: &Body<'tcx>) {
535 self.sanitize_type(&"return type", body.return_ty());
536 for local_decl in &body.local_decls {
537 self.sanitize_type(local_decl, local_decl.ty);
539 if self.errors_reported {
542 self.super_body(body);
546 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
548 cx: &'a mut TypeChecker<'b, 'tcx>,
549 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
551 TypeVerifier { promoted, last_span: cx.body.span, cx, errors_reported: false }
554 fn body(&self) -> &Body<'tcx> {
558 fn tcx(&self) -> TyCtxt<'tcx> {
562 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
563 if ty.has_escaping_bound_vars() || ty.references_error() {
564 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
570 /// Checks that the types internal to the `place` match up with
571 /// what would be expected.
576 context: PlaceContext,
578 debug!("sanitize_place: {:?}", place);
580 let mut place_ty = PlaceTy::from_ty(self.body().local_decls[place.local].ty);
582 for elem in place.projection.iter() {
583 if place_ty.variant_index.is_none() {
584 if place_ty.ty.references_error() {
585 assert!(self.errors_reported);
586 return PlaceTy::from_ty(self.tcx().ty_error());
589 place_ty = self.sanitize_projection(place_ty, elem, place, location);
592 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
593 let tcx = self.tcx();
594 let trait_ref = ty::TraitRef {
595 def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
596 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
599 // To have a `Copy` operand, the type `T` of the
600 // value must be `Copy`. Note that we prove that `T: Copy`,
601 // rather than using the `is_copy_modulo_regions`
602 // test. This is important because
603 // `is_copy_modulo_regions` ignores the resulting region
604 // obligations and assumes they pass. This can result in
605 // bounds from `Copy` impls being unsoundly ignored (e.g.,
606 // #29149). Note that we decide to use `Copy` before knowing
607 // whether the bounds fully apply: in effect, the rule is
608 // that if a value of some type could implement `Copy`, then
610 self.cx.prove_trait_ref(
612 location.to_locations(),
613 ConstraintCategory::CopyBound,
620 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
621 // Determine the constraints from the promoted MIR by running the type
622 // checker on the promoted MIR, then transfer the constraints back to
623 // the main MIR, changing the locations to the provided location.
625 let parent_body = mem::replace(&mut self.cx.body, promoted_body);
627 // Use new sets of constraints and closure bounds so that we can
628 // modify their locations.
629 let all_facts = &mut None;
630 let mut constraints = Default::default();
631 let mut closure_bounds = Default::default();
632 let mut liveness_constraints =
633 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
634 // Don't try to add borrow_region facts for the promoted MIR
636 let mut swap_constraints = |this: &mut Self| {
637 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
639 &mut this.cx.borrowck_context.constraints.outlives_constraints,
643 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
647 &mut this.cx.borrowck_context.constraints.liveness_constraints,
648 &mut liveness_constraints,
652 swap_constraints(self);
654 self.visit_body(&promoted_body);
656 if !self.errors_reported {
657 // if verifier failed, don't do further checks to avoid ICEs
658 self.cx.typeck_mir(promoted_body);
661 self.cx.body = parent_body;
662 // Merge the outlives constraints back in, at the given location.
663 swap_constraints(self);
665 let locations = location.to_locations();
666 for constraint in constraints.outlives().iter() {
667 let mut constraint = constraint.clone();
668 constraint.locations = locations;
669 if let ConstraintCategory::Return(_)
670 | ConstraintCategory::UseAsConst
671 | ConstraintCategory::UseAsStatic = constraint.category
673 // "Returning" from a promoted is an assignment to a
674 // temporary from the user's point of view.
675 constraint.category = ConstraintCategory::Boring;
677 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
679 for region in liveness_constraints.rows() {
680 // If the region is live at at least one location in the promoted MIR,
681 // then add a liveness constraint to the main MIR for this region
682 // at the location provided as an argument to this method
683 if liveness_constraints.get_elements(region).next().is_some() {
687 .liveness_constraints
688 .add_element(region, location);
692 if !closure_bounds.is_empty() {
693 let combined_bounds_mapping =
694 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
699 .closure_bounds_mapping
700 .insert(location, combined_bounds_mapping);
701 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
705 fn sanitize_projection(
712 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
713 let tcx = self.tcx();
714 let base_ty = base.ty;
716 ProjectionElem::Deref => {
717 let deref_ty = base_ty.builtin_deref(true);
718 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
719 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
722 ProjectionElem::Index(i) => {
723 let index_ty = Place::from(i).ty(self.body(), tcx).ty;
724 if index_ty != tcx.types.usize {
725 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
727 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
728 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
732 ProjectionElem::ConstantIndex { .. } => {
733 // consider verifying in-bounds
734 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
735 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
738 ProjectionElem::Subslice { from, to, from_end } => {
739 PlaceTy::from_ty(match base_ty.kind() {
740 ty::Array(inner, _) => {
741 assert!(!from_end, "array subslices should not use from_end");
742 tcx.mk_array(*inner, to - from)
745 assert!(from_end, "slice subslices should use from_end");
748 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
751 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
752 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
753 if index.as_usize() >= adt_def.variants().len() {
754 PlaceTy::from_ty(span_mirbug_and_err!(
757 "cast to variant #{:?} but enum only has {:?}",
759 adt_def.variants().len()
762 PlaceTy { ty: base_ty, variant_index: Some(index) }
765 // We do not need to handle generators here, because this runs
766 // before the generator transform stage.
768 let ty = if let Some(name) = maybe_name {
769 span_mirbug_and_err!(
772 "can't downcast {:?} as {:?}",
777 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
782 ProjectionElem::Field(field, fty) => {
783 let fty = self.sanitize_type(place, fty);
784 let fty = self.cx.normalize(fty, location);
785 match self.field_ty(place, base, field, location) {
787 let ty = self.cx.normalize(ty, location);
788 if let Err(terr) = self.cx.eq_types(
791 location.to_locations(),
792 ConstraintCategory::Boring,
797 "bad field access ({:?}: {:?}): {:?}",
804 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
807 "accessed field #{} but variant only has {}",
812 PlaceTy::from_ty(fty)
817 fn error(&mut self) -> Ty<'tcx> {
818 self.errors_reported = true;
819 self.tcx().ty_error()
824 parent: &dyn fmt::Debug,
825 base_ty: PlaceTy<'tcx>,
828 ) -> Result<Ty<'tcx>, FieldAccessError> {
829 let tcx = self.tcx();
831 let (variant, substs) = match base_ty {
832 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
833 ty::Adt(adt_def, substs) => (adt_def.variant(variant_index), substs),
834 ty::Generator(def_id, substs, _) => {
835 let mut variants = substs.as_generator().state_tys(def_id, tcx);
836 let Some(mut variant) = variants.nth(variant_index.into()) else {
838 "variant_index of generator out of range: {:?}/{:?}",
840 substs.as_generator().state_tys(def_id, tcx).count()
843 return match variant.nth(field.index()) {
845 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
848 _ => bug!("can't have downcast of non-adt non-generator type"),
850 PlaceTy { ty, variant_index: None } => match *ty.kind() {
851 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
852 (adt_def.variant(VariantIdx::new(0)), substs)
854 ty::Closure(_, substs) => {
862 None => Err(FieldAccessError::OutOfRange {
863 field_count: substs.as_closure().upvar_tys().count(),
867 ty::Generator(_, substs, _) => {
868 // Only prefix fields (upvars and current state) are
869 // accessible without a variant index.
870 return match substs.as_generator().prefix_tys().nth(field.index()) {
872 None => Err(FieldAccessError::OutOfRange {
873 field_count: substs.as_generator().prefix_tys().count(),
878 return match tys.get(field.index()) {
880 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
884 return Ok(span_mirbug_and_err!(
887 "can't project out of {:?}",
894 if let Some(field) = variant.fields.get(field.index()) {
895 Ok(self.cx.normalize(field.ty(tcx, substs), location))
897 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
902 /// The MIR type checker. Visits the MIR and enforces all the
903 /// constraints needed for it to be valid and well-typed. Along the
904 /// way, it accrues region constraints -- these can later be used by
905 /// NLL region checking.
906 struct TypeChecker<'a, 'tcx> {
907 infcx: &'a InferCtxt<'a, 'tcx>,
908 param_env: ty::ParamEnv<'tcx>,
910 body: &'a Body<'tcx>,
911 /// User type annotations are shared between the main MIR and the MIR of
912 /// all of the promoted items.
913 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
914 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
915 implicit_region_bound: ty::Region<'tcx>,
916 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
917 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
920 struct BorrowCheckContext<'a, 'tcx> {
921 pub(crate) universal_regions: &'a UniversalRegions<'tcx>,
922 location_table: &'a LocationTable,
923 all_facts: &'a mut Option<AllFacts>,
924 borrow_set: &'a BorrowSet<'tcx>,
925 pub(crate) constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
926 upvars: &'a [Upvar<'tcx>],
929 pub(crate) struct MirTypeckResults<'tcx> {
930 pub(crate) constraints: MirTypeckRegionConstraints<'tcx>,
931 pub(crate) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
932 pub(crate) opaque_type_values:
933 VecMap<OpaqueTypeKey<'tcx>, (OpaqueHiddenType<'tcx>, OpaqueTyOrigin)>,
936 /// A collection of region constraints that must be satisfied for the
937 /// program to be considered well-typed.
938 pub(crate) struct MirTypeckRegionConstraints<'tcx> {
939 /// Maps from a `ty::Placeholder` to the corresponding
940 /// `PlaceholderIndex` bit that we will use for it.
942 /// To keep everything in sync, do not insert this set
943 /// directly. Instead, use the `placeholder_region` helper.
944 pub(crate) placeholder_indices: PlaceholderIndices,
946 /// Each time we add a placeholder to `placeholder_indices`, we
947 /// also create a corresponding "representative" region vid for
948 /// that wraps it. This vector tracks those. This way, when we
949 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
950 /// the same underlying `RegionVid`.
951 pub(crate) placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
953 /// In general, the type-checker is not responsible for enforcing
954 /// liveness constraints; this job falls to the region inferencer,
955 /// which performs a liveness analysis. However, in some limited
956 /// cases, the MIR type-checker creates temporary regions that do
957 /// not otherwise appear in the MIR -- in particular, the
958 /// late-bound regions that it instantiates at call-sites -- and
959 /// hence it must report on their liveness constraints.
960 pub(crate) liveness_constraints: LivenessValues<RegionVid>,
962 pub(crate) outlives_constraints: OutlivesConstraintSet<'tcx>,
964 pub(crate) member_constraints: MemberConstraintSet<'tcx, RegionVid>,
966 pub(crate) closure_bounds_mapping:
967 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory<'tcx>, Span)>>,
969 pub(crate) universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
971 pub(crate) type_tests: Vec<TypeTest<'tcx>>,
974 impl<'tcx> MirTypeckRegionConstraints<'tcx> {
975 fn placeholder_region(
977 infcx: &InferCtxt<'_, 'tcx>,
978 placeholder: ty::PlaceholderRegion,
979 ) -> ty::Region<'tcx> {
980 let placeholder_index = self.placeholder_indices.insert(placeholder);
981 match self.placeholder_index_to_region.get(placeholder_index) {
984 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
985 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
986 self.placeholder_index_to_region.push(region);
993 /// The `Locations` type summarizes *where* region constraints are
994 /// required to hold. Normally, this is at a particular point which
995 /// created the obligation, but for constraints that the user gave, we
996 /// want the constraint to hold at all points.
997 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
999 /// Indicates that a type constraint should always be true. This
1000 /// is particularly important in the new borrowck analysis for
1001 /// things like the type of the return slot. Consider this
1004 /// ```compile_fail,E0515
1005 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
1007 /// return &y; // error
1011 /// Here, we wind up with the signature from the return type being
1012 /// something like `&'1 u32` where `'1` is a universal region. But
1013 /// the type of the return slot `_0` is something like `&'2 u32`
1014 /// where `'2` is an existential region variable. The type checker
1015 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
1016 /// older NLL analysis, we required this only at the entry point
1017 /// to the function. By the nature of the constraints, this wound
1018 /// up propagating to all points reachable from start (because
1019 /// `'1` -- as a universal region -- is live everywhere). In the
1020 /// newer analysis, though, this doesn't work: `_0` is considered
1021 /// dead at the start (it has no usable value) and hence this type
1022 /// equality is basically a no-op. Then, later on, when we do `_0
1023 /// = &'3 y`, that region `'3` never winds up related to the
1024 /// universal region `'1` and hence no error occurs. Therefore, we
1025 /// use Locations::All instead, which ensures that the `'1` and
1026 /// `'2` are equal everything. We also use this for other
1027 /// user-given type annotations; e.g., if the user wrote `let mut
1028 /// x: &'static u32 = ...`, we would ensure that all values
1029 /// assigned to `x` are of `'static` lifetime.
1031 /// The span points to the place the constraint arose. For example,
1032 /// it points to the type in a user-given type annotation. If
1033 /// there's no sensible span then it's DUMMY_SP.
1036 /// An outlives constraint that only has to hold at a single location,
1037 /// usually it represents a point where references flow from one spot to
1038 /// another (e.g., `x = y`)
1043 pub fn from_location(&self) -> Option<Location> {
1045 Locations::All(_) => None,
1046 Locations::Single(from_location) => Some(*from_location),
1050 /// Gets a span representing the location.
1051 pub fn span(&self, body: &Body<'_>) -> Span {
1053 Locations::All(span) => *span,
1054 Locations::Single(l) => body.source_info(*l).span,
1059 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1061 infcx: &'a InferCtxt<'a, 'tcx>,
1062 body: &'a Body<'tcx>,
1063 param_env: ty::ParamEnv<'tcx>,
1064 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1065 implicit_region_bound: ty::Region<'tcx>,
1066 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1068 let mut checker = Self {
1070 last_span: DUMMY_SP,
1072 user_type_annotations: &body.user_type_annotations,
1075 implicit_region_bound,
1077 reported_errors: Default::default(),
1079 checker.check_user_type_annotations();
1083 fn body(&self) -> &Body<'tcx> {
1087 fn unsized_feature_enabled(&self) -> bool {
1088 let features = self.tcx().features();
1089 features.unsized_locals || features.unsized_fn_params
1092 /// Equate the inferred type and the annotated type for user type annotations
1093 #[instrument(skip(self), level = "debug")]
1094 fn check_user_type_annotations(&mut self) {
1095 debug!(?self.user_type_annotations);
1096 for user_annotation in self.user_type_annotations {
1097 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1098 let inferred_ty = self.normalize(inferred_ty, Locations::All(span));
1099 let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1101 UserType::Ty(mut ty) => {
1102 ty = self.normalize(ty, Locations::All(span));
1104 if let Err(terr) = self.eq_types(
1107 Locations::All(span),
1108 ConstraintCategory::BoringNoLocation,
1113 "bad user type ({:?} = {:?}): {:?}",
1120 self.prove_predicate(
1121 ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into()))
1122 .to_predicate(self.tcx()),
1123 Locations::All(span),
1124 ConstraintCategory::TypeAnnotation,
1127 UserType::TypeOf(def_id, user_substs) => {
1128 if let Err(terr) = self.fully_perform_op(
1129 Locations::All(span),
1130 ConstraintCategory::BoringNoLocation,
1131 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1140 "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}",
1144 self.tcx().type_of(def_id),
1153 #[instrument(skip(self, data), level = "debug")]
1154 fn push_region_constraints(
1156 locations: Locations,
1157 category: ConstraintCategory<'tcx>,
1158 data: &QueryRegionConstraints<'tcx>,
1160 debug!("constraints generated: {:#?}", data);
1162 constraint_conversion::ConstraintConversion::new(
1164 self.borrowck_context.universal_regions,
1165 self.region_bound_pairs,
1166 self.implicit_region_bound,
1169 locations.span(self.body),
1171 &mut self.borrowck_context.constraints,
1176 /// Try to relate `sub <: sup`
1181 locations: Locations,
1182 category: ConstraintCategory<'tcx>,
1184 // Use this order of parameters because the sup type is usually the
1185 // "expected" type in diagnostics.
1186 self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
1189 #[instrument(skip(self, category), level = "debug")]
1194 locations: Locations,
1195 category: ConstraintCategory<'tcx>,
1197 self.relate_types(expected, ty::Variance::Invariant, found, locations, category)
1200 #[instrument(skip(self), level = "debug")]
1201 fn relate_type_and_user_type(
1205 user_ty: &UserTypeProjection,
1206 locations: Locations,
1207 category: ConstraintCategory<'tcx>,
1209 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1210 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1212 let tcx = self.infcx.tcx;
1214 for proj in &user_ty.projs {
1215 let projected_ty = curr_projected_ty.projection_ty_core(
1220 let ty = this.field_ty(tcx, field);
1221 self.normalize(ty, locations)
1224 curr_projected_ty = projected_ty;
1227 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1228 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1231 let ty = curr_projected_ty.ty;
1232 self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1237 fn tcx(&self) -> TyCtxt<'tcx> {
1241 #[instrument(skip(self, body, location), level = "debug")]
1242 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1243 let tcx = self.tcx();
1244 debug!("stmt kind: {:?}", stmt.kind);
1246 StatementKind::Assign(box (ref place, ref rv)) => {
1247 // Assignments to temporaries are not "interesting";
1248 // they are not caused by the user, but rather artifacts
1249 // of lowering. Assignments to other sorts of places *are* interesting
1251 let category = match place.as_local() {
1252 Some(RETURN_PLACE) => {
1253 let defining_ty = &self.borrowck_context.universal_regions.defining_ty;
1254 if defining_ty.is_const() {
1255 if tcx.is_static(defining_ty.def_id()) {
1256 ConstraintCategory::UseAsStatic
1258 ConstraintCategory::UseAsConst
1261 ConstraintCategory::Return(ReturnConstraint::Normal)
1266 body.local_decls[l].local_info,
1267 Some(box LocalInfo::AggregateTemp)
1270 ConstraintCategory::Usage
1272 Some(l) if !body.local_decls[l].is_user_variable() => {
1273 ConstraintCategory::Boring
1275 _ => ConstraintCategory::Assignment,
1278 "assignment category: {:?} {:?}",
1280 place.as_local().map(|l| &body.local_decls[l])
1283 let place_ty = place.ty(body, tcx).ty;
1285 let place_ty = self.normalize(place_ty, location);
1286 debug!("place_ty normalized: {:?}", place_ty);
1287 let rv_ty = rv.ty(body, tcx);
1289 let rv_ty = self.normalize(rv_ty, location);
1290 debug!("normalized rv_ty: {:?}", rv_ty);
1292 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1297 "bad assignment ({:?} = {:?}): {:?}",
1304 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1305 if let Err(terr) = self.relate_type_and_user_type(
1307 ty::Variance::Invariant,
1308 &UserTypeProjection { base: annotation_index, projs: vec![] },
1309 location.to_locations(),
1310 ConstraintCategory::Boring,
1312 let annotation = &self.user_type_annotations[annotation_index];
1316 "bad user type on rvalue ({:?} = {:?}): {:?}",
1324 self.check_rvalue(body, rv, location);
1325 if !self.unsized_feature_enabled() {
1326 let trait_ref = ty::TraitRef {
1327 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1328 substs: tcx.mk_substs_trait(place_ty, &[]),
1330 self.prove_trait_ref(
1332 location.to_locations(),
1333 ConstraintCategory::SizedBound,
1337 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1338 let place_ty = place.ty(body, tcx).ty;
1339 if let Err(terr) = self.relate_type_and_user_type(
1343 Locations::All(stmt.source_info.span),
1344 ConstraintCategory::TypeAnnotation,
1346 let annotation = &self.user_type_annotations[projection.base];
1350 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1358 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
1361 stmt.source_info.span,
1362 "Unexpected StatementKind::CopyNonOverlapping, should only appear after lowering_intrinsics",
1364 StatementKind::FakeRead(..)
1365 | StatementKind::StorageLive(..)
1366 | StatementKind::StorageDead(..)
1367 | StatementKind::Retag { .. }
1368 | StatementKind::Coverage(..)
1369 | StatementKind::Nop => {}
1370 StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
1371 bug!("Statement not allowed in this MIR phase")
1376 #[instrument(skip(self, body, term_location), level = "debug")]
1377 fn check_terminator(
1380 term: &Terminator<'tcx>,
1381 term_location: Location,
1383 let tcx = self.tcx();
1384 debug!("terminator kind: {:?}", term.kind);
1386 TerminatorKind::Goto { .. }
1387 | TerminatorKind::Resume
1388 | TerminatorKind::Abort
1389 | TerminatorKind::Return
1390 | TerminatorKind::GeneratorDrop
1391 | TerminatorKind::Unreachable
1392 | TerminatorKind::Drop { .. }
1393 | TerminatorKind::FalseEdge { .. }
1394 | TerminatorKind::FalseUnwind { .. }
1395 | TerminatorKind::InlineAsm { .. } => {
1396 // no checks needed for these
1399 TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1400 let place_ty = place.ty(body, tcx).ty;
1401 let rv_ty = value.ty(body, tcx);
1403 let locations = term_location.to_locations();
1405 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1410 "bad DropAndReplace ({:?} = {:?}): {:?}",
1417 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1418 self.check_operand(discr, term_location);
1420 let discr_ty = discr.ty(body, tcx);
1421 if let Err(terr) = self.sub_types(
1424 term_location.to_locations(),
1425 ConstraintCategory::Assignment,
1430 "bad SwitchInt ({:?} on {:?}): {:?}",
1436 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1437 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1439 // FIXME: check the values
1441 TerminatorKind::Call {
1449 self.check_operand(func, term_location);
1451 self.check_operand(arg, term_location);
1454 let func_ty = func.ty(body, tcx);
1455 debug!("func_ty.kind: {:?}", func_ty.kind());
1457 let sig = match func_ty.kind() {
1458 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1460 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1464 let (sig, map) = tcx.replace_late_bound_regions(sig, |br| {
1465 self.infcx.next_region_var(LateBoundRegion(
1466 term.source_info.span,
1468 LateBoundRegionConversionTime::FnCall,
1472 let sig = self.normalize(sig, term_location);
1473 self.check_call_dest(body, term, &sig, *destination, target, term_location);
1475 self.prove_predicates(
1476 sig.inputs_and_output
1478 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1479 term_location.to_locations(),
1480 ConstraintCategory::Boring,
1483 // The ordinary liveness rules will ensure that all
1484 // regions in the type of the callee are live here. We
1485 // then further constrain the late-bound regions that
1486 // were instantiated at the call site to be live as
1487 // well. The resulting is that all the input (and
1488 // output) types in the signature must be live, since
1489 // all the inputs that fed into it were live.
1490 for &late_bound_region in map.values() {
1492 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1493 self.borrowck_context
1495 .liveness_constraints
1496 .add_element(region_vid, term_location);
1499 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1501 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1502 self.check_operand(cond, term_location);
1504 let cond_ty = cond.ty(body, tcx);
1505 if cond_ty != tcx.types.bool {
1506 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1509 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1510 if len.ty(body, tcx) != tcx.types.usize {
1511 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1513 if index.ty(body, tcx) != tcx.types.usize {
1514 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1518 TerminatorKind::Yield { ref value, .. } => {
1519 self.check_operand(value, term_location);
1521 let value_ty = value.ty(body, tcx);
1522 match body.yield_ty() {
1523 None => span_mirbug!(self, term, "yield in non-generator"),
1525 if let Err(terr) = self.sub_types(
1528 term_location.to_locations(),
1529 ConstraintCategory::Yield,
1534 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1549 term: &Terminator<'tcx>,
1550 sig: &ty::FnSig<'tcx>,
1551 destination: Place<'tcx>,
1552 target: Option<BasicBlock>,
1553 term_location: Location,
1555 let tcx = self.tcx();
1558 let dest_ty = destination.ty(body, tcx).ty;
1559 let dest_ty = self.normalize(dest_ty, term_location);
1560 let category = match destination.as_local() {
1561 Some(RETURN_PLACE) => {
1562 if let BorrowCheckContext {
1566 DefiningTy::Const(def_id, _)
1567 | DefiningTy::InlineConst(def_id, _),
1571 } = self.borrowck_context
1573 if tcx.is_static(*def_id) {
1574 ConstraintCategory::UseAsStatic
1576 ConstraintCategory::UseAsConst
1579 ConstraintCategory::Return(ReturnConstraint::Normal)
1582 Some(l) if !body.local_decls[l].is_user_variable() => {
1583 ConstraintCategory::Boring
1585 _ => ConstraintCategory::Assignment,
1588 let locations = term_location.to_locations();
1590 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1594 "call dest mismatch ({:?} <- {:?}): {:?}",
1601 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1602 // this check is done at `check_local`.
1603 if self.unsized_feature_enabled() {
1604 let span = term.source_info.span;
1605 self.ensure_place_sized(dest_ty, span);
1611 .conservative_is_privately_uninhabited(self.param_env.and(sig.output()))
1613 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1619 fn check_call_inputs(
1622 term: &Terminator<'tcx>,
1623 sig: &ty::FnSig<'tcx>,
1624 args: &[Operand<'tcx>],
1625 term_location: Location,
1626 from_hir_call: bool,
1628 debug!("check_call_inputs({:?}, {:?})", sig, args);
1629 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1630 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1633 let func_ty = if let TerminatorKind::Call { func, .. } = &term.kind {
1634 Some(func.ty(body, self.infcx.tcx))
1640 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1641 let op_arg_ty = op_arg.ty(body, self.tcx());
1643 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1644 let category = if from_hir_call {
1645 ConstraintCategory::CallArgument(func_ty)
1647 ConstraintCategory::Boring
1650 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
1655 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1665 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1666 let is_cleanup = block_data.is_cleanup;
1667 self.last_span = block_data.terminator().source_info.span;
1668 match block_data.terminator().kind {
1669 TerminatorKind::Goto { target } => {
1670 self.assert_iscleanup(body, block_data, target, is_cleanup)
1672 TerminatorKind::SwitchInt { ref targets, .. } => {
1673 for target in targets.all_targets() {
1674 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1677 TerminatorKind::Resume => {
1679 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1682 TerminatorKind::Abort => {
1684 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1687 TerminatorKind::Return => {
1689 span_mirbug!(self, block_data, "return on cleanup block")
1692 TerminatorKind::GeneratorDrop { .. } => {
1694 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1697 TerminatorKind::Yield { resume, drop, .. } => {
1699 span_mirbug!(self, block_data, "yield in cleanup block")
1701 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1702 if let Some(drop) = drop {
1703 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1706 TerminatorKind::Unreachable => {}
1707 TerminatorKind::Drop { target, unwind, .. }
1708 | TerminatorKind::DropAndReplace { target, unwind, .. }
1709 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1710 self.assert_iscleanup(body, block_data, target, is_cleanup);
1711 if let Some(unwind) = unwind {
1713 span_mirbug!(self, block_data, "unwind on cleanup block")
1715 self.assert_iscleanup(body, block_data, unwind, true);
1718 TerminatorKind::Call { ref target, cleanup, .. } => {
1719 if let &Some(target) = target {
1720 self.assert_iscleanup(body, block_data, target, is_cleanup);
1722 if let Some(cleanup) = cleanup {
1724 span_mirbug!(self, block_data, "cleanup on cleanup block")
1726 self.assert_iscleanup(body, block_data, cleanup, true);
1729 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1730 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1731 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1733 TerminatorKind::FalseUnwind { real_target, unwind } => {
1734 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1735 if let Some(unwind) = unwind {
1737 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1739 self.assert_iscleanup(body, block_data, unwind, true);
1742 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
1743 if let Some(target) = destination {
1744 self.assert_iscleanup(body, block_data, target, is_cleanup);
1746 if let Some(cleanup) = cleanup {
1748 span_mirbug!(self, block_data, "cleanup on cleanup block")
1750 self.assert_iscleanup(body, block_data, cleanup, true);
1756 fn assert_iscleanup(
1759 ctxt: &dyn fmt::Debug,
1763 if body[bb].is_cleanup != iscleanuppad {
1764 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1768 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1769 match body.local_kind(local) {
1770 LocalKind::ReturnPointer | LocalKind::Arg => {
1771 // return values of normal functions are required to be
1772 // sized by typeck, but return values of ADT constructors are
1773 // not because we don't include a `Self: Sized` bounds on them.
1775 // Unbound parts of arguments were never required to be Sized
1776 // - maybe we should make that a warning.
1779 LocalKind::Var | LocalKind::Temp => {}
1782 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1783 // and nullary ops are checked in `check_call_dest`.
1784 if !self.unsized_feature_enabled() {
1785 let span = local_decl.source_info.span;
1786 let ty = local_decl.ty;
1787 self.ensure_place_sized(ty, span);
1791 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1792 let tcx = self.tcx();
1794 // Erase the regions from `ty` to get a global type. The
1795 // `Sized` bound in no way depends on precise regions, so this
1796 // shouldn't affect `is_sized`.
1797 let erased_ty = tcx.erase_regions(ty);
1798 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1799 // in current MIR construction, all non-control-flow rvalue
1800 // expressions evaluate through `as_temp` or `into` a return
1801 // slot or local, so to find all unsized rvalues it is enough
1802 // to check all temps, return slots and locals.
1803 if self.reported_errors.replace((ty, span)).is_none() {
1804 // While this is located in `nll::typeck` this error is not
1805 // an NLL error, it's a required check to prevent creation
1806 // of unsized rvalues in a call expression.
1807 self.tcx().sess.emit_err(MoveUnsized { ty, span });
1812 fn aggregate_field_ty(
1814 ak: &AggregateKind<'tcx>,
1817 ) -> Result<Ty<'tcx>, FieldAccessError> {
1818 let tcx = self.tcx();
1821 AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => {
1822 let def = tcx.adt_def(adt_did);
1823 let variant = &def.variant(variant_index);
1824 let adj_field_index = active_field_index.unwrap_or(field_index);
1825 if let Some(field) = variant.fields.get(adj_field_index) {
1826 Ok(self.normalize(field.ty(tcx, substs), location))
1828 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1831 AggregateKind::Closure(_, substs) => {
1832 match substs.as_closure().upvar_tys().nth(field_index) {
1834 None => Err(FieldAccessError::OutOfRange {
1835 field_count: substs.as_closure().upvar_tys().count(),
1839 AggregateKind::Generator(_, substs, _) => {
1840 // It doesn't make sense to look at a field beyond the prefix;
1841 // these require a variant index, and are not initialized in
1842 // aggregate rvalues.
1843 match substs.as_generator().prefix_tys().nth(field_index) {
1845 None => Err(FieldAccessError::OutOfRange {
1846 field_count: substs.as_generator().prefix_tys().count(),
1850 AggregateKind::Array(ty) => Ok(ty),
1851 AggregateKind::Tuple => {
1852 unreachable!("This should have been covered in check_rvalues");
1857 fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1858 if let Operand::Constant(constant) = op {
1859 let maybe_uneval = match constant.literal {
1860 ConstantKind::Ty(ct) => match ct.kind() {
1861 ty::ConstKind::Unevaluated(uv) => Some(uv),
1866 if let Some(uv) = maybe_uneval {
1867 if uv.promoted.is_none() {
1868 let tcx = self.tcx();
1869 let def_id = uv.def.def_id_for_type_of();
1870 if tcx.def_kind(def_id) == DefKind::InlineConst {
1871 let predicates = self.prove_closure_bounds(
1873 def_id.expect_local(),
1877 self.normalize_and_prove_instantiated_predicates(
1880 location.to_locations(),
1888 #[instrument(skip(self, body), level = "debug")]
1889 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1890 let tcx = self.tcx();
1893 Rvalue::Aggregate(ak, ops) => {
1895 self.check_operand(op, location);
1897 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1900 Rvalue::Repeat(operand, len) => {
1901 self.check_operand(operand, location);
1903 // If the length cannot be evaluated we must assume that the length can be larger
1905 // If the length is larger than 1, the repeat expression will need to copy the
1906 // element, so we require the `Copy` trait.
1907 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1909 Operand::Copy(..) | Operand::Constant(..) => {
1910 // These are always okay: direct use of a const, or a value that can evidently be copied.
1912 Operand::Move(place) => {
1913 // Make sure that repeated elements implement `Copy`.
1914 let span = body.source_info(location).span;
1915 let ty = place.ty(body, tcx).ty;
1916 let trait_ref = ty::TraitRef::new(
1917 tcx.require_lang_item(LangItem::Copy, Some(span)),
1918 tcx.mk_substs_trait(ty, &[]),
1921 self.prove_trait_ref(
1923 Locations::Single(location),
1924 ConstraintCategory::CopyBound,
1931 &Rvalue::NullaryOp(_, ty) => {
1932 let trait_ref = ty::TraitRef {
1933 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1934 substs: tcx.mk_substs_trait(ty, &[]),
1937 self.prove_trait_ref(
1939 location.to_locations(),
1940 ConstraintCategory::SizedBound,
1944 Rvalue::ShallowInitBox(operand, ty) => {
1945 self.check_operand(operand, location);
1947 let trait_ref = ty::TraitRef {
1948 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1949 substs: tcx.mk_substs_trait(*ty, &[]),
1952 self.prove_trait_ref(
1954 location.to_locations(),
1955 ConstraintCategory::SizedBound,
1959 Rvalue::Cast(cast_kind, op, ty) => {
1960 self.check_operand(op, location);
1963 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1964 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1966 // The type that we see in the fcx is like
1967 // `foo::<'a, 'b>`, where `foo` is the path to a
1968 // function definition. When we extract the
1969 // signature, it comes from the `fn_sig` query,
1970 // and hence may contain unnormalized results.
1971 let fn_sig = self.normalize(fn_sig, location);
1973 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1975 if let Err(terr) = self.eq_types(
1978 location.to_locations(),
1979 ConstraintCategory::Cast,
1984 "equating {:?} with {:?} yields {:?}",
1992 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
1993 let sig = match op.ty(body, tcx).kind() {
1994 ty::Closure(_, substs) => substs.as_closure().sig(),
1997 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
1999 if let Err(terr) = self.eq_types(
2002 location.to_locations(),
2003 ConstraintCategory::Cast,
2008 "equating {:?} with {:?} yields {:?}",
2016 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2017 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2019 // The type that we see in the fcx is like
2020 // `foo::<'a, 'b>`, where `foo` is the path to a
2021 // function definition. When we extract the
2022 // signature, it comes from the `fn_sig` query,
2023 // and hence may contain unnormalized results.
2024 let fn_sig = self.normalize(fn_sig, location);
2026 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2028 if let Err(terr) = self.eq_types(
2031 location.to_locations(),
2032 ConstraintCategory::Cast,
2037 "equating {:?} with {:?} yields {:?}",
2045 CastKind::Pointer(PointerCast::Unsize) => {
2047 let trait_ref = ty::TraitRef {
2049 .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2050 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2053 self.prove_trait_ref(
2055 location.to_locations(),
2056 ConstraintCategory::Cast,
2060 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2061 let ty::RawPtr(ty::TypeAndMut {
2063 mutbl: hir::Mutability::Mut,
2064 }) = op.ty(body, tcx).kind() else {
2068 "unexpected base type for cast {:?}",
2073 let ty::RawPtr(ty::TypeAndMut {
2075 mutbl: hir::Mutability::Not,
2076 }) = ty.kind() else {
2080 "unexpected target type for cast {:?}",
2085 if let Err(terr) = self.sub_types(
2088 location.to_locations(),
2089 ConstraintCategory::Cast,
2094 "relating {:?} with {:?} yields {:?}",
2102 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2103 let ty_from = op.ty(body, tcx);
2105 let opt_ty_elem_mut = match ty_from.kind() {
2106 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2107 match array_ty.kind() {
2108 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2115 let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
2119 "ArrayToPointer cast from unexpected type {:?}",
2125 let (ty_to, ty_to_mut) = match ty.kind() {
2126 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2133 "ArrayToPointer cast to unexpected type {:?}",
2140 if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2144 "ArrayToPointer cast from const {:?} to mut {:?}",
2151 if let Err(terr) = self.sub_types(
2154 location.to_locations(),
2155 ConstraintCategory::Cast,
2160 "relating {:?} with {:?} yields {:?}",
2168 CastKind::PointerExposeAddress => {
2169 let ty_from = op.ty(body, tcx);
2170 let cast_ty_from = CastTy::from_ty(ty_from);
2171 let cast_ty_to = CastTy::from_ty(*ty);
2172 match (cast_ty_from, cast_ty_to) {
2173 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => (),
2178 "Invalid PointerExposeAddress cast {:?} -> {:?}",
2186 CastKind::PointerFromExposedAddress => {
2187 let ty_from = op.ty(body, tcx);
2188 let cast_ty_from = CastTy::from_ty(ty_from);
2189 let cast_ty_to = CastTy::from_ty(*ty);
2190 match (cast_ty_from, cast_ty_to) {
2191 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
2196 "Invalid PointerFromExposedAddress cast {:?} -> {:?}",
2205 let ty_from = op.ty(body, tcx);
2206 let cast_ty_from = CastTy::from_ty(ty_from);
2207 let cast_ty_to = CastTy::from_ty(*ty);
2208 // Misc casts are either between floats and ints, or one ptr type to another.
2209 match (cast_ty_from, cast_ty_to) {
2211 Some(CastTy::Int(_) | CastTy::Float),
2212 Some(CastTy::Int(_) | CastTy::Float),
2214 | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
2219 "Invalid Misc cast {:?} -> {:?}",
2229 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2230 self.add_reborrow_constraint(&body, location, *region, borrowed_place);
2234 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2237 self.check_operand(left, location);
2238 self.check_operand(right, location);
2240 let ty_left = left.ty(body, tcx);
2241 match ty_left.kind() {
2242 // Types with regions are comparable if they have a common super-type.
2243 ty::RawPtr(_) | ty::FnPtr(_) => {
2244 let ty_right = right.ty(body, tcx);
2245 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2246 kind: TypeVariableOriginKind::MiscVariable,
2247 span: body.source_info(location).span,
2252 location.to_locations(),
2253 ConstraintCategory::Boring,
2255 .unwrap_or_else(|err| {
2256 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2258 if let Err(terr) = self.sub_types(
2261 location.to_locations(),
2262 ConstraintCategory::Boring,
2267 "unexpected comparison types {:?} and {:?} yields {:?}",
2274 // For types with no regions we can just check that the
2275 // both operands have the same type.
2276 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2277 if ty_left == right.ty(body, tcx) => {}
2278 // Other types are compared by trait methods, not by
2279 // `Rvalue::BinaryOp`.
2283 "unexpected comparison types {:?} and {:?}",
2290 Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => {
2291 self.check_operand(operand, location);
2293 Rvalue::CopyForDeref(place) => {
2294 let op = &Operand::Copy(*place);
2295 self.check_operand(op, location);
2298 Rvalue::BinaryOp(_, box (left, right))
2299 | Rvalue::CheckedBinaryOp(_, box (left, right)) => {
2300 self.check_operand(left, location);
2301 self.check_operand(right, location);
2304 Rvalue::AddressOf(..)
2305 | Rvalue::ThreadLocalRef(..)
2307 | Rvalue::Discriminant(..) => {}
2311 /// If this rvalue supports a user-given type annotation, then
2312 /// extract and return it. This represents the final type of the
2313 /// rvalue and will be unified with the inferred type.
2314 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2317 | Rvalue::ThreadLocalRef(_)
2318 | Rvalue::Repeat(..)
2320 | Rvalue::AddressOf(..)
2323 | Rvalue::ShallowInitBox(..)
2324 | Rvalue::BinaryOp(..)
2325 | Rvalue::CheckedBinaryOp(..)
2326 | Rvalue::NullaryOp(..)
2327 | Rvalue::CopyForDeref(..)
2328 | Rvalue::UnaryOp(..)
2329 | Rvalue::Discriminant(..) => None,
2331 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2332 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2333 AggregateKind::Array(_) => None,
2334 AggregateKind::Tuple => None,
2335 AggregateKind::Closure(_, _) => None,
2336 AggregateKind::Generator(_, _, _) => None,
2341 fn check_aggregate_rvalue(
2344 rvalue: &Rvalue<'tcx>,
2345 aggregate_kind: &AggregateKind<'tcx>,
2346 operands: &[Operand<'tcx>],
2349 let tcx = self.tcx();
2351 self.prove_aggregate_predicates(aggregate_kind, location);
2353 if *aggregate_kind == AggregateKind::Tuple {
2354 // tuple rvalue field type is always the type of the op. Nothing to check here.
2358 for (i, operand) in operands.iter().enumerate() {
2359 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2360 Ok(field_ty) => field_ty,
2361 Err(FieldAccessError::OutOfRange { field_count }) => {
2365 "accessed field #{} but variant only has {}",
2372 let operand_ty = operand.ty(body, tcx);
2373 let operand_ty = self.normalize(operand_ty, location);
2375 if let Err(terr) = self.sub_types(
2378 location.to_locations(),
2379 ConstraintCategory::Boring,
2384 "{:?} is not a subtype of {:?}: {:?}",
2393 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2397 /// - `location`: the location `L` where the borrow expression occurs
2398 /// - `borrow_region`: the region `'a` associated with the borrow
2399 /// - `borrowed_place`: the place `P` being borrowed
2400 fn add_reborrow_constraint(
2404 borrow_region: ty::Region<'tcx>,
2405 borrowed_place: &Place<'tcx>,
2407 // These constraints are only meaningful during borrowck:
2408 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2409 self.borrowck_context;
2411 // In Polonius mode, we also push a `loan_issued_at` fact
2412 // linking the loan to the region (in some cases, though,
2413 // there is no loan associated with this borrow expression --
2414 // that occurs when we are borrowing an unsafe place, for
2416 if let Some(all_facts) = all_facts {
2417 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2418 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2419 let region_vid = borrow_region.to_region_vid();
2420 all_facts.loan_issued_at.push((
2423 location_table.mid_index(location),
2428 // If we are reborrowing the referent of another reference, we
2429 // need to add outlives relationships. In a case like `&mut
2430 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2431 // need to ensure that `'b: 'a`.
2434 "add_reborrow_constraint({:?}, {:?}, {:?})",
2435 location, borrow_region, borrowed_place
2438 let mut cursor = borrowed_place.projection.as_ref();
2439 let tcx = self.infcx.tcx;
2440 let field = path_utils::is_upvar_field_projection(
2442 &self.borrowck_context.upvars,
2443 borrowed_place.as_ref(),
2446 let category = if let Some(field) = field {
2447 ConstraintCategory::ClosureUpvar(field)
2449 ConstraintCategory::Boring
2452 while let [proj_base @ .., elem] = cursor {
2455 debug!("add_reborrow_constraint - iteration {:?}", elem);
2458 ProjectionElem::Deref => {
2459 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2461 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2462 match base_ty.kind() {
2463 ty::Ref(ref_region, _, mutbl) => {
2464 constraints.outlives_constraints.push(OutlivesConstraint {
2465 sup: ref_region.to_region_vid(),
2466 sub: borrow_region.to_region_vid(),
2467 locations: location.to_locations(),
2468 span: location.to_locations().span(body),
2470 variance_info: ty::VarianceDiagInfo::default(),
2474 hir::Mutability::Not => {
2475 // Immutable reference. We don't need the base
2476 // to be valid for the entire lifetime of
2480 hir::Mutability::Mut => {
2481 // Mutable reference. We *do* need the base
2482 // to be valid, because after the base becomes
2483 // invalid, someone else can use our mutable deref.
2485 // This is in order to make the following function
2488 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2493 // As otherwise you could clone `&mut T` using the
2494 // following function:
2496 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2497 // let my_clone = unsafe_deref(&'a x);
2506 // deref of raw pointer, guaranteed to be valid
2509 ty::Adt(def, _) if def.is_box() => {
2510 // deref of `Box`, need the base to be valid - propagate
2512 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2515 ProjectionElem::Field(..)
2516 | ProjectionElem::Downcast(..)
2517 | ProjectionElem::Index(..)
2518 | ProjectionElem::ConstantIndex { .. }
2519 | ProjectionElem::Subslice { .. } => {
2520 // other field access
2526 fn prove_aggregate_predicates(
2528 aggregate_kind: &AggregateKind<'tcx>,
2531 let tcx = self.tcx();
2534 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2535 aggregate_kind, location
2538 let (def_id, instantiated_predicates) = match aggregate_kind {
2539 AggregateKind::Adt(adt_did, _, substs, _, _) => {
2540 (*adt_did, tcx.predicates_of(*adt_did).instantiate(tcx, substs))
2543 // For closures, we have some **extra requirements** we
2545 // have to check. In particular, in their upvars and
2546 // signatures, closures often reference various regions
2547 // from the surrounding function -- we call those the
2548 // closure's free regions. When we borrow-check (and hence
2549 // region-check) closures, we may find that the closure
2550 // requires certain relationships between those free
2551 // regions. However, because those free regions refer to
2552 // portions of the CFG of their caller, the closure is not
2553 // in a position to verify those relationships. In that
2554 // case, the requirements get "propagated" to us, and so
2555 // we have to solve them here where we instantiate the
2558 // Despite the opacity of the previous paragraph, this is
2559 // actually relatively easy to understand in terms of the
2560 // desugaring. A closure gets desugared to a struct, and
2561 // these extra requirements are basically like where
2562 // clauses on the struct.
2563 AggregateKind::Closure(def_id, substs)
2564 | AggregateKind::Generator(def_id, substs, _) => {
2565 (*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location))
2568 AggregateKind::Array(_) | AggregateKind::Tuple => {
2569 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2573 self.normalize_and_prove_instantiated_predicates(
2575 instantiated_predicates,
2576 location.to_locations(),
2580 fn prove_closure_bounds(
2584 substs: SubstsRef<'tcx>,
2586 ) -> ty::InstantiatedPredicates<'tcx> {
2587 if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2589 let closure_constraints = QueryRegionConstraints {
2590 outlives: closure_region_requirements.apply_requirements(
2596 // Presently, closures never propagate member
2597 // constraints to their parents -- they are enforced
2598 // locally. This is largely a non-issue as member
2599 // constraints only come from `-> impl Trait` and
2600 // friends which don't appear (thus far...) in
2602 member_constraints: vec![],
2605 let bounds_mapping = closure_constraints
2609 .filter_map(|(idx, constraint)| {
2610 let ty::OutlivesPredicate(k1, r2) =
2611 constraint.no_bound_vars().unwrap_or_else(|| {
2612 bug!("query_constraint {:?} contained bound vars", constraint,);
2616 GenericArgKind::Lifetime(r1) => {
2617 // constraint is r1: r2
2618 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2619 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2620 let outlives_requirements =
2621 &closure_region_requirements.outlives_requirements[idx];
2624 (outlives_requirements.category, outlives_requirements.blame_span),
2627 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2635 .closure_bounds_mapping
2636 .insert(location, bounds_mapping);
2637 assert!(existing.is_none(), "Multiple closures at the same location.");
2639 self.push_region_constraints(
2640 location.to_locations(),
2641 ConstraintCategory::ClosureBounds,
2642 &closure_constraints,
2646 tcx.predicates_of(def_id).instantiate(tcx, substs)
2649 #[instrument(skip(self, body), level = "debug")]
2650 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2651 self.last_span = body.span;
2654 for (local, local_decl) in body.local_decls.iter_enumerated() {
2655 self.check_local(&body, local, local_decl);
2658 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2659 let mut location = Location { block, statement_index: 0 };
2660 for stmt in &block_data.statements {
2661 if !stmt.source_info.span.is_dummy() {
2662 self.last_span = stmt.source_info.span;
2664 self.check_stmt(body, stmt, location);
2665 location.statement_index += 1;
2668 self.check_terminator(&body, block_data.terminator(), location);
2669 self.check_iscleanup(&body, block_data);
2674 trait NormalizeLocation: fmt::Debug + Copy {
2675 fn to_locations(self) -> Locations;
2678 impl NormalizeLocation for Locations {
2679 fn to_locations(self) -> Locations {
2684 impl NormalizeLocation for Location {
2685 fn to_locations(self) -> Locations {
2686 Locations::Single(self)
2690 /// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2691 /// this is not canonicalized - it directly affects the main `InferCtxt`
2692 /// that we use during MIR borrowchecking.
2694 pub(super) struct InstantiateOpaqueType<'tcx> {
2695 pub base_universe: Option<ty::UniverseIndex>,
2696 pub region_constraints: Option<RegionConstraintData<'tcx>>,
2697 pub obligations: Vec<PredicateObligation<'tcx>>,
2700 impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2702 /// We use this type itself to store the information used
2703 /// when reporting errors. Since this is not a query, we don't
2704 /// re-run anything during error reporting - we just use the information
2705 /// we saved to help extract an error from the already-existing region
2706 /// constraints in our `InferCtxt`
2707 type ErrorInfo = InstantiateOpaqueType<'tcx>;
2709 fn fully_perform(mut self, infcx: &InferCtxt<'_, 'tcx>) -> Fallible<TypeOpOutput<'tcx, Self>> {
2710 let (mut output, region_constraints) = scrape_region_constraints(infcx, || {
2711 Ok(InferOk { value: (), obligations: self.obligations.clone() })
2713 self.region_constraints = Some(region_constraints);
2714 output.error_info = Some(self);