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_middle::mir::tcx::PlaceTy;
25 use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
26 use rustc_middle::mir::AssertKind;
27 use rustc_middle::mir::*;
28 use rustc_middle::ty::adjustment::PointerCast;
29 use rustc_middle::ty::cast::CastTy;
30 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef, UserSubsts};
31 use rustc_middle::ty::visit::TypeVisitable;
32 use rustc_middle::ty::{
33 self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, OpaqueHiddenType,
34 OpaqueTypeKey, RegionVid, ToPredicate, Ty, TyCtxt, UserType, UserTypeAnnotationIndex,
36 use rustc_span::def_id::CRATE_DEF_ID;
37 use rustc_span::{Span, DUMMY_SP};
38 use rustc_target::abi::VariantIdx;
39 use rustc_trait_selection::traits::query::type_op;
40 use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
41 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
42 use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
43 use rustc_trait_selection::traits::query::Fallible;
44 use rustc_trait_selection::traits::PredicateObligation;
46 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
47 use rustc_mir_dataflow::move_paths::MoveData;
48 use rustc_mir_dataflow::ResultsCursor;
50 use crate::session_diagnostics::MoveUnsized;
52 borrow_set::BorrowSet,
53 constraints::{OutlivesConstraint, OutlivesConstraintSet},
54 diagnostics::UniverseInfo,
56 location::LocationTable,
57 member_constraints::MemberConstraintSet,
60 region_infer::values::{
61 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
63 region_infer::{ClosureRegionRequirementsExt, TypeTest},
64 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
65 universal_regions::{DefiningTy, UniversalRegions},
69 macro_rules! span_mirbug {
70 ($context:expr, $elem:expr, $($message:tt)*) => ({
71 $crate::type_check::mirbug(
75 "broken MIR in {:?} ({:?}): {}",
76 $context.body().source.def_id(),
78 format_args!($($message)*),
84 macro_rules! span_mirbug_and_err {
85 ($context:expr, $elem:expr, $($message:tt)*) => ({
87 span_mirbug!($context, $elem, $($message)*);
94 mod constraint_conversion;
95 pub mod free_region_relations;
97 pub(crate) mod liveness;
100 /// Type checks the given `mir` in the context of the inference
101 /// context `infcx`. Returns any region constraints that have yet to
102 /// be proven. This result includes liveness constraints that
103 /// ensure that regions appearing in the types of all local variables
104 /// are live at all points where that local variable may later be
107 /// This phase of type-check ought to be infallible -- this is because
108 /// the original, HIR-based type-check succeeded. So if any errors
109 /// occur here, we will get a `bug!` reported.
113 /// - `infcx` -- inference context to use
114 /// - `param_env` -- parameter environment to use for trait solving
115 /// - `body` -- MIR body to type-check
116 /// - `promoted` -- map of promoted constants within `body`
117 /// - `universal_regions` -- the universal regions from `body`s function signature
118 /// - `location_table` -- MIR location map of `body`
119 /// - `borrow_set` -- information about borrows occurring in `body`
120 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
121 /// - `flow_inits` -- results of a maybe-init dataflow analysis
122 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
123 /// - `elements` -- MIR region map
124 pub(crate) fn type_check<'mir, 'tcx>(
125 infcx: &InferCtxt<'_, 'tcx>,
126 param_env: ty::ParamEnv<'tcx>,
128 promoted: &IndexVec<Promoted, Body<'tcx>>,
129 universal_regions: &Rc<UniversalRegions<'tcx>>,
130 location_table: &LocationTable,
131 borrow_set: &BorrowSet<'tcx>,
132 all_facts: &mut Option<AllFacts>,
133 flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
134 move_data: &MoveData<'tcx>,
135 elements: &Rc<RegionValueElements>,
136 upvars: &[Upvar<'tcx>],
138 ) -> MirTypeckResults<'tcx> {
139 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
140 let mut universe_causes = FxHashMap::default();
141 universe_causes.insert(ty::UniverseIndex::from_u32(0), UniverseInfo::other());
142 let mut constraints = MirTypeckRegionConstraints {
143 placeholder_indices: PlaceholderIndices::default(),
144 placeholder_index_to_region: IndexVec::default(),
145 liveness_constraints: LivenessValues::new(elements.clone()),
146 outlives_constraints: OutlivesConstraintSet::default(),
147 member_constraints: MemberConstraintSet::default(),
148 closure_bounds_mapping: Default::default(),
149 type_tests: Vec::default(),
154 universal_region_relations,
156 normalized_inputs_and_output,
157 } = free_region_relations::create(
160 implicit_region_bound,
165 debug!(?normalized_inputs_and_output);
167 for u in ty::UniverseIndex::ROOT..infcx.universe() {
168 let info = UniverseInfo::other();
169 constraints.universe_causes.insert(u, info);
172 let mut borrowck_context = BorrowCheckContext {
177 constraints: &mut constraints,
181 let mut checker = TypeChecker::new(
186 implicit_region_bound,
187 &mut borrowck_context,
190 let errors_reported = {
191 let mut verifier = TypeVerifier::new(&mut checker, promoted);
192 verifier.visit_body(&body);
193 verifier.errors_reported
196 if !errors_reported {
197 // if verifier failed, don't do further checks to avoid ICEs
198 checker.typeck_mir(body);
201 checker.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
212 translate_outlives_facts(&mut checker);
213 let opaque_type_values = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
215 let opaque_type_values = opaque_type_values
217 .map(|(opaque_type_key, decl)| {
220 Locations::All(body.span),
221 ConstraintCategory::OpaqueType,
224 infcx.register_member_constraints(
228 decl.hidden_type.span,
230 Ok(InferOk { value: (), obligations: vec![] })
232 || "opaque_type_map".to_string(),
236 let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
237 trace!("finalized opaque type {:?} to {:#?}", opaque_type_key, hidden_type.ty.kind());
238 if hidden_type.has_infer_types_or_consts() {
239 infcx.tcx.sess.delay_span_bug(
240 decl.hidden_type.span,
241 &format!("could not resolve {:#?}", hidden_type.ty.kind()),
243 hidden_type.ty = infcx.tcx.ty_error();
246 (opaque_type_key, (hidden_type, decl.origin))
250 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
253 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
254 let cx = &mut typeck.borrowck_context;
255 if let Some(facts) = cx.all_facts {
256 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
257 let location_table = cx.location_table;
258 facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
259 |constraint: &OutlivesConstraint<'_>| {
260 if let Some(from_location) = constraint.locations.from_location() {
261 Either::Left(iter::once((
264 location_table.mid_index(from_location),
270 .map(move |location| (constraint.sup, constraint.sub, location)),
279 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
280 // We sometimes see MIR failures (notably predicate failures) due to
281 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
282 // to avoid reporting bugs in those cases.
283 tcx.sess.diagnostic().delay_span_bug(span, msg);
286 enum FieldAccessError {
287 OutOfRange { field_count: usize },
290 /// Verifies that MIR types are sane to not crash further checks.
292 /// The sanitize_XYZ methods here take an MIR object and compute its
293 /// type, calling `span_mirbug` and returning an error type if there
295 struct TypeVerifier<'a, 'b, 'tcx> {
296 cx: &'a mut TypeChecker<'b, 'tcx>,
297 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
299 errors_reported: bool,
302 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
303 fn visit_span(&mut self, span: Span) {
304 if !span.is_dummy() {
305 self.last_span = span;
309 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
310 self.sanitize_place(place, location, context);
313 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
314 debug!(?constant, ?location, "visit_constant");
316 self.super_constant(constant, location);
317 let ty = self.sanitize_type(constant, constant.literal.ty());
319 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
320 let live_region_vid =
321 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
325 .liveness_constraints
326 .add_element(live_region_vid, location);
329 // HACK(compiler-errors): Constants that are gathered into Body.required_consts
330 // have their locations erased...
331 let locations = if location != Location::START {
332 location.to_locations()
334 Locations::All(constant.span)
337 if let Some(annotation_index) = constant.user_ty {
338 if let Err(terr) = self.cx.relate_type_and_user_type(
339 constant.literal.ty(),
340 ty::Variance::Invariant,
341 &UserTypeProjection { base: annotation_index, projs: vec![] },
343 ConstraintCategory::Boring,
345 let annotation = &self.cx.user_type_annotations[annotation_index];
349 "bad constant user type {:?} vs {:?}: {:?}",
351 constant.literal.ty(),
356 let tcx = self.tcx();
357 let maybe_uneval = match constant.literal {
358 ConstantKind::Ty(ct) => match ct.kind() {
359 ty::ConstKind::Unevaluated(uv) => Some(uv),
364 if let Some(uv) = maybe_uneval {
365 if let Some(promoted) = uv.promoted {
366 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
367 promoted: &Body<'tcx>,
371 verifier.cx.eq_types(ty, san_ty, locations, ConstraintCategory::Boring)
376 "bad promoted type ({:?}: {:?}): {:?}",
384 if !self.errors_reported {
385 let promoted_body = &self.promoted[promoted];
386 self.sanitize_promoted(promoted_body, location);
388 let promoted_ty = promoted_body.return_ty();
389 check_err(self, promoted_body, ty, promoted_ty);
392 if let Err(terr) = self.cx.fully_perform_op(
394 ConstraintCategory::Boring,
395 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
396 constant.literal.ty(),
398 UserSubsts { substs: uv.substs, user_self_ty: None },
404 "bad constant type {:?} ({:?})",
410 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
411 let unnormalized_ty = tcx.type_of(static_def_id);
412 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
413 let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty;
415 if let Err(terr) = self.cx.eq_types(
419 ConstraintCategory::Boring,
421 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
425 if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() {
426 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
427 self.cx.normalize_and_prove_instantiated_predicates(
429 instantiated_predicates,
436 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
437 self.super_rvalue(rvalue, location);
438 let rval_ty = rvalue.ty(self.body(), self.tcx());
439 self.sanitize_type(rvalue, rval_ty);
442 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
443 self.super_local_decl(local, local_decl);
444 self.sanitize_type(local_decl, local_decl.ty);
446 if let Some(user_ty) = &local_decl.user_ty {
447 for (user_ty, span) in user_ty.projections_and_spans() {
448 let ty = if !local_decl.is_nonref_binding() {
449 // If we have a binding of the form `let ref x: T = ..`
450 // then remove the outermost reference so we can check the
451 // type annotation for the remaining type.
452 if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
455 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
461 if let Err(terr) = self.cx.relate_type_and_user_type(
463 ty::Variance::Invariant,
465 Locations::All(*span),
466 ConstraintCategory::TypeAnnotation,
471 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
482 fn visit_body(&mut self, body: &Body<'tcx>) {
483 self.sanitize_type(&"return type", body.return_ty());
484 for local_decl in &body.local_decls {
485 self.sanitize_type(local_decl, local_decl.ty);
487 if self.errors_reported {
490 self.super_body(body);
494 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
496 cx: &'a mut TypeChecker<'b, 'tcx>,
497 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
499 TypeVerifier { promoted, last_span: cx.body.span, cx, errors_reported: false }
502 fn body(&self) -> &Body<'tcx> {
506 fn tcx(&self) -> TyCtxt<'tcx> {
510 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
511 if ty.has_escaping_bound_vars() || ty.references_error() {
512 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
518 /// Checks that the types internal to the `place` match up with
519 /// what would be expected.
524 context: PlaceContext,
526 debug!("sanitize_place: {:?}", place);
528 let mut place_ty = PlaceTy::from_ty(self.body().local_decls[place.local].ty);
530 for elem in place.projection.iter() {
531 if place_ty.variant_index.is_none() {
532 if place_ty.ty.references_error() {
533 assert!(self.errors_reported);
534 return PlaceTy::from_ty(self.tcx().ty_error());
537 place_ty = self.sanitize_projection(place_ty, elem, place, location);
540 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
541 let tcx = self.tcx();
542 let trait_ref = ty::TraitRef {
543 def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
544 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
547 // To have a `Copy` operand, the type `T` of the
548 // value must be `Copy`. Note that we prove that `T: Copy`,
549 // rather than using the `is_copy_modulo_regions`
550 // test. This is important because
551 // `is_copy_modulo_regions` ignores the resulting region
552 // obligations and assumes they pass. This can result in
553 // bounds from `Copy` impls being unsoundly ignored (e.g.,
554 // #29149). Note that we decide to use `Copy` before knowing
555 // whether the bounds fully apply: in effect, the rule is
556 // that if a value of some type could implement `Copy`, then
558 self.cx.prove_trait_ref(
560 location.to_locations(),
561 ConstraintCategory::CopyBound,
568 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
569 // Determine the constraints from the promoted MIR by running the type
570 // checker on the promoted MIR, then transfer the constraints back to
571 // the main MIR, changing the locations to the provided location.
573 let parent_body = mem::replace(&mut self.cx.body, promoted_body);
575 // Use new sets of constraints and closure bounds so that we can
576 // modify their locations.
577 let all_facts = &mut None;
578 let mut constraints = Default::default();
579 let mut closure_bounds = Default::default();
580 let mut liveness_constraints =
581 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
582 // Don't try to add borrow_region facts for the promoted MIR
584 let mut swap_constraints = |this: &mut Self| {
585 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
587 &mut this.cx.borrowck_context.constraints.outlives_constraints,
591 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
595 &mut this.cx.borrowck_context.constraints.liveness_constraints,
596 &mut liveness_constraints,
600 swap_constraints(self);
602 self.visit_body(&promoted_body);
604 if !self.errors_reported {
605 // if verifier failed, don't do further checks to avoid ICEs
606 self.cx.typeck_mir(promoted_body);
609 self.cx.body = parent_body;
610 // Merge the outlives constraints back in, at the given location.
611 swap_constraints(self);
613 let locations = location.to_locations();
614 for constraint in constraints.outlives().iter() {
615 let mut constraint = constraint.clone();
616 constraint.locations = locations;
617 if let ConstraintCategory::Return(_)
618 | ConstraintCategory::UseAsConst
619 | ConstraintCategory::UseAsStatic = constraint.category
621 // "Returning" from a promoted is an assignment to a
622 // temporary from the user's point of view.
623 constraint.category = ConstraintCategory::Boring;
625 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
627 for region in liveness_constraints.rows() {
628 // If the region is live at at least one location in the promoted MIR,
629 // then add a liveness constraint to the main MIR for this region
630 // at the location provided as an argument to this method
631 if liveness_constraints.get_elements(region).next().is_some() {
635 .liveness_constraints
636 .add_element(region, location);
640 if !closure_bounds.is_empty() {
641 let combined_bounds_mapping =
642 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
647 .closure_bounds_mapping
648 .insert(location, combined_bounds_mapping);
649 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
653 fn sanitize_projection(
660 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
661 let tcx = self.tcx();
662 let base_ty = base.ty;
664 ProjectionElem::Deref => {
665 let deref_ty = base_ty.builtin_deref(true);
666 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
667 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
670 ProjectionElem::Index(i) => {
671 let index_ty = Place::from(i).ty(self.body(), tcx).ty;
672 if index_ty != tcx.types.usize {
673 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
675 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
676 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
680 ProjectionElem::ConstantIndex { .. } => {
681 // consider verifying in-bounds
682 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
683 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
686 ProjectionElem::Subslice { from, to, from_end } => {
687 PlaceTy::from_ty(match base_ty.kind() {
688 ty::Array(inner, _) => {
689 assert!(!from_end, "array subslices should not use from_end");
690 tcx.mk_array(*inner, to - from)
693 assert!(from_end, "slice subslices should use from_end");
696 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
699 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
700 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
701 if index.as_usize() >= adt_def.variants().len() {
702 PlaceTy::from_ty(span_mirbug_and_err!(
705 "cast to variant #{:?} but enum only has {:?}",
707 adt_def.variants().len()
710 PlaceTy { ty: base_ty, variant_index: Some(index) }
713 // We do not need to handle generators here, because this runs
714 // before the generator transform stage.
716 let ty = if let Some(name) = maybe_name {
717 span_mirbug_and_err!(
720 "can't downcast {:?} as {:?}",
725 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
730 ProjectionElem::Field(field, fty) => {
731 let fty = self.sanitize_type(place, fty);
732 let fty = self.cx.normalize(fty, location);
733 match self.field_ty(place, base, field, location) {
735 let ty = self.cx.normalize(ty, location);
736 if let Err(terr) = self.cx.eq_types(
739 location.to_locations(),
740 ConstraintCategory::Boring,
745 "bad field access ({:?}: {:?}): {:?}",
752 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
755 "accessed field #{} but variant only has {}",
760 PlaceTy::from_ty(fty)
765 fn error(&mut self) -> Ty<'tcx> {
766 self.errors_reported = true;
767 self.tcx().ty_error()
772 parent: &dyn fmt::Debug,
773 base_ty: PlaceTy<'tcx>,
776 ) -> Result<Ty<'tcx>, FieldAccessError> {
777 let tcx = self.tcx();
779 let (variant, substs) = match base_ty {
780 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
781 ty::Adt(adt_def, substs) => (adt_def.variant(variant_index), substs),
782 ty::Generator(def_id, substs, _) => {
783 let mut variants = substs.as_generator().state_tys(def_id, tcx);
784 let Some(mut variant) = variants.nth(variant_index.into()) else {
786 "variant_index of generator out of range: {:?}/{:?}",
788 substs.as_generator().state_tys(def_id, tcx).count()
791 return match variant.nth(field.index()) {
793 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
796 _ => bug!("can't have downcast of non-adt non-generator type"),
798 PlaceTy { ty, variant_index: None } => match *ty.kind() {
799 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
800 (adt_def.variant(VariantIdx::new(0)), substs)
802 ty::Closure(_, substs) => {
810 None => Err(FieldAccessError::OutOfRange {
811 field_count: substs.as_closure().upvar_tys().count(),
815 ty::Generator(_, substs, _) => {
816 // Only prefix fields (upvars and current state) are
817 // accessible without a variant index.
818 return match substs.as_generator().prefix_tys().nth(field.index()) {
820 None => Err(FieldAccessError::OutOfRange {
821 field_count: substs.as_generator().prefix_tys().count(),
826 return match tys.get(field.index()) {
828 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
832 return Ok(span_mirbug_and_err!(
835 "can't project out of {:?}",
842 if let Some(field) = variant.fields.get(field.index()) {
843 Ok(self.cx.normalize(field.ty(tcx, substs), location))
845 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
850 /// The MIR type checker. Visits the MIR and enforces all the
851 /// constraints needed for it to be valid and well-typed. Along the
852 /// way, it accrues region constraints -- these can later be used by
853 /// NLL region checking.
854 struct TypeChecker<'a, 'tcx> {
855 infcx: &'a InferCtxt<'a, 'tcx>,
856 param_env: ty::ParamEnv<'tcx>,
858 body: &'a Body<'tcx>,
859 /// User type annotations are shared between the main MIR and the MIR of
860 /// all of the promoted items.
861 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
862 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
863 implicit_region_bound: ty::Region<'tcx>,
864 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
865 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
868 struct BorrowCheckContext<'a, 'tcx> {
869 pub(crate) universal_regions: &'a UniversalRegions<'tcx>,
870 location_table: &'a LocationTable,
871 all_facts: &'a mut Option<AllFacts>,
872 borrow_set: &'a BorrowSet<'tcx>,
873 pub(crate) constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
874 upvars: &'a [Upvar<'tcx>],
877 pub(crate) struct MirTypeckResults<'tcx> {
878 pub(crate) constraints: MirTypeckRegionConstraints<'tcx>,
879 pub(crate) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
880 pub(crate) opaque_type_values:
881 VecMap<OpaqueTypeKey<'tcx>, (OpaqueHiddenType<'tcx>, OpaqueTyOrigin)>,
884 /// A collection of region constraints that must be satisfied for the
885 /// program to be considered well-typed.
886 pub(crate) struct MirTypeckRegionConstraints<'tcx> {
887 /// Maps from a `ty::Placeholder` to the corresponding
888 /// `PlaceholderIndex` bit that we will use for it.
890 /// To keep everything in sync, do not insert this set
891 /// directly. Instead, use the `placeholder_region` helper.
892 pub(crate) placeholder_indices: PlaceholderIndices,
894 /// Each time we add a placeholder to `placeholder_indices`, we
895 /// also create a corresponding "representative" region vid for
896 /// that wraps it. This vector tracks those. This way, when we
897 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
898 /// the same underlying `RegionVid`.
899 pub(crate) placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
901 /// In general, the type-checker is not responsible for enforcing
902 /// liveness constraints; this job falls to the region inferencer,
903 /// which performs a liveness analysis. However, in some limited
904 /// cases, the MIR type-checker creates temporary regions that do
905 /// not otherwise appear in the MIR -- in particular, the
906 /// late-bound regions that it instantiates at call-sites -- and
907 /// hence it must report on their liveness constraints.
908 pub(crate) liveness_constraints: LivenessValues<RegionVid>,
910 pub(crate) outlives_constraints: OutlivesConstraintSet<'tcx>,
912 pub(crate) member_constraints: MemberConstraintSet<'tcx, RegionVid>,
914 pub(crate) closure_bounds_mapping:
915 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory<'tcx>, Span)>>,
917 pub(crate) universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
919 pub(crate) type_tests: Vec<TypeTest<'tcx>>,
922 impl<'tcx> MirTypeckRegionConstraints<'tcx> {
923 fn placeholder_region(
925 infcx: &InferCtxt<'_, 'tcx>,
926 placeholder: ty::PlaceholderRegion,
927 ) -> ty::Region<'tcx> {
928 let placeholder_index = self.placeholder_indices.insert(placeholder);
929 match self.placeholder_index_to_region.get(placeholder_index) {
932 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
933 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
934 self.placeholder_index_to_region.push(region);
941 /// The `Locations` type summarizes *where* region constraints are
942 /// required to hold. Normally, this is at a particular point which
943 /// created the obligation, but for constraints that the user gave, we
944 /// want the constraint to hold at all points.
945 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
947 /// Indicates that a type constraint should always be true. This
948 /// is particularly important in the new borrowck analysis for
949 /// things like the type of the return slot. Consider this
952 /// ```compile_fail,E0515
953 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
955 /// return &y; // error
959 /// Here, we wind up with the signature from the return type being
960 /// something like `&'1 u32` where `'1` is a universal region. But
961 /// the type of the return slot `_0` is something like `&'2 u32`
962 /// where `'2` is an existential region variable. The type checker
963 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
964 /// older NLL analysis, we required this only at the entry point
965 /// to the function. By the nature of the constraints, this wound
966 /// up propagating to all points reachable from start (because
967 /// `'1` -- as a universal region -- is live everywhere). In the
968 /// newer analysis, though, this doesn't work: `_0` is considered
969 /// dead at the start (it has no usable value) and hence this type
970 /// equality is basically a no-op. Then, later on, when we do `_0
971 /// = &'3 y`, that region `'3` never winds up related to the
972 /// universal region `'1` and hence no error occurs. Therefore, we
973 /// use Locations::All instead, which ensures that the `'1` and
974 /// `'2` are equal everything. We also use this for other
975 /// user-given type annotations; e.g., if the user wrote `let mut
976 /// x: &'static u32 = ...`, we would ensure that all values
977 /// assigned to `x` are of `'static` lifetime.
979 /// The span points to the place the constraint arose. For example,
980 /// it points to the type in a user-given type annotation. If
981 /// there's no sensible span then it's DUMMY_SP.
984 /// An outlives constraint that only has to hold at a single location,
985 /// usually it represents a point where references flow from one spot to
986 /// another (e.g., `x = y`)
991 pub fn from_location(&self) -> Option<Location> {
993 Locations::All(_) => None,
994 Locations::Single(from_location) => Some(*from_location),
998 /// Gets a span representing the location.
999 pub fn span(&self, body: &Body<'_>) -> Span {
1001 Locations::All(span) => *span,
1002 Locations::Single(l) => body.source_info(*l).span,
1007 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1009 infcx: &'a InferCtxt<'a, 'tcx>,
1010 body: &'a Body<'tcx>,
1011 param_env: ty::ParamEnv<'tcx>,
1012 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1013 implicit_region_bound: ty::Region<'tcx>,
1014 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1016 let mut checker = Self {
1018 last_span: DUMMY_SP,
1020 user_type_annotations: &body.user_type_annotations,
1023 implicit_region_bound,
1025 reported_errors: Default::default(),
1027 checker.check_user_type_annotations();
1031 fn body(&self) -> &Body<'tcx> {
1035 fn unsized_feature_enabled(&self) -> bool {
1036 let features = self.tcx().features();
1037 features.unsized_locals || features.unsized_fn_params
1040 /// Equate the inferred type and the annotated type for user type annotations
1041 #[instrument(skip(self), level = "debug")]
1042 fn check_user_type_annotations(&mut self) {
1043 debug!(?self.user_type_annotations);
1044 for user_annotation in self.user_type_annotations {
1045 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1046 let inferred_ty = self.normalize(inferred_ty, Locations::All(span));
1047 let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1048 debug!(?annotation);
1050 UserType::Ty(mut ty) => {
1051 ty = self.normalize(ty, Locations::All(span));
1053 if let Err(terr) = self.eq_types(
1056 Locations::All(span),
1057 ConstraintCategory::BoringNoLocation,
1062 "bad user type ({:?} = {:?}): {:?}",
1069 self.prove_predicate(
1070 ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into()))
1071 .to_predicate(self.tcx()),
1072 Locations::All(span),
1073 ConstraintCategory::TypeAnnotation,
1076 UserType::TypeOf(def_id, user_substs) => {
1077 if let Err(terr) = self.fully_perform_op(
1078 Locations::All(span),
1079 ConstraintCategory::BoringNoLocation,
1080 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1089 "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}",
1093 self.tcx().type_of(def_id),
1102 #[instrument(skip(self, data), level = "debug")]
1103 fn push_region_constraints(
1105 locations: Locations,
1106 category: ConstraintCategory<'tcx>,
1107 data: &QueryRegionConstraints<'tcx>,
1109 debug!("constraints generated: {:#?}", data);
1111 constraint_conversion::ConstraintConversion::new(
1113 self.borrowck_context.universal_regions,
1114 self.region_bound_pairs,
1115 self.implicit_region_bound,
1118 locations.span(self.body),
1120 &mut self.borrowck_context.constraints,
1125 /// Try to relate `sub <: sup`
1130 locations: Locations,
1131 category: ConstraintCategory<'tcx>,
1133 // Use this order of parameters because the sup type is usually the
1134 // "expected" type in diagnostics.
1135 self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
1138 #[instrument(skip(self, category), level = "debug")]
1143 locations: Locations,
1144 category: ConstraintCategory<'tcx>,
1146 self.relate_types(expected, ty::Variance::Invariant, found, locations, category)
1149 #[instrument(skip(self), level = "debug")]
1150 fn relate_type_and_user_type(
1154 user_ty: &UserTypeProjection,
1155 locations: Locations,
1156 category: ConstraintCategory<'tcx>,
1158 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1159 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1161 let tcx = self.infcx.tcx;
1163 for proj in &user_ty.projs {
1164 let projected_ty = curr_projected_ty.projection_ty_core(
1169 let ty = this.field_ty(tcx, field);
1170 self.normalize(ty, locations)
1173 curr_projected_ty = projected_ty;
1176 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1177 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1180 let ty = curr_projected_ty.ty;
1181 self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1186 fn tcx(&self) -> TyCtxt<'tcx> {
1190 #[instrument(skip(self, body, location), level = "debug")]
1191 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1192 let tcx = self.tcx();
1193 debug!("stmt kind: {:?}", stmt.kind);
1195 StatementKind::Assign(box (ref place, ref rv)) => {
1196 // Assignments to temporaries are not "interesting";
1197 // they are not caused by the user, but rather artifacts
1198 // of lowering. Assignments to other sorts of places *are* interesting
1200 let category = match place.as_local() {
1201 Some(RETURN_PLACE) => {
1202 let defining_ty = &self.borrowck_context.universal_regions.defining_ty;
1203 if defining_ty.is_const() {
1204 if tcx.is_static(defining_ty.def_id()) {
1205 ConstraintCategory::UseAsStatic
1207 ConstraintCategory::UseAsConst
1210 ConstraintCategory::Return(ReturnConstraint::Normal)
1215 body.local_decls[l].local_info,
1216 Some(box LocalInfo::AggregateTemp)
1219 ConstraintCategory::Usage
1221 Some(l) if !body.local_decls[l].is_user_variable() => {
1222 ConstraintCategory::Boring
1224 _ => ConstraintCategory::Assignment,
1227 "assignment category: {:?} {:?}",
1229 place.as_local().map(|l| &body.local_decls[l])
1232 let place_ty = place.ty(body, tcx).ty;
1234 let place_ty = self.normalize(place_ty, location);
1235 debug!("place_ty normalized: {:?}", place_ty);
1236 let rv_ty = rv.ty(body, tcx);
1238 let rv_ty = self.normalize(rv_ty, location);
1239 debug!("normalized rv_ty: {:?}", rv_ty);
1241 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1246 "bad assignment ({:?} = {:?}): {:?}",
1253 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1254 if let Err(terr) = self.relate_type_and_user_type(
1256 ty::Variance::Invariant,
1257 &UserTypeProjection { base: annotation_index, projs: vec![] },
1258 location.to_locations(),
1259 ConstraintCategory::Boring,
1261 let annotation = &self.user_type_annotations[annotation_index];
1265 "bad user type on rvalue ({:?} = {:?}): {:?}",
1273 self.check_rvalue(body, rv, location);
1274 if !self.unsized_feature_enabled() {
1275 let trait_ref = ty::TraitRef {
1276 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1277 substs: tcx.mk_substs_trait(place_ty, &[]),
1279 self.prove_trait_ref(
1281 location.to_locations(),
1282 ConstraintCategory::SizedBound,
1286 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1287 let place_ty = place.ty(body, tcx).ty;
1288 if let Err(terr) = self.relate_type_and_user_type(
1292 Locations::All(stmt.source_info.span),
1293 ConstraintCategory::TypeAnnotation,
1295 let annotation = &self.user_type_annotations[projection.base];
1299 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1307 StatementKind::Intrinsic(box ref kind) => match kind {
1308 NonDivergingIntrinsic::Assume(op) => self.check_operand(op, location),
1309 NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
1310 stmt.source_info.span,
1311 "Unexpected NonDivergingIntrinsic::CopyNonOverlapping, should only appear after lowering_intrinsics",
1314 StatementKind::FakeRead(..)
1315 | StatementKind::StorageLive(..)
1316 | StatementKind::StorageDead(..)
1317 | StatementKind::Retag { .. }
1318 | StatementKind::Coverage(..)
1319 | StatementKind::Nop => {}
1320 StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
1321 bug!("Statement not allowed in this MIR phase")
1326 #[instrument(skip(self, body, term_location), level = "debug")]
1327 fn check_terminator(
1330 term: &Terminator<'tcx>,
1331 term_location: Location,
1333 let tcx = self.tcx();
1334 debug!("terminator kind: {:?}", term.kind);
1336 TerminatorKind::Goto { .. }
1337 | TerminatorKind::Resume
1338 | TerminatorKind::Abort
1339 | TerminatorKind::Return
1340 | TerminatorKind::GeneratorDrop
1341 | TerminatorKind::Unreachable
1342 | TerminatorKind::Drop { .. }
1343 | TerminatorKind::FalseEdge { .. }
1344 | TerminatorKind::FalseUnwind { .. }
1345 | TerminatorKind::InlineAsm { .. } => {
1346 // no checks needed for these
1349 TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1350 let place_ty = place.ty(body, tcx).ty;
1351 let rv_ty = value.ty(body, tcx);
1353 let locations = term_location.to_locations();
1355 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1360 "bad DropAndReplace ({:?} = {:?}): {:?}",
1367 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1368 self.check_operand(discr, term_location);
1370 let discr_ty = discr.ty(body, tcx);
1371 if let Err(terr) = self.sub_types(
1374 term_location.to_locations(),
1375 ConstraintCategory::Assignment,
1380 "bad SwitchInt ({:?} on {:?}): {:?}",
1386 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1387 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1389 // FIXME: check the values
1391 TerminatorKind::Call {
1399 self.check_operand(func, term_location);
1401 self.check_operand(arg, term_location);
1404 let func_ty = func.ty(body, tcx);
1405 debug!("func_ty.kind: {:?}", func_ty.kind());
1407 let sig = match func_ty.kind() {
1408 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1410 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1414 let (sig, map) = tcx.replace_late_bound_regions(sig, |br| {
1415 self.infcx.next_region_var(LateBoundRegion(
1416 term.source_info.span,
1418 LateBoundRegionConversionTime::FnCall,
1422 // IMPORTANT: We have to prove well formed for the function signature before
1423 // we normalize it, as otherwise types like `<&'a &'b () as Trait>::Assoc`
1424 // get normalized away, causing us to ignore the `'b: 'a` bound used by the function.
1426 // Normalization results in a well formed type if the input is well formed, so we
1427 // don't have to check it twice.
1429 // See #91068 for an example.
1430 self.prove_predicates(
1431 sig.inputs_and_output
1433 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1434 term_location.to_locations(),
1435 ConstraintCategory::Boring,
1437 let sig = self.normalize(sig, term_location);
1438 self.check_call_dest(body, term, &sig, *destination, target, term_location);
1440 // The ordinary liveness rules will ensure that all
1441 // regions in the type of the callee are live here. We
1442 // then further constrain the late-bound regions that
1443 // were instantiated at the call site to be live as
1444 // well. The resulting is that all the input (and
1445 // output) types in the signature must be live, since
1446 // all the inputs that fed into it were live.
1447 for &late_bound_region in map.values() {
1449 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1450 self.borrowck_context
1452 .liveness_constraints
1453 .add_element(region_vid, term_location);
1456 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1458 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1459 self.check_operand(cond, term_location);
1461 let cond_ty = cond.ty(body, tcx);
1462 if cond_ty != tcx.types.bool {
1463 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1466 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1467 if len.ty(body, tcx) != tcx.types.usize {
1468 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1470 if index.ty(body, tcx) != tcx.types.usize {
1471 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1475 TerminatorKind::Yield { ref value, .. } => {
1476 self.check_operand(value, term_location);
1478 let value_ty = value.ty(body, tcx);
1479 match body.yield_ty() {
1480 None => span_mirbug!(self, term, "yield in non-generator"),
1482 if let Err(terr) = self.sub_types(
1485 term_location.to_locations(),
1486 ConstraintCategory::Yield,
1491 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1506 term: &Terminator<'tcx>,
1507 sig: &ty::FnSig<'tcx>,
1508 destination: Place<'tcx>,
1509 target: Option<BasicBlock>,
1510 term_location: Location,
1512 let tcx = self.tcx();
1515 let dest_ty = destination.ty(body, tcx).ty;
1516 let dest_ty = self.normalize(dest_ty, term_location);
1517 let category = match destination.as_local() {
1518 Some(RETURN_PLACE) => {
1519 if let BorrowCheckContext {
1523 DefiningTy::Const(def_id, _)
1524 | DefiningTy::InlineConst(def_id, _),
1528 } = self.borrowck_context
1530 if tcx.is_static(*def_id) {
1531 ConstraintCategory::UseAsStatic
1533 ConstraintCategory::UseAsConst
1536 ConstraintCategory::Return(ReturnConstraint::Normal)
1539 Some(l) if !body.local_decls[l].is_user_variable() => {
1540 ConstraintCategory::Boring
1542 _ => ConstraintCategory::Assignment,
1545 let locations = term_location.to_locations();
1547 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1551 "call dest mismatch ({:?} <- {:?}): {:?}",
1558 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1559 // this check is done at `check_local`.
1560 if self.unsized_feature_enabled() {
1561 let span = term.source_info.span;
1562 self.ensure_place_sized(dest_ty, span);
1568 .conservative_is_privately_uninhabited(self.param_env.and(sig.output()))
1570 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1576 fn check_call_inputs(
1579 term: &Terminator<'tcx>,
1580 sig: &ty::FnSig<'tcx>,
1581 args: &[Operand<'tcx>],
1582 term_location: Location,
1583 from_hir_call: bool,
1585 debug!("check_call_inputs({:?}, {:?})", sig, args);
1586 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1587 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1590 let func_ty = if let TerminatorKind::Call { func, .. } = &term.kind {
1591 Some(func.ty(body, self.infcx.tcx))
1597 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1598 let op_arg_ty = op_arg.ty(body, self.tcx());
1600 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1601 let category = if from_hir_call {
1602 ConstraintCategory::CallArgument(func_ty)
1604 ConstraintCategory::Boring
1607 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
1612 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1622 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1623 let is_cleanup = block_data.is_cleanup;
1624 self.last_span = block_data.terminator().source_info.span;
1625 match block_data.terminator().kind {
1626 TerminatorKind::Goto { target } => {
1627 self.assert_iscleanup(body, block_data, target, is_cleanup)
1629 TerminatorKind::SwitchInt { ref targets, .. } => {
1630 for target in targets.all_targets() {
1631 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1634 TerminatorKind::Resume => {
1636 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1639 TerminatorKind::Abort => {
1641 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1644 TerminatorKind::Return => {
1646 span_mirbug!(self, block_data, "return on cleanup block")
1649 TerminatorKind::GeneratorDrop { .. } => {
1651 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1654 TerminatorKind::Yield { resume, drop, .. } => {
1656 span_mirbug!(self, block_data, "yield in cleanup block")
1658 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1659 if let Some(drop) = drop {
1660 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1663 TerminatorKind::Unreachable => {}
1664 TerminatorKind::Drop { target, unwind, .. }
1665 | TerminatorKind::DropAndReplace { target, unwind, .. }
1666 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1667 self.assert_iscleanup(body, block_data, target, is_cleanup);
1668 if let Some(unwind) = unwind {
1670 span_mirbug!(self, block_data, "unwind on cleanup block")
1672 self.assert_iscleanup(body, block_data, unwind, true);
1675 TerminatorKind::Call { ref target, cleanup, .. } => {
1676 if let &Some(target) = target {
1677 self.assert_iscleanup(body, block_data, target, is_cleanup);
1679 if let Some(cleanup) = cleanup {
1681 span_mirbug!(self, block_data, "cleanup on cleanup block")
1683 self.assert_iscleanup(body, block_data, cleanup, true);
1686 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1687 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1688 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1690 TerminatorKind::FalseUnwind { real_target, unwind } => {
1691 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1692 if let Some(unwind) = unwind {
1694 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1696 self.assert_iscleanup(body, block_data, unwind, true);
1699 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
1700 if let Some(target) = destination {
1701 self.assert_iscleanup(body, block_data, target, is_cleanup);
1703 if let Some(cleanup) = cleanup {
1705 span_mirbug!(self, block_data, "cleanup on cleanup block")
1707 self.assert_iscleanup(body, block_data, cleanup, true);
1713 fn assert_iscleanup(
1716 ctxt: &dyn fmt::Debug,
1720 if body[bb].is_cleanup != iscleanuppad {
1721 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1725 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1726 match body.local_kind(local) {
1727 LocalKind::ReturnPointer | LocalKind::Arg => {
1728 // return values of normal functions are required to be
1729 // sized by typeck, but return values of ADT constructors are
1730 // not because we don't include a `Self: Sized` bounds on them.
1732 // Unbound parts of arguments were never required to be Sized
1733 // - maybe we should make that a warning.
1736 LocalKind::Var | LocalKind::Temp => {}
1739 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1740 // and nullary ops are checked in `check_call_dest`.
1741 if !self.unsized_feature_enabled() {
1742 let span = local_decl.source_info.span;
1743 let ty = local_decl.ty;
1744 self.ensure_place_sized(ty, span);
1748 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1749 let tcx = self.tcx();
1751 // Erase the regions from `ty` to get a global type. The
1752 // `Sized` bound in no way depends on precise regions, so this
1753 // shouldn't affect `is_sized`.
1754 let erased_ty = tcx.erase_regions(ty);
1755 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1756 // in current MIR construction, all non-control-flow rvalue
1757 // expressions evaluate through `as_temp` or `into` a return
1758 // slot or local, so to find all unsized rvalues it is enough
1759 // to check all temps, return slots and locals.
1760 if self.reported_errors.replace((ty, span)).is_none() {
1761 // While this is located in `nll::typeck` this error is not
1762 // an NLL error, it's a required check to prevent creation
1763 // of unsized rvalues in a call expression.
1764 self.tcx().sess.emit_err(MoveUnsized { ty, span });
1769 fn aggregate_field_ty(
1771 ak: &AggregateKind<'tcx>,
1774 ) -> Result<Ty<'tcx>, FieldAccessError> {
1775 let tcx = self.tcx();
1778 AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => {
1779 let def = tcx.adt_def(adt_did);
1780 let variant = &def.variant(variant_index);
1781 let adj_field_index = active_field_index.unwrap_or(field_index);
1782 if let Some(field) = variant.fields.get(adj_field_index) {
1783 Ok(self.normalize(field.ty(tcx, substs), location))
1785 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1788 AggregateKind::Closure(_, substs) => {
1789 match substs.as_closure().upvar_tys().nth(field_index) {
1791 None => Err(FieldAccessError::OutOfRange {
1792 field_count: substs.as_closure().upvar_tys().count(),
1796 AggregateKind::Generator(_, substs, _) => {
1797 // It doesn't make sense to look at a field beyond the prefix;
1798 // these require a variant index, and are not initialized in
1799 // aggregate rvalues.
1800 match substs.as_generator().prefix_tys().nth(field_index) {
1802 None => Err(FieldAccessError::OutOfRange {
1803 field_count: substs.as_generator().prefix_tys().count(),
1807 AggregateKind::Array(ty) => Ok(ty),
1808 AggregateKind::Tuple => {
1809 unreachable!("This should have been covered in check_rvalues");
1814 fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1815 debug!(?op, ?location, "check_operand");
1817 if let Operand::Constant(constant) = op {
1818 let maybe_uneval = match constant.literal {
1819 ConstantKind::Ty(ct) => match ct.kind() {
1820 ty::ConstKind::Unevaluated(uv) => Some(uv),
1825 if let Some(uv) = maybe_uneval {
1826 if uv.promoted.is_none() {
1827 let tcx = self.tcx();
1828 let def_id = uv.def.def_id_for_type_of();
1829 if tcx.def_kind(def_id) == DefKind::InlineConst {
1830 let def_id = def_id.expect_local();
1832 self.prove_closure_bounds(tcx, def_id, uv.substs, location);
1833 self.normalize_and_prove_instantiated_predicates(
1836 location.to_locations(),
1844 #[instrument(skip(self, body), level = "debug")]
1845 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1846 let tcx = self.tcx();
1849 Rvalue::Aggregate(ak, ops) => {
1851 self.check_operand(op, location);
1853 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1856 Rvalue::Repeat(operand, len) => {
1857 self.check_operand(operand, location);
1859 // If the length cannot be evaluated we must assume that the length can be larger
1861 // If the length is larger than 1, the repeat expression will need to copy the
1862 // element, so we require the `Copy` trait.
1863 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1865 Operand::Copy(..) | Operand::Constant(..) => {
1866 // These are always okay: direct use of a const, or a value that can evidently be copied.
1868 Operand::Move(place) => {
1869 // Make sure that repeated elements implement `Copy`.
1870 let span = body.source_info(location).span;
1871 let ty = place.ty(body, tcx).ty;
1872 let trait_ref = ty::TraitRef::new(
1873 tcx.require_lang_item(LangItem::Copy, Some(span)),
1874 tcx.mk_substs_trait(ty, &[]),
1877 self.prove_trait_ref(
1879 Locations::Single(location),
1880 ConstraintCategory::CopyBound,
1887 &Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, ty) => {
1888 let trait_ref = ty::TraitRef {
1889 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1890 substs: tcx.mk_substs_trait(ty, &[]),
1893 self.prove_trait_ref(
1895 location.to_locations(),
1896 ConstraintCategory::SizedBound,
1900 Rvalue::ShallowInitBox(operand, ty) => {
1901 self.check_operand(operand, location);
1903 let trait_ref = ty::TraitRef {
1904 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1905 substs: tcx.mk_substs_trait(*ty, &[]),
1908 self.prove_trait_ref(
1910 location.to_locations(),
1911 ConstraintCategory::SizedBound,
1915 Rvalue::Cast(cast_kind, op, ty) => {
1916 self.check_operand(op, location);
1919 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1920 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1922 // The type that we see in the fcx is like
1923 // `foo::<'a, 'b>`, where `foo` is the path to a
1924 // function definition. When we extract the
1925 // signature, it comes from the `fn_sig` query,
1926 // and hence may contain unnormalized results.
1927 let fn_sig = self.normalize(fn_sig, location);
1929 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1931 if let Err(terr) = self.eq_types(
1934 location.to_locations(),
1935 ConstraintCategory::Cast,
1940 "equating {:?} with {:?} yields {:?}",
1948 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
1949 let sig = match op.ty(body, tcx).kind() {
1950 ty::Closure(_, substs) => substs.as_closure().sig(),
1953 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
1955 if let Err(terr) = self.eq_types(
1958 location.to_locations(),
1959 ConstraintCategory::Cast,
1964 "equating {:?} with {:?} yields {:?}",
1972 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
1973 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1975 // The type that we see in the fcx is like
1976 // `foo::<'a, 'b>`, where `foo` is the path to a
1977 // function definition. When we extract the
1978 // signature, it comes from the `fn_sig` query,
1979 // and hence may contain unnormalized results.
1980 let fn_sig = self.normalize(fn_sig, location);
1982 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1984 if let Err(terr) = self.eq_types(
1987 location.to_locations(),
1988 ConstraintCategory::Cast,
1993 "equating {:?} with {:?} yields {:?}",
2001 CastKind::Pointer(PointerCast::Unsize) => {
2003 let trait_ref = ty::TraitRef {
2005 .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2006 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2009 self.prove_trait_ref(
2011 location.to_locations(),
2012 ConstraintCategory::Cast,
2016 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2017 let ty::RawPtr(ty::TypeAndMut {
2019 mutbl: hir::Mutability::Mut,
2020 }) = op.ty(body, tcx).kind() else {
2024 "unexpected base type for cast {:?}",
2029 let ty::RawPtr(ty::TypeAndMut {
2031 mutbl: hir::Mutability::Not,
2032 }) = ty.kind() else {
2036 "unexpected target type for cast {:?}",
2041 if let Err(terr) = self.sub_types(
2044 location.to_locations(),
2045 ConstraintCategory::Cast,
2050 "relating {:?} with {:?} yields {:?}",
2058 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2059 let ty_from = op.ty(body, tcx);
2061 let opt_ty_elem_mut = match ty_from.kind() {
2062 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2063 match array_ty.kind() {
2064 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2071 let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
2075 "ArrayToPointer cast from unexpected type {:?}",
2081 let (ty_to, ty_to_mut) = match ty.kind() {
2082 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2089 "ArrayToPointer cast to unexpected type {:?}",
2096 if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2100 "ArrayToPointer cast from const {:?} to mut {:?}",
2107 if let Err(terr) = self.sub_types(
2110 location.to_locations(),
2111 ConstraintCategory::Cast,
2116 "relating {:?} with {:?} yields {:?}",
2124 CastKind::PointerExposeAddress => {
2125 let ty_from = op.ty(body, tcx);
2126 let cast_ty_from = CastTy::from_ty(ty_from);
2127 let cast_ty_to = CastTy::from_ty(*ty);
2128 match (cast_ty_from, cast_ty_to) {
2129 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => (),
2134 "Invalid PointerExposeAddress cast {:?} -> {:?}",
2142 CastKind::PointerFromExposedAddress => {
2143 let ty_from = op.ty(body, tcx);
2144 let cast_ty_from = CastTy::from_ty(ty_from);
2145 let cast_ty_to = CastTy::from_ty(*ty);
2146 match (cast_ty_from, cast_ty_to) {
2147 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
2152 "Invalid PointerFromExposedAddress cast {:?} -> {:?}",
2161 let ty_from = op.ty(body, tcx);
2162 let cast_ty_from = CastTy::from_ty(ty_from);
2163 let cast_ty_to = CastTy::from_ty(*ty);
2164 // Misc casts are either between floats and ints, or one ptr type to another.
2165 match (cast_ty_from, cast_ty_to) {
2167 Some(CastTy::Int(_) | CastTy::Float),
2168 Some(CastTy::Int(_) | CastTy::Float),
2170 | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
2175 "Invalid Misc cast {:?} -> {:?}",
2185 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2186 self.add_reborrow_constraint(&body, location, *region, borrowed_place);
2190 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2193 self.check_operand(left, location);
2194 self.check_operand(right, location);
2196 let ty_left = left.ty(body, tcx);
2197 match ty_left.kind() {
2198 // Types with regions are comparable if they have a common super-type.
2199 ty::RawPtr(_) | ty::FnPtr(_) => {
2200 let ty_right = right.ty(body, tcx);
2201 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2202 kind: TypeVariableOriginKind::MiscVariable,
2203 span: body.source_info(location).span,
2208 location.to_locations(),
2209 ConstraintCategory::Boring,
2211 .unwrap_or_else(|err| {
2212 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2214 if let Err(terr) = self.sub_types(
2217 location.to_locations(),
2218 ConstraintCategory::Boring,
2223 "unexpected comparison types {:?} and {:?} yields {:?}",
2230 // For types with no regions we can just check that the
2231 // both operands have the same type.
2232 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2233 if ty_left == right.ty(body, tcx) => {}
2234 // Other types are compared by trait methods, not by
2235 // `Rvalue::BinaryOp`.
2239 "unexpected comparison types {:?} and {:?}",
2246 Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => {
2247 self.check_operand(operand, location);
2249 Rvalue::CopyForDeref(place) => {
2250 let op = &Operand::Copy(*place);
2251 self.check_operand(op, location);
2254 Rvalue::BinaryOp(_, box (left, right))
2255 | Rvalue::CheckedBinaryOp(_, box (left, right)) => {
2256 self.check_operand(left, location);
2257 self.check_operand(right, location);
2260 Rvalue::AddressOf(..)
2261 | Rvalue::ThreadLocalRef(..)
2263 | Rvalue::Discriminant(..) => {}
2267 /// If this rvalue supports a user-given type annotation, then
2268 /// extract and return it. This represents the final type of the
2269 /// rvalue and will be unified with the inferred type.
2270 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2273 | Rvalue::ThreadLocalRef(_)
2274 | Rvalue::Repeat(..)
2276 | Rvalue::AddressOf(..)
2279 | Rvalue::ShallowInitBox(..)
2280 | Rvalue::BinaryOp(..)
2281 | Rvalue::CheckedBinaryOp(..)
2282 | Rvalue::NullaryOp(..)
2283 | Rvalue::CopyForDeref(..)
2284 | Rvalue::UnaryOp(..)
2285 | Rvalue::Discriminant(..) => None,
2287 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2288 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2289 AggregateKind::Array(_) => None,
2290 AggregateKind::Tuple => None,
2291 AggregateKind::Closure(_, _) => None,
2292 AggregateKind::Generator(_, _, _) => None,
2297 fn check_aggregate_rvalue(
2300 rvalue: &Rvalue<'tcx>,
2301 aggregate_kind: &AggregateKind<'tcx>,
2302 operands: &[Operand<'tcx>],
2305 let tcx = self.tcx();
2307 self.prove_aggregate_predicates(aggregate_kind, location);
2309 if *aggregate_kind == AggregateKind::Tuple {
2310 // tuple rvalue field type is always the type of the op. Nothing to check here.
2314 for (i, operand) in operands.iter().enumerate() {
2315 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2316 Ok(field_ty) => field_ty,
2317 Err(FieldAccessError::OutOfRange { field_count }) => {
2321 "accessed field #{} but variant only has {}",
2328 let operand_ty = operand.ty(body, tcx);
2329 let operand_ty = self.normalize(operand_ty, location);
2331 if let Err(terr) = self.sub_types(
2334 location.to_locations(),
2335 ConstraintCategory::Boring,
2340 "{:?} is not a subtype of {:?}: {:?}",
2349 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2353 /// - `location`: the location `L` where the borrow expression occurs
2354 /// - `borrow_region`: the region `'a` associated with the borrow
2355 /// - `borrowed_place`: the place `P` being borrowed
2356 fn add_reborrow_constraint(
2360 borrow_region: ty::Region<'tcx>,
2361 borrowed_place: &Place<'tcx>,
2363 // These constraints are only meaningful during borrowck:
2364 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2365 self.borrowck_context;
2367 // In Polonius mode, we also push a `loan_issued_at` fact
2368 // linking the loan to the region (in some cases, though,
2369 // there is no loan associated with this borrow expression --
2370 // that occurs when we are borrowing an unsafe place, for
2372 if let Some(all_facts) = all_facts {
2373 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2374 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2375 let region_vid = borrow_region.to_region_vid();
2376 all_facts.loan_issued_at.push((
2379 location_table.mid_index(location),
2384 // If we are reborrowing the referent of another reference, we
2385 // need to add outlives relationships. In a case like `&mut
2386 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2387 // need to ensure that `'b: 'a`.
2390 "add_reborrow_constraint({:?}, {:?}, {:?})",
2391 location, borrow_region, borrowed_place
2394 let mut cursor = borrowed_place.projection.as_ref();
2395 let tcx = self.infcx.tcx;
2396 let field = path_utils::is_upvar_field_projection(
2398 &self.borrowck_context.upvars,
2399 borrowed_place.as_ref(),
2402 let category = if let Some(field) = field {
2403 ConstraintCategory::ClosureUpvar(field)
2405 ConstraintCategory::Boring
2408 while let [proj_base @ .., elem] = cursor {
2411 debug!("add_reborrow_constraint - iteration {:?}", elem);
2414 ProjectionElem::Deref => {
2415 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2417 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2418 match base_ty.kind() {
2419 ty::Ref(ref_region, _, mutbl) => {
2420 constraints.outlives_constraints.push(OutlivesConstraint {
2421 sup: ref_region.to_region_vid(),
2422 sub: borrow_region.to_region_vid(),
2423 locations: location.to_locations(),
2424 span: location.to_locations().span(body),
2426 variance_info: ty::VarianceDiagInfo::default(),
2430 hir::Mutability::Not => {
2431 // Immutable reference. We don't need the base
2432 // to be valid for the entire lifetime of
2436 hir::Mutability::Mut => {
2437 // Mutable reference. We *do* need the base
2438 // to be valid, because after the base becomes
2439 // invalid, someone else can use our mutable deref.
2441 // This is in order to make the following function
2444 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2449 // As otherwise you could clone `&mut T` using the
2450 // following function:
2452 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2453 // let my_clone = unsafe_deref(&'a x);
2462 // deref of raw pointer, guaranteed to be valid
2465 ty::Adt(def, _) if def.is_box() => {
2466 // deref of `Box`, need the base to be valid - propagate
2468 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2471 ProjectionElem::Field(..)
2472 | ProjectionElem::Downcast(..)
2473 | ProjectionElem::Index(..)
2474 | ProjectionElem::ConstantIndex { .. }
2475 | ProjectionElem::Subslice { .. } => {
2476 // other field access
2482 fn prove_aggregate_predicates(
2484 aggregate_kind: &AggregateKind<'tcx>,
2487 let tcx = self.tcx();
2490 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2491 aggregate_kind, location
2494 let (def_id, instantiated_predicates) = match *aggregate_kind {
2495 AggregateKind::Adt(adt_did, _, substs, _, _) => {
2496 (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, substs))
2499 // For closures, we have some **extra requirements** we
2501 // have to check. In particular, in their upvars and
2502 // signatures, closures often reference various regions
2503 // from the surrounding function -- we call those the
2504 // closure's free regions. When we borrow-check (and hence
2505 // region-check) closures, we may find that the closure
2506 // requires certain relationships between those free
2507 // regions. However, because those free regions refer to
2508 // portions of the CFG of their caller, the closure is not
2509 // in a position to verify those relationships. In that
2510 // case, the requirements get "propagated" to us, and so
2511 // we have to solve them here where we instantiate the
2514 // Despite the opacity of the previous paragraph, this is
2515 // actually relatively easy to understand in terms of the
2516 // desugaring. A closure gets desugared to a struct, and
2517 // these extra requirements are basically like where
2518 // clauses on the struct.
2519 AggregateKind::Closure(def_id, substs)
2520 | AggregateKind::Generator(def_id, substs, _) => {
2521 (def_id.to_def_id(), self.prove_closure_bounds(tcx, def_id, substs, location))
2524 AggregateKind::Array(_) | AggregateKind::Tuple => {
2525 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2529 self.normalize_and_prove_instantiated_predicates(
2531 instantiated_predicates,
2532 location.to_locations(),
2536 fn prove_closure_bounds(
2540 substs: SubstsRef<'tcx>,
2542 ) -> ty::InstantiatedPredicates<'tcx> {
2543 if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2545 let closure_constraints = QueryRegionConstraints {
2546 outlives: closure_region_requirements.apply_requirements(
2552 // Presently, closures never propagate member
2553 // constraints to their parents -- they are enforced
2554 // locally. This is largely a non-issue as member
2555 // constraints only come from `-> impl Trait` and
2556 // friends which don't appear (thus far...) in
2558 member_constraints: vec![],
2561 let bounds_mapping = closure_constraints
2565 .filter_map(|(idx, constraint)| {
2566 let ty::OutlivesPredicate(k1, r2) =
2567 constraint.0.no_bound_vars().unwrap_or_else(|| {
2568 bug!("query_constraint {:?} contained bound vars", constraint,);
2572 GenericArgKind::Lifetime(r1) => {
2573 // constraint is r1: r2
2574 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2575 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2576 let outlives_requirements =
2577 &closure_region_requirements.outlives_requirements[idx];
2580 (outlives_requirements.category, outlives_requirements.blame_span),
2583 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2591 .closure_bounds_mapping
2592 .insert(location, bounds_mapping);
2593 assert!(existing.is_none(), "Multiple closures at the same location.");
2595 self.push_region_constraints(
2596 location.to_locations(),
2597 ConstraintCategory::ClosureBounds,
2598 &closure_constraints,
2602 // Now equate closure substs to regions inherited from `typeck_root_def_id`. Fixes #98589.
2603 let typeck_root_def_id = tcx.typeck_root_def_id(self.body.source.def_id());
2604 let typeck_root_substs = ty::InternalSubsts::identity_for_item(tcx, typeck_root_def_id);
2606 let parent_substs = match tcx.def_kind(def_id) {
2607 DefKind::Closure => substs.as_closure().parent_substs(),
2608 DefKind::Generator => substs.as_generator().parent_substs(),
2609 DefKind::InlineConst => substs.as_inline_const().parent_substs(),
2610 other => bug!("unexpected item {:?}", other),
2612 let parent_substs = tcx.mk_substs(parent_substs.iter());
2614 assert_eq!(typeck_root_substs.len(), parent_substs.len());
2615 if let Err(_) = self.eq_substs(
2618 location.to_locations(),
2619 ConstraintCategory::BoringNoLocation,
2624 "could not relate closure to parent {:?} != {:?}",
2630 tcx.predicates_of(def_id).instantiate(tcx, substs)
2633 #[instrument(skip(self, body), level = "debug")]
2634 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2635 self.last_span = body.span;
2638 for (local, local_decl) in body.local_decls.iter_enumerated() {
2639 self.check_local(&body, local, local_decl);
2642 for (block, block_data) in body.basic_blocks.iter_enumerated() {
2643 let mut location = Location { block, statement_index: 0 };
2644 for stmt in &block_data.statements {
2645 if !stmt.source_info.span.is_dummy() {
2646 self.last_span = stmt.source_info.span;
2648 self.check_stmt(body, stmt, location);
2649 location.statement_index += 1;
2652 self.check_terminator(&body, block_data.terminator(), location);
2653 self.check_iscleanup(&body, block_data);
2658 trait NormalizeLocation: fmt::Debug + Copy {
2659 fn to_locations(self) -> Locations;
2662 impl NormalizeLocation for Locations {
2663 fn to_locations(self) -> Locations {
2668 impl NormalizeLocation for Location {
2669 fn to_locations(self) -> Locations {
2670 Locations::Single(self)
2674 /// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2675 /// this is not canonicalized - it directly affects the main `InferCtxt`
2676 /// that we use during MIR borrowchecking.
2678 pub(super) struct InstantiateOpaqueType<'tcx> {
2679 pub base_universe: Option<ty::UniverseIndex>,
2680 pub region_constraints: Option<RegionConstraintData<'tcx>>,
2681 pub obligations: Vec<PredicateObligation<'tcx>>,
2684 impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2686 /// We use this type itself to store the information used
2687 /// when reporting errors. Since this is not a query, we don't
2688 /// re-run anything during error reporting - we just use the information
2689 /// we saved to help extract an error from the already-existing region
2690 /// constraints in our `InferCtxt`
2691 type ErrorInfo = InstantiateOpaqueType<'tcx>;
2693 fn fully_perform(mut self, infcx: &InferCtxt<'_, 'tcx>) -> Fallible<TypeOpOutput<'tcx, Self>> {
2694 let (mut output, region_constraints) = scrape_region_constraints(infcx, || {
2695 Ok(InferOk { value: (), obligations: self.obligations.clone() })
2697 self.region_constraints = Some(region_constraints);
2698 output.error_info = Some(self);