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;
12 use rustc_errors::struct_span_err;
14 use rustc_hir::def::DefKind;
15 use rustc_hir::def_id::LocalDefId;
16 use rustc_hir::lang_items::LangItem;
17 use rustc_index::vec::{Idx, IndexVec};
18 use rustc_infer::infer::canonical::QueryRegionConstraints;
19 use rustc_infer::infer::outlives::env::RegionBoundPairs;
20 use rustc_infer::infer::region_constraints::RegionConstraintData;
21 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
22 use rustc_infer::infer::{
23 InferCtxt, InferOk, LateBoundRegionConversionTime, NllRegionVariableOrigin,
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::fold::TypeFoldable;
32 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef, UserSubsts};
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::infer::InferCtxtExt as _;
41 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
42 use rustc_trait_selection::traits::query::type_op;
43 use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
44 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
45 use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
46 use rustc_trait_selection::traits::query::Fallible;
47 use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligation};
49 use rustc_const_eval::transform::{
50 check_consts::ConstCx, promote_consts::is_const_fn_in_array_repeat_expression,
52 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
53 use rustc_mir_dataflow::move_paths::MoveData;
54 use rustc_mir_dataflow::ResultsCursor;
57 borrow_set::BorrowSet,
58 constraints::{OutlivesConstraint, OutlivesConstraintSet},
59 diagnostics::UniverseInfo,
61 location::LocationTable,
62 member_constraints::MemberConstraintSet,
65 region_infer::values::{
66 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
68 region_infer::{ClosureRegionRequirementsExt, TypeTest},
69 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
70 universal_regions::{DefiningTy, UniversalRegions},
74 macro_rules! span_mirbug {
75 ($context:expr, $elem:expr, $($message:tt)*) => ({
76 $crate::type_check::mirbug(
80 "broken MIR in {:?} ({:?}): {}",
81 $context.body().source.def_id(),
83 format_args!($($message)*),
89 macro_rules! span_mirbug_and_err {
90 ($context:expr, $elem:expr, $($message:tt)*) => ({
92 span_mirbug!($context, $elem, $($message)*);
99 mod constraint_conversion;
100 pub mod free_region_relations;
105 /// Type checks the given `mir` in the context of the inference
106 /// context `infcx`. Returns any region constraints that have yet to
107 /// be proven. This result includes liveness constraints that
108 /// ensure that regions appearing in the types of all local variables
109 /// are live at all points where that local variable may later be
112 /// This phase of type-check ought to be infallible -- this is because
113 /// the original, HIR-based type-check succeeded. So if any errors
114 /// occur here, we will get a `bug!` reported.
118 /// - `infcx` -- inference context to use
119 /// - `param_env` -- parameter environment to use for trait solving
120 /// - `body` -- MIR body to type-check
121 /// - `promoted` -- map of promoted constants within `body`
122 /// - `universal_regions` -- the universal regions from `body`s function signature
123 /// - `location_table` -- MIR location map of `body`
124 /// - `borrow_set` -- information about borrows occurring in `body`
125 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
126 /// - `flow_inits` -- results of a maybe-init dataflow analysis
127 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
128 /// - `elements` -- MIR region map
129 pub(crate) fn type_check<'mir, 'tcx>(
130 infcx: &InferCtxt<'_, 'tcx>,
131 param_env: ty::ParamEnv<'tcx>,
133 promoted: &IndexVec<Promoted, Body<'tcx>>,
134 universal_regions: &Rc<UniversalRegions<'tcx>>,
135 location_table: &LocationTable,
136 borrow_set: &BorrowSet<'tcx>,
137 all_facts: &mut Option<AllFacts>,
138 flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
139 move_data: &MoveData<'tcx>,
140 elements: &Rc<RegionValueElements>,
141 upvars: &[Upvar<'tcx>],
143 ) -> MirTypeckResults<'tcx> {
144 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
145 let mut universe_causes = FxHashMap::default();
146 universe_causes.insert(ty::UniverseIndex::from_u32(0), UniverseInfo::other());
147 let mut constraints = MirTypeckRegionConstraints {
148 placeholder_indices: PlaceholderIndices::default(),
149 placeholder_index_to_region: IndexVec::default(),
150 liveness_constraints: LivenessValues::new(elements.clone()),
151 outlives_constraints: OutlivesConstraintSet::default(),
152 member_constraints: MemberConstraintSet::default(),
153 closure_bounds_mapping: Default::default(),
154 type_tests: Vec::default(),
159 universal_region_relations,
161 normalized_inputs_and_output,
162 } = free_region_relations::create(
165 Some(implicit_region_bound),
170 for u in ty::UniverseIndex::ROOT..infcx.universe() {
171 let info = UniverseInfo::other();
172 constraints.universe_causes.insert(u, info);
175 let mut borrowck_context = BorrowCheckContext {
180 constraints: &mut constraints,
184 let opaque_type_values = type_check_internal(
190 implicit_region_bound,
191 &mut borrowck_context,
193 cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
204 translate_outlives_facts(&mut cx);
205 let opaque_type_values =
206 infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
210 .map(|(opaque_type_key, decl)| {
212 Locations::All(body.span),
213 ConstraintCategory::OpaqueType,
216 infcx.register_member_constraints(
220 decl.hidden_type.span,
222 Ok(InferOk { value: (), obligations: vec![] })
224 || "opaque_type_map".to_string(),
228 let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
230 "finalized opaque type {:?} to {:#?}",
232 hidden_type.ty.kind()
234 if hidden_type.has_infer_types_or_consts() {
235 infcx.tcx.sess.delay_span_bug(
236 decl.hidden_type.span,
237 &format!("could not resolve {:#?}", hidden_type.ty.kind()),
239 hidden_type.ty = infcx.tcx.ty_error();
242 (opaque_type_key, (hidden_type, decl.origin))
248 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
252 skip(infcx, body, promoted, region_bound_pairs, borrowck_context, extra),
255 fn type_check_internal<'a, 'tcx, R>(
256 infcx: &'a InferCtxt<'a, 'tcx>,
257 param_env: ty::ParamEnv<'tcx>,
258 body: &'a Body<'tcx>,
259 promoted: &'a IndexVec<Promoted, Body<'tcx>>,
260 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
261 implicit_region_bound: ty::Region<'tcx>,
262 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
263 extra: impl FnOnce(TypeChecker<'a, 'tcx>) -> R,
265 let mut checker = TypeChecker::new(
270 implicit_region_bound,
273 let errors_reported = {
274 let mut verifier = TypeVerifier::new(&mut checker, promoted);
275 verifier.visit_body(&body);
276 verifier.errors_reported
279 if !errors_reported {
280 // if verifier failed, don't do further checks to avoid ICEs
281 checker.typeck_mir(body);
287 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
288 let cx = &mut typeck.borrowck_context;
289 if let Some(facts) = cx.all_facts {
290 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
291 let location_table = cx.location_table;
292 facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
293 |constraint: &OutlivesConstraint<'_>| {
294 if let Some(from_location) = constraint.locations.from_location() {
295 Either::Left(iter::once((
298 location_table.mid_index(from_location),
304 .map(move |location| (constraint.sup, constraint.sub, location)),
313 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
314 // We sometimes see MIR failures (notably predicate failures) due to
315 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
316 // to avoid reporting bugs in those cases.
317 tcx.sess.diagnostic().delay_span_bug(span, msg);
320 enum FieldAccessError {
321 OutOfRange { field_count: usize },
324 /// Verifies that MIR types are sane to not crash further checks.
326 /// The sanitize_XYZ methods here take an MIR object and compute its
327 /// type, calling `span_mirbug` and returning an error type if there
329 struct TypeVerifier<'a, 'b, 'tcx> {
330 cx: &'a mut TypeChecker<'b, 'tcx>,
331 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
333 errors_reported: bool,
336 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
337 fn visit_span(&mut self, span: &Span) {
338 if !span.is_dummy() {
339 self.last_span = *span;
343 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
344 self.sanitize_place(place, location, context);
347 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
348 self.super_constant(constant, location);
349 let ty = self.sanitize_type(constant, constant.literal.ty());
351 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
352 let live_region_vid =
353 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
357 .liveness_constraints
358 .add_element(live_region_vid, location);
361 if let Some(annotation_index) = constant.user_ty {
362 if let Err(terr) = self.cx.relate_type_and_user_type(
363 constant.literal.ty(),
364 ty::Variance::Invariant,
365 &UserTypeProjection { base: annotation_index, projs: vec![] },
366 location.to_locations(),
367 ConstraintCategory::Boring,
369 let annotation = &self.cx.user_type_annotations[annotation_index];
373 "bad constant user type {:?} vs {:?}: {:?}",
375 constant.literal.ty(),
380 let tcx = self.tcx();
381 let maybe_uneval = match constant.literal {
382 ConstantKind::Ty(ct) => match ct.val() {
383 ty::ConstKind::Unevaluated(uv) => Some(uv),
388 if let Some(uv) = maybe_uneval {
389 if let Some(promoted) = uv.promoted {
390 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
391 promoted: &Body<'tcx>,
394 if let Err(terr) = verifier.cx.eq_types(
397 location.to_locations(),
398 ConstraintCategory::Boring,
403 "bad promoted type ({:?}: {:?}): {:?}",
411 if !self.errors_reported {
412 let promoted_body = &self.promoted[promoted];
413 self.sanitize_promoted(promoted_body, location);
415 let promoted_ty = promoted_body.return_ty();
416 check_err(self, promoted_body, ty, promoted_ty);
419 if let Err(terr) = self.cx.fully_perform_op(
420 location.to_locations(),
421 ConstraintCategory::Boring,
422 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
423 constant.literal.ty(),
425 UserSubsts { substs: uv.substs, user_self_ty: None },
431 "bad constant type {:?} ({:?})",
437 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
438 let unnormalized_ty = tcx.type_of(static_def_id);
439 let locations = location.to_locations();
440 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
441 let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty;
443 if let Err(terr) = self.cx.eq_types(
447 ConstraintCategory::Boring,
449 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
453 if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() {
454 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
455 self.cx.normalize_and_prove_instantiated_predicates(
457 instantiated_predicates,
458 location.to_locations(),
464 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
465 self.super_rvalue(rvalue, location);
466 let rval_ty = rvalue.ty(self.body(), self.tcx());
467 self.sanitize_type(rvalue, rval_ty);
470 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
471 self.super_local_decl(local, local_decl);
472 self.sanitize_type(local_decl, local_decl.ty);
474 if let Some(user_ty) = &local_decl.user_ty {
475 for (user_ty, span) in user_ty.projections_and_spans() {
476 let ty = if !local_decl.is_nonref_binding() {
477 // If we have a binding of the form `let ref x: T = ..`
478 // then remove the outermost reference so we can check the
479 // type annotation for the remaining type.
480 if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
483 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
489 if let Err(terr) = self.cx.relate_type_and_user_type(
491 ty::Variance::Invariant,
493 Locations::All(*span),
494 ConstraintCategory::TypeAnnotation,
499 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
510 fn visit_body(&mut self, body: &Body<'tcx>) {
511 self.sanitize_type(&"return type", body.return_ty());
512 for local_decl in &body.local_decls {
513 self.sanitize_type(local_decl, local_decl.ty);
515 if self.errors_reported {
518 self.super_body(body);
522 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
524 cx: &'a mut TypeChecker<'b, 'tcx>,
525 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
527 TypeVerifier { promoted, last_span: cx.body.span, cx, errors_reported: false }
530 fn body(&self) -> &Body<'tcx> {
534 fn tcx(&self) -> TyCtxt<'tcx> {
538 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
539 if ty.has_escaping_bound_vars() || ty.references_error() {
540 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
546 /// Checks that the types internal to the `place` match up with
547 /// what would be expected.
552 context: PlaceContext,
554 debug!("sanitize_place: {:?}", place);
556 let mut place_ty = PlaceTy::from_ty(self.body().local_decls[place.local].ty);
558 for elem in place.projection.iter() {
559 if place_ty.variant_index.is_none() {
560 if place_ty.ty.references_error() {
561 assert!(self.errors_reported);
562 return PlaceTy::from_ty(self.tcx().ty_error());
565 place_ty = self.sanitize_projection(place_ty, elem, place, location);
568 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
569 let tcx = self.tcx();
570 let trait_ref = ty::TraitRef {
571 def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
572 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
575 // To have a `Copy` operand, the type `T` of the
576 // value must be `Copy`. Note that we prove that `T: Copy`,
577 // rather than using the `is_copy_modulo_regions`
578 // test. This is important because
579 // `is_copy_modulo_regions` ignores the resulting region
580 // obligations and assumes they pass. This can result in
581 // bounds from `Copy` impls being unsoundly ignored (e.g.,
582 // #29149). Note that we decide to use `Copy` before knowing
583 // whether the bounds fully apply: in effect, the rule is
584 // that if a value of some type could implement `Copy`, then
586 self.cx.prove_trait_ref(
588 location.to_locations(),
589 ConstraintCategory::CopyBound,
596 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
597 // Determine the constraints from the promoted MIR by running the type
598 // checker on the promoted MIR, then transfer the constraints back to
599 // the main MIR, changing the locations to the provided location.
601 let parent_body = mem::replace(&mut self.cx.body, promoted_body);
603 // Use new sets of constraints and closure bounds so that we can
604 // modify their locations.
605 let all_facts = &mut None;
606 let mut constraints = Default::default();
607 let mut closure_bounds = Default::default();
608 let mut liveness_constraints =
609 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
610 // Don't try to add borrow_region facts for the promoted MIR
612 let mut swap_constraints = |this: &mut Self| {
613 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
615 &mut this.cx.borrowck_context.constraints.outlives_constraints,
619 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
623 &mut this.cx.borrowck_context.constraints.liveness_constraints,
624 &mut liveness_constraints,
628 swap_constraints(self);
630 self.visit_body(&promoted_body);
632 if !self.errors_reported {
633 // if verifier failed, don't do further checks to avoid ICEs
634 self.cx.typeck_mir(promoted_body);
637 self.cx.body = parent_body;
638 // Merge the outlives constraints back in, at the given location.
639 swap_constraints(self);
641 let locations = location.to_locations();
642 for constraint in constraints.outlives().iter() {
643 let mut constraint = constraint.clone();
644 constraint.locations = locations;
645 if let ConstraintCategory::Return(_)
646 | ConstraintCategory::UseAsConst
647 | ConstraintCategory::UseAsStatic = constraint.category
649 // "Returning" from a promoted is an assignment to a
650 // temporary from the user's point of view.
651 constraint.category = ConstraintCategory::Boring;
653 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
655 for region in liveness_constraints.rows() {
656 // If the region is live at at least one location in the promoted MIR,
657 // then add a liveness constraint to the main MIR for this region
658 // at the location provided as an argument to this method
659 if liveness_constraints.get_elements(region).next().is_some() {
663 .liveness_constraints
664 .add_element(region, location);
668 if !closure_bounds.is_empty() {
669 let combined_bounds_mapping =
670 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
675 .closure_bounds_mapping
676 .insert(location, combined_bounds_mapping);
677 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
681 fn sanitize_projection(
688 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
689 let tcx = self.tcx();
690 let base_ty = base.ty;
692 ProjectionElem::Deref => {
693 let deref_ty = base_ty.builtin_deref(true);
694 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
695 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
698 ProjectionElem::Index(i) => {
699 let index_ty = Place::from(i).ty(self.body(), tcx).ty;
700 if index_ty != tcx.types.usize {
701 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
703 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
704 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
708 ProjectionElem::ConstantIndex { .. } => {
709 // consider verifying in-bounds
710 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
711 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
714 ProjectionElem::Subslice { from, to, from_end } => {
715 PlaceTy::from_ty(match base_ty.kind() {
716 ty::Array(inner, _) => {
717 assert!(!from_end, "array subslices should not use from_end");
718 tcx.mk_array(*inner, to - from)
721 assert!(from_end, "slice subslices should use from_end");
724 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
727 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
728 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
729 if index.as_usize() >= adt_def.variants().len() {
730 PlaceTy::from_ty(span_mirbug_and_err!(
733 "cast to variant #{:?} but enum only has {:?}",
735 adt_def.variants().len()
738 PlaceTy { ty: base_ty, variant_index: Some(index) }
741 // We do not need to handle generators here, because this runs
742 // before the generator transform stage.
744 let ty = if let Some(name) = maybe_name {
745 span_mirbug_and_err!(
748 "can't downcast {:?} as {:?}",
753 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
758 ProjectionElem::Field(field, fty) => {
759 let fty = self.sanitize_type(place, fty);
760 let fty = self.cx.normalize(fty, location);
761 match self.field_ty(place, base, field, location) {
763 let ty = self.cx.normalize(ty, location);
764 if let Err(terr) = self.cx.eq_types(
767 location.to_locations(),
768 ConstraintCategory::Boring,
773 "bad field access ({:?}: {:?}): {:?}",
780 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
783 "accessed field #{} but variant only has {}",
788 PlaceTy::from_ty(fty)
793 fn error(&mut self) -> Ty<'tcx> {
794 self.errors_reported = true;
795 self.tcx().ty_error()
800 parent: &dyn fmt::Debug,
801 base_ty: PlaceTy<'tcx>,
804 ) -> Result<Ty<'tcx>, FieldAccessError> {
805 let tcx = self.tcx();
807 let (variant, substs) = match base_ty {
808 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
809 ty::Adt(adt_def, substs) => (adt_def.variant(variant_index), substs),
810 ty::Generator(def_id, substs, _) => {
811 let mut variants = substs.as_generator().state_tys(def_id, tcx);
812 let Some(mut variant) = variants.nth(variant_index.into()) else {
814 "variant_index of generator out of range: {:?}/{:?}",
816 substs.as_generator().state_tys(def_id, tcx).count()
819 return match variant.nth(field.index()) {
821 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
824 _ => bug!("can't have downcast of non-adt non-generator type"),
826 PlaceTy { ty, variant_index: None } => match *ty.kind() {
827 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
828 (adt_def.variant(VariantIdx::new(0)), substs)
830 ty::Closure(_, substs) => {
838 None => Err(FieldAccessError::OutOfRange {
839 field_count: substs.as_closure().upvar_tys().count(),
843 ty::Generator(_, substs, _) => {
844 // Only prefix fields (upvars and current state) are
845 // accessible without a variant index.
846 return match substs.as_generator().prefix_tys().nth(field.index()) {
848 None => Err(FieldAccessError::OutOfRange {
849 field_count: substs.as_generator().prefix_tys().count(),
854 return match tys.get(field.index()) {
856 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
860 return Ok(span_mirbug_and_err!(
863 "can't project out of {:?}",
870 if let Some(field) = variant.fields.get(field.index()) {
871 Ok(self.cx.normalize(field.ty(tcx, substs), location))
873 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
878 /// The MIR type checker. Visits the MIR and enforces all the
879 /// constraints needed for it to be valid and well-typed. Along the
880 /// way, it accrues region constraints -- these can later be used by
881 /// NLL region checking.
882 struct TypeChecker<'a, 'tcx> {
883 infcx: &'a InferCtxt<'a, 'tcx>,
884 param_env: ty::ParamEnv<'tcx>,
886 body: &'a Body<'tcx>,
887 /// User type annotations are shared between the main MIR and the MIR of
888 /// all of the promoted items.
889 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
890 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
891 implicit_region_bound: ty::Region<'tcx>,
892 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
893 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
896 struct BorrowCheckContext<'a, 'tcx> {
897 pub(crate) universal_regions: &'a UniversalRegions<'tcx>,
898 location_table: &'a LocationTable,
899 all_facts: &'a mut Option<AllFacts>,
900 borrow_set: &'a BorrowSet<'tcx>,
901 pub(crate) constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
902 upvars: &'a [Upvar<'tcx>],
905 crate struct MirTypeckResults<'tcx> {
906 crate constraints: MirTypeckRegionConstraints<'tcx>,
907 crate universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
908 crate opaque_type_values: VecMap<OpaqueTypeKey<'tcx>, (OpaqueHiddenType<'tcx>, OpaqueTyOrigin)>,
911 /// A collection of region constraints that must be satisfied for the
912 /// program to be considered well-typed.
913 crate struct MirTypeckRegionConstraints<'tcx> {
914 /// Maps from a `ty::Placeholder` to the corresponding
915 /// `PlaceholderIndex` bit that we will use for it.
917 /// To keep everything in sync, do not insert this set
918 /// directly. Instead, use the `placeholder_region` helper.
919 crate placeholder_indices: PlaceholderIndices,
921 /// Each time we add a placeholder to `placeholder_indices`, we
922 /// also create a corresponding "representative" region vid for
923 /// that wraps it. This vector tracks those. This way, when we
924 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
925 /// the same underlying `RegionVid`.
926 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
928 /// In general, the type-checker is not responsible for enforcing
929 /// liveness constraints; this job falls to the region inferencer,
930 /// which performs a liveness analysis. However, in some limited
931 /// cases, the MIR type-checker creates temporary regions that do
932 /// not otherwise appear in the MIR -- in particular, the
933 /// late-bound regions that it instantiates at call-sites -- and
934 /// hence it must report on their liveness constraints.
935 crate liveness_constraints: LivenessValues<RegionVid>,
937 crate outlives_constraints: OutlivesConstraintSet<'tcx>,
939 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
941 crate closure_bounds_mapping:
942 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
944 crate universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
946 crate type_tests: Vec<TypeTest<'tcx>>,
949 impl<'tcx> MirTypeckRegionConstraints<'tcx> {
950 fn placeholder_region(
952 infcx: &InferCtxt<'_, 'tcx>,
953 placeholder: ty::PlaceholderRegion,
954 ) -> ty::Region<'tcx> {
955 let placeholder_index = self.placeholder_indices.insert(placeholder);
956 match self.placeholder_index_to_region.get(placeholder_index) {
959 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
960 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
961 self.placeholder_index_to_region.push(region);
968 /// The `Locations` type summarizes *where* region constraints are
969 /// required to hold. Normally, this is at a particular point which
970 /// created the obligation, but for constraints that the user gave, we
971 /// want the constraint to hold at all points.
972 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
974 /// Indicates that a type constraint should always be true. This
975 /// is particularly important in the new borrowck analysis for
976 /// things like the type of the return slot. Consider this
980 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
982 /// return &y; // error
986 /// Here, we wind up with the signature from the return type being
987 /// something like `&'1 u32` where `'1` is a universal region. But
988 /// the type of the return slot `_0` is something like `&'2 u32`
989 /// where `'2` is an existential region variable. The type checker
990 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
991 /// older NLL analysis, we required this only at the entry point
992 /// to the function. By the nature of the constraints, this wound
993 /// up propagating to all points reachable from start (because
994 /// `'1` -- as a universal region -- is live everywhere). In the
995 /// newer analysis, though, this doesn't work: `_0` is considered
996 /// dead at the start (it has no usable value) and hence this type
997 /// equality is basically a no-op. Then, later on, when we do `_0
998 /// = &'3 y`, that region `'3` never winds up related to the
999 /// universal region `'1` and hence no error occurs. Therefore, we
1000 /// use Locations::All instead, which ensures that the `'1` and
1001 /// `'2` are equal everything. We also use this for other
1002 /// user-given type annotations; e.g., if the user wrote `let mut
1003 /// x: &'static u32 = ...`, we would ensure that all values
1004 /// assigned to `x` are of `'static` lifetime.
1006 /// The span points to the place the constraint arose. For example,
1007 /// it points to the type in a user-given type annotation. If
1008 /// there's no sensible span then it's DUMMY_SP.
1011 /// An outlives constraint that only has to hold at a single location,
1012 /// usually it represents a point where references flow from one spot to
1013 /// another (e.g., `x = y`)
1018 pub fn from_location(&self) -> Option<Location> {
1020 Locations::All(_) => None,
1021 Locations::Single(from_location) => Some(*from_location),
1025 /// Gets a span representing the location.
1026 pub fn span(&self, body: &Body<'_>) -> Span {
1028 Locations::All(span) => *span,
1029 Locations::Single(l) => body.source_info(*l).span,
1034 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1036 infcx: &'a InferCtxt<'a, 'tcx>,
1037 body: &'a Body<'tcx>,
1038 param_env: ty::ParamEnv<'tcx>,
1039 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1040 implicit_region_bound: ty::Region<'tcx>,
1041 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1043 let mut checker = Self {
1045 last_span: DUMMY_SP,
1047 user_type_annotations: &body.user_type_annotations,
1050 implicit_region_bound,
1052 reported_errors: Default::default(),
1054 checker.check_user_type_annotations();
1058 fn body(&self) -> &Body<'tcx> {
1062 fn unsized_feature_enabled(&self) -> bool {
1063 let features = self.tcx().features();
1064 features.unsized_locals || features.unsized_fn_params
1067 /// Equate the inferred type and the annotated type for user type annotations
1068 #[instrument(skip(self), level = "debug")]
1069 fn check_user_type_annotations(&mut self) {
1070 debug!(?self.user_type_annotations);
1071 for user_annotation in self.user_type_annotations {
1072 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1073 let inferred_ty = self.normalize(inferred_ty, Locations::All(span));
1074 let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1076 UserType::Ty(mut ty) => {
1077 ty = self.normalize(ty, Locations::All(span));
1079 if let Err(terr) = self.eq_types(
1082 Locations::All(span),
1083 ConstraintCategory::BoringNoLocation,
1088 "bad user type ({:?} = {:?}): {:?}",
1095 self.prove_predicate(
1096 ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into()))
1097 .to_predicate(self.tcx()),
1098 Locations::All(span),
1099 ConstraintCategory::TypeAnnotation,
1102 UserType::TypeOf(def_id, user_substs) => {
1103 if let Err(terr) = self.fully_perform_op(
1104 Locations::All(span),
1105 ConstraintCategory::BoringNoLocation,
1106 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1115 "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}",
1119 self.tcx().type_of(def_id),
1128 #[instrument(skip(self, data), level = "debug")]
1129 fn push_region_constraints(
1131 locations: Locations,
1132 category: ConstraintCategory,
1133 data: &QueryRegionConstraints<'tcx>,
1135 debug!("constraints generated: {:#?}", data);
1137 constraint_conversion::ConstraintConversion::new(
1139 self.borrowck_context.universal_regions,
1140 self.region_bound_pairs,
1141 Some(self.implicit_region_bound),
1145 &mut self.borrowck_context.constraints,
1150 /// Try to relate `sub <: sup`
1155 locations: Locations,
1156 category: ConstraintCategory,
1158 // Use this order of parameters because the sup type is usually the
1159 // "expected" type in diagnostics.
1160 self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
1163 #[instrument(skip(self, category), level = "debug")]
1168 locations: Locations,
1169 category: ConstraintCategory,
1171 self.relate_types(expected, ty::Variance::Invariant, found, locations, category)
1174 #[instrument(skip(self), level = "debug")]
1175 fn relate_type_and_user_type(
1179 user_ty: &UserTypeProjection,
1180 locations: Locations,
1181 category: ConstraintCategory,
1183 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1184 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1186 let tcx = self.infcx.tcx;
1188 for proj in &user_ty.projs {
1189 let projected_ty = curr_projected_ty.projection_ty_core(
1194 let ty = this.field_ty(tcx, field);
1195 self.normalize(ty, locations)
1198 curr_projected_ty = projected_ty;
1201 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1202 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1205 let ty = curr_projected_ty.ty;
1206 self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1211 fn tcx(&self) -> TyCtxt<'tcx> {
1215 #[instrument(skip(self, body, location), level = "debug")]
1216 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1217 let tcx = self.tcx();
1219 StatementKind::Assign(box (ref place, ref rv)) => {
1220 // Assignments to temporaries are not "interesting";
1221 // they are not caused by the user, but rather artifacts
1222 // of lowering. Assignments to other sorts of places *are* interesting
1224 let category = match place.as_local() {
1225 Some(RETURN_PLACE) => {
1226 let defining_ty = &self.borrowck_context.universal_regions.defining_ty;
1227 if defining_ty.is_const() {
1228 if tcx.is_static(defining_ty.def_id()) {
1229 ConstraintCategory::UseAsStatic
1231 ConstraintCategory::UseAsConst
1234 ConstraintCategory::Return(ReturnConstraint::Normal)
1239 body.local_decls[l].local_info,
1240 Some(box LocalInfo::AggregateTemp)
1243 ConstraintCategory::Usage
1245 Some(l) if !body.local_decls[l].is_user_variable() => {
1246 ConstraintCategory::Boring
1248 _ => ConstraintCategory::Assignment,
1251 "assignment category: {:?} {:?}",
1253 place.as_local().map(|l| &body.local_decls[l])
1256 let place_ty = place.ty(body, tcx).ty;
1257 let place_ty = self.normalize(place_ty, location);
1258 let rv_ty = rv.ty(body, tcx);
1259 let rv_ty = self.normalize(rv_ty, location);
1261 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1266 "bad assignment ({:?} = {:?}): {:?}",
1273 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1274 if let Err(terr) = self.relate_type_and_user_type(
1276 ty::Variance::Invariant,
1277 &UserTypeProjection { base: annotation_index, projs: vec![] },
1278 location.to_locations(),
1279 ConstraintCategory::Boring,
1281 let annotation = &self.user_type_annotations[annotation_index];
1285 "bad user type on rvalue ({:?} = {:?}): {:?}",
1293 self.check_rvalue(body, rv, location);
1294 if !self.unsized_feature_enabled() {
1295 let trait_ref = ty::TraitRef {
1296 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1297 substs: tcx.mk_substs_trait(place_ty, &[]),
1299 self.prove_trait_ref(
1301 location.to_locations(),
1302 ConstraintCategory::SizedBound,
1306 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1307 let place_ty = place.ty(body, tcx).ty;
1308 if let Err(terr) = self.relate_type_and_user_type(
1312 Locations::All(stmt.source_info.span),
1313 ConstraintCategory::TypeAnnotation,
1315 let annotation = &self.user_type_annotations[projection.base];
1319 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1327 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
1330 stmt.source_info.span,
1331 "Unexpected StatementKind::CopyNonOverlapping, should only appear after lowering_intrinsics",
1333 StatementKind::FakeRead(..)
1334 | StatementKind::StorageLive(..)
1335 | StatementKind::StorageDead(..)
1336 | StatementKind::Retag { .. }
1337 | StatementKind::Coverage(..)
1338 | StatementKind::Nop => {}
1339 StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
1340 bug!("Statement not allowed in this MIR phase")
1345 #[instrument(skip(self, body, term_location), level = "debug")]
1346 fn check_terminator(
1349 term: &Terminator<'tcx>,
1350 term_location: Location,
1352 let tcx = self.tcx();
1354 TerminatorKind::Goto { .. }
1355 | TerminatorKind::Resume
1356 | TerminatorKind::Abort
1357 | TerminatorKind::Return
1358 | TerminatorKind::GeneratorDrop
1359 | TerminatorKind::Unreachable
1360 | TerminatorKind::Drop { .. }
1361 | TerminatorKind::FalseEdge { .. }
1362 | TerminatorKind::FalseUnwind { .. }
1363 | TerminatorKind::InlineAsm { .. } => {
1364 // no checks needed for these
1367 TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1368 let place_ty = place.ty(body, tcx).ty;
1369 let rv_ty = value.ty(body, tcx);
1371 let locations = term_location.to_locations();
1373 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1378 "bad DropAndReplace ({:?} = {:?}): {:?}",
1385 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1386 self.check_operand(discr, term_location);
1388 let discr_ty = discr.ty(body, tcx);
1389 if let Err(terr) = self.sub_types(
1392 term_location.to_locations(),
1393 ConstraintCategory::Assignment,
1398 "bad SwitchInt ({:?} on {:?}): {:?}",
1404 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1405 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1407 // FIXME: check the values
1409 TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1410 self.check_operand(func, term_location);
1412 self.check_operand(arg, term_location);
1415 let func_ty = func.ty(body, tcx);
1416 debug!("check_terminator: call, func_ty={:?}", func_ty);
1417 let sig = match func_ty.kind() {
1418 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1420 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1424 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1425 term.source_info.span,
1426 LateBoundRegionConversionTime::FnCall,
1429 let sig = self.normalize(sig, term_location);
1430 self.check_call_dest(body, term, &sig, destination, term_location);
1432 self.prove_predicates(
1433 sig.inputs_and_output
1435 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1436 term_location.to_locations(),
1437 ConstraintCategory::Boring,
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: &Option<(Place<'tcx>, BasicBlock)>,
1509 term_location: Location,
1511 let tcx = self.tcx();
1512 match *destination {
1513 Some((ref dest, _target_block)) => {
1514 let dest_ty = dest.ty(body, tcx).ty;
1515 let dest_ty = self.normalize(dest_ty, term_location);
1516 let category = match dest.as_local() {
1517 Some(RETURN_PLACE) => {
1518 if let BorrowCheckContext {
1522 DefiningTy::Const(def_id, _)
1523 | DefiningTy::InlineConst(def_id, _),
1527 } = self.borrowck_context
1529 if tcx.is_static(*def_id) {
1530 ConstraintCategory::UseAsStatic
1532 ConstraintCategory::UseAsConst
1535 ConstraintCategory::Return(ReturnConstraint::Normal)
1538 Some(l) if !body.local_decls[l].is_user_variable() => {
1539 ConstraintCategory::Boring
1541 _ => ConstraintCategory::Assignment,
1544 let locations = term_location.to_locations();
1546 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1550 "call dest mismatch ({:?} <- {:?}): {:?}",
1557 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1558 // this check is done at `check_local`.
1559 if self.unsized_feature_enabled() {
1560 let span = term.source_info.span;
1561 self.ensure_place_sized(dest_ty, span);
1567 .conservative_is_privately_uninhabited(self.param_env.and(sig.output()))
1569 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1575 fn check_call_inputs(
1578 term: &Terminator<'tcx>,
1579 sig: &ty::FnSig<'tcx>,
1580 args: &[Operand<'tcx>],
1581 term_location: Location,
1582 from_hir_call: bool,
1584 debug!("check_call_inputs({:?}, {:?})", sig, args);
1585 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1586 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1588 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1589 let op_arg_ty = op_arg.ty(body, self.tcx());
1590 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1591 let category = if from_hir_call {
1592 ConstraintCategory::CallArgument
1594 ConstraintCategory::Boring
1597 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
1602 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1612 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1613 let is_cleanup = block_data.is_cleanup;
1614 self.last_span = block_data.terminator().source_info.span;
1615 match block_data.terminator().kind {
1616 TerminatorKind::Goto { target } => {
1617 self.assert_iscleanup(body, block_data, target, is_cleanup)
1619 TerminatorKind::SwitchInt { ref targets, .. } => {
1620 for target in targets.all_targets() {
1621 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1624 TerminatorKind::Resume => {
1626 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1629 TerminatorKind::Abort => {
1631 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1634 TerminatorKind::Return => {
1636 span_mirbug!(self, block_data, "return on cleanup block")
1639 TerminatorKind::GeneratorDrop { .. } => {
1641 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1644 TerminatorKind::Yield { resume, drop, .. } => {
1646 span_mirbug!(self, block_data, "yield in cleanup block")
1648 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1649 if let Some(drop) = drop {
1650 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1653 TerminatorKind::Unreachable => {}
1654 TerminatorKind::Drop { target, unwind, .. }
1655 | TerminatorKind::DropAndReplace { target, unwind, .. }
1656 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1657 self.assert_iscleanup(body, block_data, target, is_cleanup);
1658 if let Some(unwind) = unwind {
1660 span_mirbug!(self, block_data, "unwind on cleanup block")
1662 self.assert_iscleanup(body, block_data, unwind, true);
1665 TerminatorKind::Call { ref destination, cleanup, .. } => {
1666 if let &Some((_, target)) = destination {
1667 self.assert_iscleanup(body, block_data, target, is_cleanup);
1669 if let Some(cleanup) = cleanup {
1671 span_mirbug!(self, block_data, "cleanup on cleanup block")
1673 self.assert_iscleanup(body, block_data, cleanup, true);
1676 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1677 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1678 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1680 TerminatorKind::FalseUnwind { real_target, unwind } => {
1681 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1682 if let Some(unwind) = unwind {
1684 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1686 self.assert_iscleanup(body, block_data, unwind, true);
1689 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
1690 if let Some(target) = destination {
1691 self.assert_iscleanup(body, block_data, target, is_cleanup);
1693 if let Some(cleanup) = cleanup {
1695 span_mirbug!(self, block_data, "cleanup on cleanup block")
1697 self.assert_iscleanup(body, block_data, cleanup, true);
1703 fn assert_iscleanup(
1706 ctxt: &dyn fmt::Debug,
1710 if body[bb].is_cleanup != iscleanuppad {
1711 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1715 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1716 match body.local_kind(local) {
1717 LocalKind::ReturnPointer | LocalKind::Arg => {
1718 // return values of normal functions are required to be
1719 // sized by typeck, but return values of ADT constructors are
1720 // not because we don't include a `Self: Sized` bounds on them.
1722 // Unbound parts of arguments were never required to be Sized
1723 // - maybe we should make that a warning.
1726 LocalKind::Var | LocalKind::Temp => {}
1729 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1730 // and nullary ops are checked in `check_call_dest`.
1731 if !self.unsized_feature_enabled() {
1732 let span = local_decl.source_info.span;
1733 let ty = local_decl.ty;
1734 self.ensure_place_sized(ty, span);
1738 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1739 let tcx = self.tcx();
1741 // Erase the regions from `ty` to get a global type. The
1742 // `Sized` bound in no way depends on precise regions, so this
1743 // shouldn't affect `is_sized`.
1744 let erased_ty = tcx.erase_regions(ty);
1745 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1746 // in current MIR construction, all non-control-flow rvalue
1747 // expressions evaluate through `as_temp` or `into` a return
1748 // slot or local, so to find all unsized rvalues it is enough
1749 // to check all temps, return slots and locals.
1750 if self.reported_errors.replace((ty, span)).is_none() {
1751 let mut diag = struct_span_err!(
1755 "cannot move a value of type {0}: the size of {0} \
1756 cannot be statically determined",
1760 // While this is located in `nll::typeck` this error is not
1761 // an NLL error, it's a required check to prevent creation
1762 // of unsized rvalues in a call expression.
1768 fn aggregate_field_ty(
1770 ak: &AggregateKind<'tcx>,
1773 ) -> Result<Ty<'tcx>, FieldAccessError> {
1774 let tcx = self.tcx();
1777 AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => {
1778 let def = tcx.adt_def(adt_did);
1779 let variant = &def.variant(variant_index);
1780 let adj_field_index = active_field_index.unwrap_or(field_index);
1781 if let Some(field) = variant.fields.get(adj_field_index) {
1782 Ok(self.normalize(field.ty(tcx, substs), location))
1784 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1787 AggregateKind::Closure(_, substs) => {
1788 match substs.as_closure().upvar_tys().nth(field_index) {
1790 None => Err(FieldAccessError::OutOfRange {
1791 field_count: substs.as_closure().upvar_tys().count(),
1795 AggregateKind::Generator(_, substs, _) => {
1796 // It doesn't make sense to look at a field beyond the prefix;
1797 // these require a variant index, and are not initialized in
1798 // aggregate rvalues.
1799 match substs.as_generator().prefix_tys().nth(field_index) {
1801 None => Err(FieldAccessError::OutOfRange {
1802 field_count: substs.as_generator().prefix_tys().count(),
1806 AggregateKind::Array(ty) => Ok(ty),
1807 AggregateKind::Tuple => {
1808 unreachable!("This should have been covered in check_rvalues");
1813 fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1814 if let Operand::Constant(constant) = op {
1815 let maybe_uneval = match constant.literal {
1816 ConstantKind::Ty(ct) => match ct.val() {
1817 ty::ConstKind::Unevaluated(uv) => Some(uv),
1822 if let Some(uv) = maybe_uneval {
1823 if uv.promoted.is_none() {
1824 let tcx = self.tcx();
1825 let def_id = uv.def.def_id_for_type_of();
1826 if tcx.def_kind(def_id) == DefKind::InlineConst {
1827 let predicates = self.prove_closure_bounds(
1829 def_id.expect_local(),
1833 self.normalize_and_prove_instantiated_predicates(
1836 location.to_locations(),
1844 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1845 let tcx = self.tcx();
1848 Rvalue::Aggregate(ak, ops) => {
1850 self.check_operand(op, location);
1852 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1855 Rvalue::Repeat(operand, len) => {
1856 self.check_operand(operand, location);
1858 // If the length cannot be evaluated we must assume that the length can be larger
1860 // If the length is larger than 1, the repeat expression will need to copy the
1861 // element, so we require the `Copy` trait.
1862 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1864 Operand::Copy(..) | Operand::Constant(..) => {
1865 // These are always okay: direct use of a const, or a value that can evidently be copied.
1867 Operand::Move(place) => {
1868 // Make sure that repeated elements implement `Copy`.
1869 let span = body.source_info(location).span;
1870 let ty = operand.ty(body, tcx);
1871 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1872 let ccx = ConstCx::new_with_param_env(tcx, body, self.param_env);
1874 is_const_fn_in_array_repeat_expression(&ccx, &place, &body);
1876 debug!("check_rvalue: is_const_fn={:?}", is_const_fn);
1878 let def_id = body.source.def_id().expect_local();
1879 let obligation = traits::Obligation::new(
1880 ObligationCause::new(
1882 self.tcx().hir().local_def_id_to_hir_id(def_id),
1883 traits::ObligationCauseCode::RepeatElementCopy {
1888 ty::Binder::dummy(ty::TraitRef::new(
1889 self.tcx().require_lang_item(
1891 Some(self.last_span),
1893 tcx.mk_substs_trait(ty, &[]),
1896 .to_predicate(self.tcx()),
1898 self.infcx.report_selection_error(
1901 &traits::SelectionError::Unimplemented,
1910 &Rvalue::NullaryOp(_, ty) => {
1911 let trait_ref = ty::TraitRef {
1912 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1913 substs: tcx.mk_substs_trait(ty, &[]),
1916 self.prove_trait_ref(
1918 location.to_locations(),
1919 ConstraintCategory::SizedBound,
1923 Rvalue::ShallowInitBox(operand, ty) => {
1924 self.check_operand(operand, location);
1926 let trait_ref = ty::TraitRef {
1927 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1928 substs: tcx.mk_substs_trait(*ty, &[]),
1931 self.prove_trait_ref(
1933 location.to_locations(),
1934 ConstraintCategory::SizedBound,
1938 Rvalue::Cast(cast_kind, op, ty) => {
1939 self.check_operand(op, location);
1942 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1943 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1945 // The type that we see in the fcx is like
1946 // `foo::<'a, 'b>`, where `foo` is the path to a
1947 // function definition. When we extract the
1948 // signature, it comes from the `fn_sig` query,
1949 // and hence may contain unnormalized results.
1950 let fn_sig = self.normalize(fn_sig, location);
1952 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1954 if let Err(terr) = self.eq_types(
1957 location.to_locations(),
1958 ConstraintCategory::Cast,
1963 "equating {:?} with {:?} yields {:?}",
1971 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
1972 let sig = match op.ty(body, tcx).kind() {
1973 ty::Closure(_, substs) => substs.as_closure().sig(),
1976 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
1978 if let Err(terr) = self.eq_types(
1981 location.to_locations(),
1982 ConstraintCategory::Cast,
1987 "equating {:?} with {:?} yields {:?}",
1995 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
1996 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1998 // The type that we see in the fcx is like
1999 // `foo::<'a, 'b>`, where `foo` is the path to a
2000 // function definition. When we extract the
2001 // signature, it comes from the `fn_sig` query,
2002 // and hence may contain unnormalized results.
2003 let fn_sig = self.normalize(fn_sig, location);
2005 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2007 if let Err(terr) = self.eq_types(
2010 location.to_locations(),
2011 ConstraintCategory::Cast,
2016 "equating {:?} with {:?} yields {:?}",
2024 CastKind::Pointer(PointerCast::Unsize) => {
2026 let trait_ref = ty::TraitRef {
2028 .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2029 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2032 self.prove_trait_ref(
2034 location.to_locations(),
2035 ConstraintCategory::Cast,
2039 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2040 let ty::RawPtr(ty::TypeAndMut {
2042 mutbl: hir::Mutability::Mut,
2043 }) = op.ty(body, tcx).kind() else {
2047 "unexpected base type for cast {:?}",
2052 let ty::RawPtr(ty::TypeAndMut {
2054 mutbl: hir::Mutability::Not,
2055 }) = ty.kind() else {
2059 "unexpected target type for cast {:?}",
2064 if let Err(terr) = self.sub_types(
2067 location.to_locations(),
2068 ConstraintCategory::Cast,
2073 "relating {:?} with {:?} yields {:?}",
2081 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2082 let ty_from = op.ty(body, tcx);
2084 let opt_ty_elem_mut = match ty_from.kind() {
2085 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2086 match array_ty.kind() {
2087 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2094 let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
2098 "ArrayToPointer cast from unexpected type {:?}",
2104 let (ty_to, ty_to_mut) = match ty.kind() {
2105 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2112 "ArrayToPointer cast to unexpected type {:?}",
2119 if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2123 "ArrayToPointer cast from const {:?} to mut {:?}",
2130 if let Err(terr) = self.sub_types(
2133 location.to_locations(),
2134 ConstraintCategory::Cast,
2139 "relating {:?} with {:?} yields {:?}",
2148 let ty_from = op.ty(body, tcx);
2149 let cast_ty_from = CastTy::from_ty(ty_from);
2150 let cast_ty_to = CastTy::from_ty(*ty);
2151 match (cast_ty_from, cast_ty_to) {
2153 | (_, None | Some(CastTy::FnPtr))
2154 | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2155 | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => {
2156 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2159 Some(CastTy::Int(_)),
2160 Some(CastTy::Int(_) | CastTy::Float | CastTy::Ptr(_)),
2162 | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float))
2163 | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_)))
2164 | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (),
2170 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2171 self.add_reborrow_constraint(&body, location, *region, borrowed_place);
2175 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2178 self.check_operand(left, location);
2179 self.check_operand(right, location);
2181 let ty_left = left.ty(body, tcx);
2182 match ty_left.kind() {
2183 // Types with regions are comparable if they have a common super-type.
2184 ty::RawPtr(_) | ty::FnPtr(_) => {
2185 let ty_right = right.ty(body, tcx);
2186 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2187 kind: TypeVariableOriginKind::MiscVariable,
2188 span: body.source_info(location).span,
2193 location.to_locations(),
2194 ConstraintCategory::Boring,
2196 .unwrap_or_else(|err| {
2197 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2199 if let Err(terr) = self.sub_types(
2202 location.to_locations(),
2203 ConstraintCategory::Boring,
2208 "unexpected comparison types {:?} and {:?} yields {:?}",
2215 // For types with no regions we can just check that the
2216 // both operands have the same type.
2217 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2218 if ty_left == right.ty(body, tcx) => {}
2219 // Other types are compared by trait methods, not by
2220 // `Rvalue::BinaryOp`.
2224 "unexpected comparison types {:?} and {:?}",
2231 Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => {
2232 self.check_operand(operand, location);
2235 Rvalue::BinaryOp(_, box (left, right))
2236 | Rvalue::CheckedBinaryOp(_, box (left, right)) => {
2237 self.check_operand(left, location);
2238 self.check_operand(right, location);
2241 Rvalue::AddressOf(..)
2242 | Rvalue::ThreadLocalRef(..)
2244 | Rvalue::Discriminant(..) => {}
2248 /// If this rvalue supports a user-given type annotation, then
2249 /// extract and return it. This represents the final type of the
2250 /// rvalue and will be unified with the inferred type.
2251 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2254 | Rvalue::ThreadLocalRef(_)
2255 | Rvalue::Repeat(..)
2257 | Rvalue::AddressOf(..)
2260 | Rvalue::ShallowInitBox(..)
2261 | Rvalue::BinaryOp(..)
2262 | Rvalue::CheckedBinaryOp(..)
2263 | Rvalue::NullaryOp(..)
2264 | Rvalue::UnaryOp(..)
2265 | Rvalue::Discriminant(..) => None,
2267 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2268 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2269 AggregateKind::Array(_) => None,
2270 AggregateKind::Tuple => None,
2271 AggregateKind::Closure(_, _) => None,
2272 AggregateKind::Generator(_, _, _) => None,
2277 fn check_aggregate_rvalue(
2280 rvalue: &Rvalue<'tcx>,
2281 aggregate_kind: &AggregateKind<'tcx>,
2282 operands: &[Operand<'tcx>],
2285 let tcx = self.tcx();
2287 self.prove_aggregate_predicates(aggregate_kind, location);
2289 if *aggregate_kind == AggregateKind::Tuple {
2290 // tuple rvalue field type is always the type of the op. Nothing to check here.
2294 for (i, operand) in operands.iter().enumerate() {
2295 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2296 Ok(field_ty) => field_ty,
2297 Err(FieldAccessError::OutOfRange { field_count }) => {
2301 "accessed field #{} but variant only has {}",
2308 let operand_ty = operand.ty(body, tcx);
2309 let operand_ty = self.normalize(operand_ty, location);
2311 if let Err(terr) = self.sub_types(
2314 location.to_locations(),
2315 ConstraintCategory::Boring,
2320 "{:?} is not a subtype of {:?}: {:?}",
2329 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2333 /// - `location`: the location `L` where the borrow expression occurs
2334 /// - `borrow_region`: the region `'a` associated with the borrow
2335 /// - `borrowed_place`: the place `P` being borrowed
2336 fn add_reborrow_constraint(
2340 borrow_region: ty::Region<'tcx>,
2341 borrowed_place: &Place<'tcx>,
2343 // These constraints are only meaningful during borrowck:
2344 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2345 self.borrowck_context;
2347 // In Polonius mode, we also push a `loan_issued_at` fact
2348 // linking the loan to the region (in some cases, though,
2349 // there is no loan associated with this borrow expression --
2350 // that occurs when we are borrowing an unsafe place, for
2352 if let Some(all_facts) = all_facts {
2353 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2354 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2355 let region_vid = borrow_region.to_region_vid();
2356 all_facts.loan_issued_at.push((
2359 location_table.mid_index(location),
2364 // If we are reborrowing the referent of another reference, we
2365 // need to add outlives relationships. In a case like `&mut
2366 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2367 // need to ensure that `'b: 'a`.
2370 "add_reborrow_constraint({:?}, {:?}, {:?})",
2371 location, borrow_region, borrowed_place
2374 let mut cursor = borrowed_place.projection.as_ref();
2375 let tcx = self.infcx.tcx;
2376 let field = path_utils::is_upvar_field_projection(
2378 &self.borrowck_context.upvars,
2379 borrowed_place.as_ref(),
2382 let category = if let Some(field) = field {
2383 ConstraintCategory::ClosureUpvar(field)
2385 ConstraintCategory::Boring
2388 while let [proj_base @ .., elem] = cursor {
2391 debug!("add_reborrow_constraint - iteration {:?}", elem);
2394 ProjectionElem::Deref => {
2395 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2397 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2398 match base_ty.kind() {
2399 ty::Ref(ref_region, _, mutbl) => {
2400 constraints.outlives_constraints.push(OutlivesConstraint {
2401 sup: ref_region.to_region_vid(),
2402 sub: borrow_region.to_region_vid(),
2403 locations: location.to_locations(),
2405 variance_info: ty::VarianceDiagInfo::default(),
2409 hir::Mutability::Not => {
2410 // Immutable reference. We don't need the base
2411 // to be valid for the entire lifetime of
2415 hir::Mutability::Mut => {
2416 // Mutable reference. We *do* need the base
2417 // to be valid, because after the base becomes
2418 // invalid, someone else can use our mutable deref.
2420 // This is in order to make the following function
2423 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2428 // As otherwise you could clone `&mut T` using the
2429 // following function:
2431 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2432 // let my_clone = unsafe_deref(&'a x);
2441 // deref of raw pointer, guaranteed to be valid
2444 ty::Adt(def, _) if def.is_box() => {
2445 // deref of `Box`, need the base to be valid - propagate
2447 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2450 ProjectionElem::Field(..)
2451 | ProjectionElem::Downcast(..)
2452 | ProjectionElem::Index(..)
2453 | ProjectionElem::ConstantIndex { .. }
2454 | ProjectionElem::Subslice { .. } => {
2455 // other field access
2461 fn prove_aggregate_predicates(
2463 aggregate_kind: &AggregateKind<'tcx>,
2466 let tcx = self.tcx();
2469 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2470 aggregate_kind, location
2473 let (def_id, instantiated_predicates) = match aggregate_kind {
2474 AggregateKind::Adt(adt_did, _, substs, _, _) => {
2475 (*adt_did, tcx.predicates_of(*adt_did).instantiate(tcx, substs))
2478 // For closures, we have some **extra requirements** we
2480 // have to check. In particular, in their upvars and
2481 // signatures, closures often reference various regions
2482 // from the surrounding function -- we call those the
2483 // closure's free regions. When we borrow-check (and hence
2484 // region-check) closures, we may find that the closure
2485 // requires certain relationships between those free
2486 // regions. However, because those free regions refer to
2487 // portions of the CFG of their caller, the closure is not
2488 // in a position to verify those relationships. In that
2489 // case, the requirements get "propagated" to us, and so
2490 // we have to solve them here where we instantiate the
2493 // Despite the opacity of the previous paragraph, this is
2494 // actually relatively easy to understand in terms of the
2495 // desugaring. A closure gets desugared to a struct, and
2496 // these extra requirements are basically like where
2497 // clauses on the struct.
2498 AggregateKind::Closure(def_id, substs)
2499 | AggregateKind::Generator(def_id, substs, _) => {
2500 (*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location))
2503 AggregateKind::Array(_) | AggregateKind::Tuple => {
2504 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2508 self.normalize_and_prove_instantiated_predicates(
2510 instantiated_predicates,
2511 location.to_locations(),
2515 fn prove_closure_bounds(
2519 substs: SubstsRef<'tcx>,
2521 ) -> ty::InstantiatedPredicates<'tcx> {
2522 if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2524 let closure_constraints = QueryRegionConstraints {
2525 outlives: closure_region_requirements.apply_requirements(
2531 // Presently, closures never propagate member
2532 // constraints to their parents -- they are enforced
2533 // locally. This is largely a non-issue as member
2534 // constraints only come from `-> impl Trait` and
2535 // friends which don't appear (thus far...) in
2537 member_constraints: vec![],
2540 let bounds_mapping = closure_constraints
2544 .filter_map(|(idx, constraint)| {
2545 let ty::OutlivesPredicate(k1, r2) =
2546 constraint.no_bound_vars().unwrap_or_else(|| {
2547 bug!("query_constraint {:?} contained bound vars", constraint,);
2551 GenericArgKind::Lifetime(r1) => {
2552 // constraint is r1: r2
2553 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2554 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2555 let outlives_requirements =
2556 &closure_region_requirements.outlives_requirements[idx];
2559 (outlives_requirements.category, outlives_requirements.blame_span),
2562 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2570 .closure_bounds_mapping
2571 .insert(location, bounds_mapping);
2572 assert!(existing.is_none(), "Multiple closures at the same location.");
2574 self.push_region_constraints(
2575 location.to_locations(),
2576 ConstraintCategory::ClosureBounds,
2577 &closure_constraints,
2581 tcx.predicates_of(def_id).instantiate(tcx, substs)
2584 #[instrument(skip(self, body), level = "debug")]
2585 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2586 self.last_span = body.span;
2589 for (local, local_decl) in body.local_decls.iter_enumerated() {
2590 self.check_local(&body, local, local_decl);
2593 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2594 let mut location = Location { block, statement_index: 0 };
2595 for stmt in &block_data.statements {
2596 if !stmt.source_info.span.is_dummy() {
2597 self.last_span = stmt.source_info.span;
2599 self.check_stmt(body, stmt, location);
2600 location.statement_index += 1;
2603 self.check_terminator(&body, block_data.terminator(), location);
2604 self.check_iscleanup(&body, block_data);
2609 trait NormalizeLocation: fmt::Debug + Copy {
2610 fn to_locations(self) -> Locations;
2613 impl NormalizeLocation for Locations {
2614 fn to_locations(self) -> Locations {
2619 impl NormalizeLocation for Location {
2620 fn to_locations(self) -> Locations {
2621 Locations::Single(self)
2625 /// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2626 /// this is not canonicalized - it directly affects the main `InferCtxt`
2627 /// that we use during MIR borrowchecking.
2629 pub(super) struct InstantiateOpaqueType<'tcx> {
2630 pub base_universe: Option<ty::UniverseIndex>,
2631 pub region_constraints: Option<RegionConstraintData<'tcx>>,
2632 pub obligations: Vec<PredicateObligation<'tcx>>,
2635 impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2637 /// We use this type itself to store the information used
2638 /// when reporting errors. Since this is not a query, we don't
2639 /// re-run anything during error reporting - we just use the information
2640 /// we saved to help extract an error from the already-existing region
2641 /// constraints in our `InferCtxt`
2642 type ErrorInfo = InstantiateOpaqueType<'tcx>;
2644 fn fully_perform(mut self, infcx: &InferCtxt<'_, 'tcx>) -> Fallible<TypeOpOutput<'tcx, Self>> {
2645 let (mut output, region_constraints) = scrape_region_constraints(infcx, || {
2646 Ok(InferOk { value: (), obligations: self.obligations.clone() })
2648 self.region_constraints = Some(region_constraints);
2649 output.error_info = Some(self);