1 #![deny(rustc::untranslatable_diagnostic)]
2 #![deny(rustc::diagnostic_outside_of_impl)]
3 //! This pass type-checks the MIR to ensure it is not broken.
6 use std::{fmt, iter, mem};
10 use hir::OpaqueTyOrigin;
11 use rustc_data_structures::frozen::Frozen;
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_data_structures::vec_map::VecMap;
15 use rustc_hir::def::DefKind;
16 use rustc_hir::def_id::LocalDefId;
17 use rustc_hir::lang_items::LangItem;
18 use rustc_index::vec::{Idx, IndexVec};
19 use rustc_infer::infer::canonical::QueryRegionConstraints;
20 use rustc_infer::infer::outlives::env::RegionBoundPairs;
21 use rustc_infer::infer::region_constraints::RegionConstraintData;
22 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
23 use rustc_infer::infer::{
24 InferCtxt, InferOk, LateBoundRegion, LateBoundRegionConversionTime, NllRegionVariableOrigin,
26 use rustc_middle::mir::tcx::PlaceTy;
27 use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
28 use rustc_middle::mir::AssertKind;
29 use rustc_middle::mir::*;
30 use rustc_middle::ty::adjustment::PointerCast;
31 use rustc_middle::ty::cast::CastTy;
32 use rustc_middle::ty::subst::{SubstsRef, UserSubsts};
33 use rustc_middle::ty::visit::TypeVisitable;
34 use rustc_middle::ty::{
35 self, Binder, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, Dynamic,
36 OpaqueHiddenType, OpaqueTypeKey, RegionVid, Ty, TyCtxt, UserType, UserTypeAnnotationIndex,
38 use rustc_span::def_id::CRATE_DEF_ID;
39 use rustc_span::{Span, DUMMY_SP};
40 use rustc_target::abi::VariantIdx;
41 use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
42 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
43 use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
44 use rustc_trait_selection::traits::query::Fallible;
45 use rustc_trait_selection::traits::PredicateObligation;
47 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
48 use rustc_mir_dataflow::move_paths::MoveData;
49 use rustc_mir_dataflow::ResultsCursor;
51 use crate::session_diagnostics::MoveUnsized;
53 borrow_set::BorrowSet,
54 constraints::{OutlivesConstraint, OutlivesConstraintSet},
55 diagnostics::UniverseInfo,
57 location::LocationTable,
58 member_constraints::MemberConstraintSet,
61 region_infer::values::{
62 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
64 region_infer::TypeTest,
65 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
66 universal_regions::{DefiningTy, UniversalRegions},
70 macro_rules! span_mirbug {
71 ($context:expr, $elem:expr, $($message:tt)*) => ({
72 $crate::type_check::mirbug(
76 "broken MIR in {:?} ({:?}): {}",
77 $context.body().source.def_id(),
79 format_args!($($message)*),
85 macro_rules! span_mirbug_and_err {
86 ($context:expr, $elem:expr, $($message:tt)*) => ({
88 span_mirbug!($context, $elem, $($message)*);
95 mod constraint_conversion;
96 pub mod free_region_relations;
98 pub(crate) mod liveness;
101 /// Type checks the given `mir` in the context of the inference
102 /// context `infcx`. Returns any region constraints that have yet to
103 /// be proven. This result includes liveness constraints that
104 /// ensure that regions appearing in the types of all local variables
105 /// are live at all points where that local variable may later be
108 /// This phase of type-check ought to be infallible -- this is because
109 /// the original, HIR-based type-check succeeded. So if any errors
110 /// occur here, we will get a `bug!` reported.
114 /// - `infcx` -- inference context to use
115 /// - `param_env` -- parameter environment to use for trait solving
116 /// - `body` -- MIR body to type-check
117 /// - `promoted` -- map of promoted constants within `body`
118 /// - `universal_regions` -- the universal regions from `body`s function signature
119 /// - `location_table` -- MIR location map of `body`
120 /// - `borrow_set` -- information about borrows occurring in `body`
121 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
122 /// - `flow_inits` -- results of a maybe-init dataflow analysis
123 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
124 /// - `elements` -- MIR region map
125 pub(crate) fn type_check<'mir, 'tcx>(
126 infcx: &InferCtxt<'tcx>,
127 param_env: ty::ParamEnv<'tcx>,
129 promoted: &IndexVec<Promoted, Body<'tcx>>,
130 universal_regions: &Rc<UniversalRegions<'tcx>>,
131 location_table: &LocationTable,
132 borrow_set: &BorrowSet<'tcx>,
133 all_facts: &mut Option<AllFacts>,
134 flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
135 move_data: &MoveData<'tcx>,
136 elements: &Rc<RegionValueElements>,
137 upvars: &[Upvar<'tcx>],
139 ) -> MirTypeckResults<'tcx> {
140 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
141 let mut constraints = MirTypeckRegionConstraints {
142 placeholder_indices: PlaceholderIndices::default(),
143 placeholder_index_to_region: IndexVec::default(),
144 liveness_constraints: LivenessValues::new(elements.clone()),
145 outlives_constraints: OutlivesConstraintSet::default(),
146 member_constraints: MemberConstraintSet::default(),
147 type_tests: Vec::default(),
148 universe_causes: FxHashMap::default(),
152 universal_region_relations,
154 normalized_inputs_and_output,
155 } = free_region_relations::create(
158 implicit_region_bound,
163 debug!(?normalized_inputs_and_output);
165 for u in ty::UniverseIndex::ROOT..=infcx.universe() {
166 constraints.universe_causes.insert(u, UniverseInfo::other());
169 let mut borrowck_context = BorrowCheckContext {
174 constraints: &mut constraints,
178 let mut checker = TypeChecker::new(
183 implicit_region_bound,
184 &mut borrowck_context,
187 let errors_reported = {
188 let mut verifier = TypeVerifier::new(&mut checker, promoted);
189 verifier.visit_body(&body);
190 verifier.errors_reported
193 if !errors_reported {
194 // if verifier failed, don't do further checks to avoid ICEs
195 checker.typeck_mir(body);
198 checker.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
199 checker.check_signature_annotation(&body);
211 translate_outlives_facts(&mut checker);
212 let opaque_type_values = infcx.take_opaque_types();
214 let opaque_type_values = opaque_type_values
216 .map(|(opaque_type_key, decl)| {
219 Locations::All(body.span),
220 ConstraintCategory::OpaqueType,
223 infcx.register_member_constraints(
227 decl.hidden_type.span,
229 Ok(InferOk { value: (), obligations: vec![] })
231 || "opaque_type_map".to_string(),
235 let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
236 trace!("finalized opaque type {:?} to {:#?}", opaque_type_key, hidden_type.ty.kind());
237 if hidden_type.has_non_region_infer() {
238 let reported = infcx.tcx.sess.delay_span_bug(
239 decl.hidden_type.span,
240 &format!("could not resolve {:#?}", hidden_type.ty.kind()),
242 hidden_type.ty = infcx.tcx.ty_error_with_guaranteed(reported);
245 (opaque_type_key, (hidden_type, decl.origin))
249 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
252 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
253 let cx = &mut typeck.borrowck_context;
254 if let Some(facts) = cx.all_facts {
255 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
256 let location_table = cx.location_table;
257 facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
258 |constraint: &OutlivesConstraint<'_>| {
259 if let Some(from_location) = constraint.locations.from_location() {
260 Either::Left(iter::once((
263 location_table.mid_index(from_location),
269 .map(move |location| (constraint.sup, constraint.sub, location)),
278 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
279 // We sometimes see MIR failures (notably predicate failures) due to
280 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
281 // to avoid reporting bugs in those cases.
282 tcx.sess.diagnostic().delay_span_bug(span, msg);
285 enum FieldAccessError {
286 OutOfRange { field_count: usize },
289 /// Verifies that MIR types are sane to not crash further checks.
291 /// The sanitize_XYZ methods here take an MIR object and compute its
292 /// type, calling `span_mirbug` and returning an error type if there
294 struct TypeVerifier<'a, 'b, 'tcx> {
295 cx: &'a mut TypeChecker<'b, 'tcx>,
296 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
298 errors_reported: bool,
301 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
302 fn visit_span(&mut self, span: Span) {
303 if !span.is_dummy() {
304 self.last_span = span;
308 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
309 self.sanitize_place(place, location, context);
312 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
313 debug!(?constant, ?location, "visit_constant");
315 self.super_constant(constant, location);
316 let ty = self.sanitize_type(constant, constant.literal.ty());
318 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
319 let live_region_vid =
320 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
324 .liveness_constraints
325 .add_element(live_region_vid, location);
328 // HACK(compiler-errors): Constants that are gathered into Body.required_consts
329 // have their locations erased...
330 let locations = if location != Location::START {
331 location.to_locations()
333 Locations::All(constant.span)
336 if let Some(annotation_index) = constant.user_ty {
337 if let Err(terr) = self.cx.relate_type_and_user_type(
338 constant.literal.ty(),
339 ty::Variance::Invariant,
340 &UserTypeProjection { base: annotation_index, projs: vec![] },
342 ConstraintCategory::Boring,
344 let annotation = &self.cx.user_type_annotations[annotation_index];
348 "bad constant user type {:?} vs {:?}: {:?}",
350 constant.literal.ty(),
355 let tcx = self.tcx();
356 let maybe_uneval = match constant.literal {
357 ConstantKind::Ty(ct) => match ct.kind() {
358 ty::ConstKind::Unevaluated(_) => {
359 bug!("should not encounter unevaluated ConstantKind::Ty here, got {:?}", ct)
363 ConstantKind::Unevaluated(uv, _) => Some(uv),
367 if let Some(uv) = maybe_uneval {
368 if let Some(promoted) = uv.promoted {
369 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
370 promoted: &Body<'tcx>,
374 verifier.cx.eq_types(ty, san_ty, locations, ConstraintCategory::Boring)
379 "bad promoted type ({:?}: {:?}): {:?}",
387 if !self.errors_reported {
388 let promoted_body = &self.promoted[promoted];
389 self.sanitize_promoted(promoted_body, location);
391 let promoted_ty = promoted_body.return_ty();
392 check_err(self, promoted_body, ty, promoted_ty);
395 self.cx.ascribe_user_type(
396 constant.literal.ty(),
399 UserSubsts { substs: uv.substs, user_self_ty: None },
401 locations.span(&self.cx.body),
404 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
405 let unnormalized_ty = tcx.type_of(static_def_id);
406 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
407 let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty;
409 if let Err(terr) = self.cx.eq_types(
413 ConstraintCategory::Boring,
415 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
419 if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() {
420 // const_trait_impl: use a non-const param env when checking that a FnDef type is well formed.
421 // this is because the well-formedness of the function does not need to be proved to have `const`
422 // impls for trait bounds.
423 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
424 let prev = self.cx.param_env;
425 self.cx.param_env = prev.without_const();
426 self.cx.normalize_and_prove_instantiated_predicates(
428 instantiated_predicates,
431 self.cx.param_env = prev;
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 = tcx.at(self.last_span).mk_trait_ref(LangItem::Copy, [place_ty.ty]);
544 // To have a `Copy` operand, the type `T` of the
545 // value must be `Copy`. Note that we prove that `T: Copy`,
546 // rather than using the `is_copy_modulo_regions`
547 // test. This is important because
548 // `is_copy_modulo_regions` ignores the resulting region
549 // obligations and assumes they pass. This can result in
550 // bounds from `Copy` impls being unsoundly ignored (e.g.,
551 // #29149). Note that we decide to use `Copy` before knowing
552 // whether the bounds fully apply: in effect, the rule is
553 // that if a value of some type could implement `Copy`, then
555 self.cx.prove_trait_ref(
557 location.to_locations(),
558 ConstraintCategory::CopyBound,
565 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
566 // Determine the constraints from the promoted MIR by running the type
567 // checker on the promoted MIR, then transfer the constraints back to
568 // the main MIR, changing the locations to the provided location.
570 let parent_body = mem::replace(&mut self.cx.body, promoted_body);
572 // Use new sets of constraints and closure bounds so that we can
573 // modify their locations.
574 let all_facts = &mut None;
575 let mut constraints = Default::default();
576 let mut liveness_constraints =
577 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
578 // Don't try to add borrow_region facts for the promoted MIR
580 let mut swap_constraints = |this: &mut Self| {
581 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
583 &mut this.cx.borrowck_context.constraints.outlives_constraints,
587 &mut this.cx.borrowck_context.constraints.liveness_constraints,
588 &mut liveness_constraints,
592 swap_constraints(self);
594 self.visit_body(&promoted_body);
596 if !self.errors_reported {
597 // if verifier failed, don't do further checks to avoid ICEs
598 self.cx.typeck_mir(promoted_body);
601 self.cx.body = parent_body;
602 // Merge the outlives constraints back in, at the given location.
603 swap_constraints(self);
605 let locations = location.to_locations();
606 for constraint in constraints.outlives().iter() {
607 let mut constraint = *constraint;
608 constraint.locations = locations;
609 if let ConstraintCategory::Return(_)
610 | ConstraintCategory::UseAsConst
611 | ConstraintCategory::UseAsStatic = constraint.category
613 // "Returning" from a promoted is an assignment to a
614 // temporary from the user's point of view.
615 constraint.category = ConstraintCategory::Boring;
617 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
619 for region in liveness_constraints.rows() {
620 // If the region is live at at least one location in the promoted MIR,
621 // then add a liveness constraint to the main MIR for this region
622 // at the location provided as an argument to this method
623 if liveness_constraints.get_elements(region).next().is_some() {
627 .liveness_constraints
628 .add_element(region, location);
633 fn sanitize_projection(
640 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
641 let tcx = self.tcx();
642 let base_ty = base.ty;
644 ProjectionElem::Deref => {
645 let deref_ty = base_ty.builtin_deref(true);
646 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
647 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
650 ProjectionElem::Index(i) => {
651 let index_ty = Place::from(i).ty(self.body(), tcx).ty;
652 if index_ty != tcx.types.usize {
653 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
655 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
656 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
660 ProjectionElem::ConstantIndex { .. } => {
661 // consider verifying in-bounds
662 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
663 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
666 ProjectionElem::Subslice { from, to, from_end } => {
667 PlaceTy::from_ty(match base_ty.kind() {
668 ty::Array(inner, _) => {
669 assert!(!from_end, "array subslices should not use from_end");
670 tcx.mk_array(*inner, to - from)
673 assert!(from_end, "slice subslices should use from_end");
676 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
679 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
680 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
681 if index.as_usize() >= adt_def.variants().len() {
682 PlaceTy::from_ty(span_mirbug_and_err!(
685 "cast to variant #{:?} but enum only has {:?}",
687 adt_def.variants().len()
690 PlaceTy { ty: base_ty, variant_index: Some(index) }
693 // We do not need to handle generators here, because this runs
694 // before the generator transform stage.
696 let ty = if let Some(name) = maybe_name {
697 span_mirbug_and_err!(
700 "can't downcast {:?} as {:?}",
705 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
710 ProjectionElem::Field(field, fty) => {
711 let fty = self.sanitize_type(place, fty);
712 let fty = self.cx.normalize(fty, location);
713 match self.field_ty(place, base, field, location) {
715 let ty = self.cx.normalize(ty, location);
716 if let Err(terr) = self.cx.eq_types(
719 location.to_locations(),
720 ConstraintCategory::Boring,
725 "bad field access ({:?}: {:?}): {:?}",
732 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
735 "accessed field #{} but variant only has {}",
740 PlaceTy::from_ty(fty)
742 ProjectionElem::OpaqueCast(ty) => {
743 let ty = self.sanitize_type(place, ty);
744 let ty = self.cx.normalize(ty, location);
749 location.to_locations(),
750 ConstraintCategory::TypeAnnotation,
758 fn error(&mut self) -> Ty<'tcx> {
759 self.errors_reported = true;
760 self.tcx().ty_error()
765 parent: &dyn fmt::Debug,
766 base_ty: PlaceTy<'tcx>,
769 ) -> Result<Ty<'tcx>, FieldAccessError> {
770 let tcx = self.tcx();
772 let (variant, substs) = match base_ty {
773 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
774 ty::Adt(adt_def, substs) => (adt_def.variant(variant_index), substs),
775 ty::Generator(def_id, substs, _) => {
776 let mut variants = substs.as_generator().state_tys(def_id, tcx);
777 let Some(mut variant) = variants.nth(variant_index.into()) else {
779 "variant_index of generator out of range: {:?}/{:?}",
781 substs.as_generator().state_tys(def_id, tcx).count()
784 return match variant.nth(field.index()) {
786 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
789 _ => bug!("can't have downcast of non-adt non-generator type"),
791 PlaceTy { ty, variant_index: None } => match *ty.kind() {
792 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
793 (adt_def.variant(VariantIdx::new(0)), substs)
795 ty::Closure(_, substs) => {
803 None => Err(FieldAccessError::OutOfRange {
804 field_count: substs.as_closure().upvar_tys().count(),
808 ty::Generator(_, substs, _) => {
809 // Only prefix fields (upvars and current state) are
810 // accessible without a variant index.
811 return match substs.as_generator().prefix_tys().nth(field.index()) {
813 None => Err(FieldAccessError::OutOfRange {
814 field_count: substs.as_generator().prefix_tys().count(),
819 return match tys.get(field.index()) {
821 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
825 return Ok(span_mirbug_and_err!(
828 "can't project out of {:?}",
835 if let Some(field) = variant.fields.get(field.index()) {
836 Ok(self.cx.normalize(field.ty(tcx, substs), location))
838 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
843 /// The MIR type checker. Visits the MIR and enforces all the
844 /// constraints needed for it to be valid and well-typed. Along the
845 /// way, it accrues region constraints -- these can later be used by
846 /// NLL region checking.
847 struct TypeChecker<'a, 'tcx> {
848 infcx: &'a InferCtxt<'tcx>,
849 param_env: ty::ParamEnv<'tcx>,
851 body: &'a Body<'tcx>,
852 /// User type annotations are shared between the main MIR and the MIR of
853 /// all of the promoted items.
854 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
855 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
856 implicit_region_bound: ty::Region<'tcx>,
857 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
858 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
861 struct BorrowCheckContext<'a, 'tcx> {
862 pub(crate) universal_regions: &'a UniversalRegions<'tcx>,
863 location_table: &'a LocationTable,
864 all_facts: &'a mut Option<AllFacts>,
865 borrow_set: &'a BorrowSet<'tcx>,
866 pub(crate) constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
867 upvars: &'a [Upvar<'tcx>],
870 pub(crate) struct MirTypeckResults<'tcx> {
871 pub(crate) constraints: MirTypeckRegionConstraints<'tcx>,
872 pub(crate) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
873 pub(crate) opaque_type_values:
874 VecMap<OpaqueTypeKey<'tcx>, (OpaqueHiddenType<'tcx>, OpaqueTyOrigin)>,
877 /// A collection of region constraints that must be satisfied for the
878 /// program to be considered well-typed.
879 pub(crate) struct MirTypeckRegionConstraints<'tcx> {
880 /// Maps from a `ty::Placeholder` to the corresponding
881 /// `PlaceholderIndex` bit that we will use for it.
883 /// To keep everything in sync, do not insert this set
884 /// directly. Instead, use the `placeholder_region` helper.
885 pub(crate) placeholder_indices: PlaceholderIndices,
887 /// Each time we add a placeholder to `placeholder_indices`, we
888 /// also create a corresponding "representative" region vid for
889 /// that wraps it. This vector tracks those. This way, when we
890 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
891 /// the same underlying `RegionVid`.
892 pub(crate) placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
894 /// In general, the type-checker is not responsible for enforcing
895 /// liveness constraints; this job falls to the region inferencer,
896 /// which performs a liveness analysis. However, in some limited
897 /// cases, the MIR type-checker creates temporary regions that do
898 /// not otherwise appear in the MIR -- in particular, the
899 /// late-bound regions that it instantiates at call-sites -- and
900 /// hence it must report on their liveness constraints.
901 pub(crate) liveness_constraints: LivenessValues<RegionVid>,
903 pub(crate) outlives_constraints: OutlivesConstraintSet<'tcx>,
905 pub(crate) member_constraints: MemberConstraintSet<'tcx, RegionVid>,
907 pub(crate) universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
909 pub(crate) type_tests: Vec<TypeTest<'tcx>>,
912 impl<'tcx> MirTypeckRegionConstraints<'tcx> {
913 fn placeholder_region(
915 infcx: &InferCtxt<'tcx>,
916 placeholder: ty::PlaceholderRegion,
917 ) -> ty::Region<'tcx> {
918 let placeholder_index = self.placeholder_indices.insert(placeholder);
919 match self.placeholder_index_to_region.get(placeholder_index) {
922 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
923 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
924 self.placeholder_index_to_region.push(region);
931 /// The `Locations` type summarizes *where* region constraints are
932 /// required to hold. Normally, this is at a particular point which
933 /// created the obligation, but for constraints that the user gave, we
934 /// want the constraint to hold at all points.
935 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
937 /// Indicates that a type constraint should always be true. This
938 /// is particularly important in the new borrowck analysis for
939 /// things like the type of the return slot. Consider this
942 /// ```compile_fail,E0515
943 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
945 /// return &y; // error
949 /// Here, we wind up with the signature from the return type being
950 /// something like `&'1 u32` where `'1` is a universal region. But
951 /// the type of the return slot `_0` is something like `&'2 u32`
952 /// where `'2` is an existential region variable. The type checker
953 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
954 /// older NLL analysis, we required this only at the entry point
955 /// to the function. By the nature of the constraints, this wound
956 /// up propagating to all points reachable from start (because
957 /// `'1` -- as a universal region -- is live everywhere). In the
958 /// newer analysis, though, this doesn't work: `_0` is considered
959 /// dead at the start (it has no usable value) and hence this type
960 /// equality is basically a no-op. Then, later on, when we do `_0
961 /// = &'3 y`, that region `'3` never winds up related to the
962 /// universal region `'1` and hence no error occurs. Therefore, we
963 /// use Locations::All instead, which ensures that the `'1` and
964 /// `'2` are equal everything. We also use this for other
965 /// user-given type annotations; e.g., if the user wrote `let mut
966 /// x: &'static u32 = ...`, we would ensure that all values
967 /// assigned to `x` are of `'static` lifetime.
969 /// The span points to the place the constraint arose. For example,
970 /// it points to the type in a user-given type annotation. If
971 /// there's no sensible span then it's DUMMY_SP.
974 /// An outlives constraint that only has to hold at a single location,
975 /// usually it represents a point where references flow from one spot to
976 /// another (e.g., `x = y`)
981 pub fn from_location(&self) -> Option<Location> {
983 Locations::All(_) => None,
984 Locations::Single(from_location) => Some(*from_location),
988 /// Gets a span representing the location.
989 pub fn span(&self, body: &Body<'_>) -> Span {
991 Locations::All(span) => *span,
992 Locations::Single(l) => body.source_info(*l).span,
997 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
999 infcx: &'a InferCtxt<'tcx>,
1000 body: &'a Body<'tcx>,
1001 param_env: ty::ParamEnv<'tcx>,
1002 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1003 implicit_region_bound: ty::Region<'tcx>,
1004 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1006 let mut checker = Self {
1008 last_span: DUMMY_SP,
1010 user_type_annotations: &body.user_type_annotations,
1013 implicit_region_bound,
1015 reported_errors: Default::default(),
1017 checker.check_user_type_annotations();
1021 fn body(&self) -> &Body<'tcx> {
1025 fn unsized_feature_enabled(&self) -> bool {
1026 let features = self.tcx().features();
1027 features.unsized_locals || features.unsized_fn_params
1030 /// Equate the inferred type and the annotated type for user type annotations
1031 #[instrument(skip(self), level = "debug")]
1032 fn check_user_type_annotations(&mut self) {
1033 debug!(?self.user_type_annotations);
1034 for user_annotation in self.user_type_annotations {
1035 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1036 let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1037 self.ascribe_user_type(inferred_ty, annotation, span);
1041 #[instrument(skip(self, data), level = "debug")]
1042 fn push_region_constraints(
1044 locations: Locations,
1045 category: ConstraintCategory<'tcx>,
1046 data: &QueryRegionConstraints<'tcx>,
1048 debug!("constraints generated: {:#?}", data);
1050 constraint_conversion::ConstraintConversion::new(
1052 self.borrowck_context.universal_regions,
1053 self.region_bound_pairs,
1054 self.implicit_region_bound,
1057 locations.span(self.body),
1059 &mut self.borrowck_context.constraints,
1064 /// Try to relate `sub <: sup`
1069 locations: Locations,
1070 category: ConstraintCategory<'tcx>,
1072 // Use this order of parameters because the sup type is usually the
1073 // "expected" type in diagnostics.
1074 self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
1077 #[instrument(skip(self, category), level = "debug")]
1082 locations: Locations,
1083 category: ConstraintCategory<'tcx>,
1085 self.relate_types(expected, ty::Variance::Invariant, found, locations, category)
1088 #[instrument(skip(self), level = "debug")]
1089 fn relate_type_and_user_type(
1093 user_ty: &UserTypeProjection,
1094 locations: Locations,
1095 category: ConstraintCategory<'tcx>,
1097 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1098 trace!(?annotated_type);
1099 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1101 let tcx = self.infcx.tcx;
1103 for proj in &user_ty.projs {
1104 if let ty::Alias(ty::Opaque, ..) = curr_projected_ty.ty.kind() {
1105 // There is nothing that we can compare here if we go through an opaque type.
1106 // We're always in its defining scope as we can otherwise not project through
1107 // it, so we're constraining it anyways.
1110 let projected_ty = curr_projected_ty.projection_ty_core(
1115 let ty = this.field_ty(tcx, field);
1116 self.normalize(ty, locations)
1118 |_, _| unreachable!(),
1120 curr_projected_ty = projected_ty;
1122 trace!(?curr_projected_ty);
1124 let ty = curr_projected_ty.ty;
1125 self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1130 fn tcx(&self) -> TyCtxt<'tcx> {
1134 #[instrument(skip(self, body, location), level = "debug")]
1135 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1136 let tcx = self.tcx();
1137 debug!("stmt kind: {:?}", stmt.kind);
1139 StatementKind::Assign(box (place, rv)) => {
1140 // Assignments to temporaries are not "interesting";
1141 // they are not caused by the user, but rather artifacts
1142 // of lowering. Assignments to other sorts of places *are* interesting
1144 let category = match place.as_local() {
1145 Some(RETURN_PLACE) => {
1146 let defining_ty = &self.borrowck_context.universal_regions.defining_ty;
1147 if defining_ty.is_const() {
1148 if tcx.is_static(defining_ty.def_id()) {
1149 ConstraintCategory::UseAsStatic
1151 ConstraintCategory::UseAsConst
1154 ConstraintCategory::Return(ReturnConstraint::Normal)
1159 body.local_decls[l].local_info,
1160 Some(box LocalInfo::AggregateTemp)
1163 ConstraintCategory::Usage
1165 Some(l) if !body.local_decls[l].is_user_variable() => {
1166 ConstraintCategory::Boring
1168 _ => ConstraintCategory::Assignment,
1171 "assignment category: {:?} {:?}",
1173 place.as_local().map(|l| &body.local_decls[l])
1176 let place_ty = place.ty(body, tcx).ty;
1178 let place_ty = self.normalize(place_ty, location);
1179 debug!("place_ty normalized: {:?}", place_ty);
1180 let rv_ty = rv.ty(body, tcx);
1182 let rv_ty = self.normalize(rv_ty, location);
1183 debug!("normalized rv_ty: {:?}", rv_ty);
1185 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1190 "bad assignment ({:?} = {:?}): {:?}",
1197 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1198 if let Err(terr) = self.relate_type_and_user_type(
1200 ty::Variance::Invariant,
1201 &UserTypeProjection { base: annotation_index, projs: vec![] },
1202 location.to_locations(),
1203 ConstraintCategory::Boring,
1205 let annotation = &self.user_type_annotations[annotation_index];
1209 "bad user type on rvalue ({:?} = {:?}): {:?}",
1217 self.check_rvalue(body, rv, location);
1218 if !self.unsized_feature_enabled() {
1220 tcx.at(self.last_span).mk_trait_ref(LangItem::Sized, [place_ty]);
1221 self.prove_trait_ref(
1223 location.to_locations(),
1224 ConstraintCategory::SizedBound,
1228 StatementKind::AscribeUserType(box (place, projection), variance) => {
1229 let place_ty = place.ty(body, tcx).ty;
1230 if let Err(terr) = self.relate_type_and_user_type(
1234 Locations::All(stmt.source_info.span),
1235 ConstraintCategory::TypeAnnotation,
1237 let annotation = &self.user_type_annotations[projection.base];
1241 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1249 StatementKind::Intrinsic(box kind) => match kind {
1250 NonDivergingIntrinsic::Assume(op) => self.check_operand(op, location),
1251 NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
1252 stmt.source_info.span,
1253 "Unexpected NonDivergingIntrinsic::CopyNonOverlapping, should only appear after lowering_intrinsics",
1256 StatementKind::FakeRead(..)
1257 | StatementKind::StorageLive(..)
1258 | StatementKind::StorageDead(..)
1259 | StatementKind::Retag { .. }
1260 | StatementKind::Coverage(..)
1261 | StatementKind::Nop => {}
1262 StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
1263 bug!("Statement not allowed in this MIR phase")
1268 #[instrument(skip(self, body, term_location), level = "debug")]
1269 fn check_terminator(
1272 term: &Terminator<'tcx>,
1273 term_location: Location,
1275 let tcx = self.tcx();
1276 debug!("terminator kind: {:?}", term.kind);
1278 TerminatorKind::Goto { .. }
1279 | TerminatorKind::Resume
1280 | TerminatorKind::Abort
1281 | TerminatorKind::Return
1282 | TerminatorKind::GeneratorDrop
1283 | TerminatorKind::Unreachable
1284 | TerminatorKind::Drop { .. }
1285 | TerminatorKind::FalseEdge { .. }
1286 | TerminatorKind::FalseUnwind { .. }
1287 | TerminatorKind::InlineAsm { .. } => {
1288 // no checks needed for these
1291 TerminatorKind::DropAndReplace { place, value, target: _, unwind: _ } => {
1292 let place_ty = place.ty(body, tcx).ty;
1293 let rv_ty = value.ty(body, tcx);
1295 let locations = term_location.to_locations();
1297 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1302 "bad DropAndReplace ({:?} = {:?}): {:?}",
1309 TerminatorKind::SwitchInt { discr, .. } => {
1310 self.check_operand(discr, term_location);
1312 let switch_ty = discr.ty(body, tcx);
1313 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1314 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1316 // FIXME: check the values
1318 TerminatorKind::Call { func, args, destination, from_hir_call, target, .. } => {
1319 self.check_operand(func, term_location);
1321 self.check_operand(arg, term_location);
1324 let func_ty = func.ty(body, tcx);
1325 debug!("func_ty.kind: {:?}", func_ty.kind());
1327 let sig = match func_ty.kind() {
1328 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1330 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1334 let (sig, map) = tcx.replace_late_bound_regions(sig, |br| {
1335 self.infcx.next_region_var(LateBoundRegion(
1336 term.source_info.span,
1338 LateBoundRegionConversionTime::FnCall,
1342 // IMPORTANT: We have to prove well formed for the function signature before
1343 // we normalize it, as otherwise types like `<&'a &'b () as Trait>::Assoc`
1344 // get normalized away, causing us to ignore the `'b: 'a` bound used by the function.
1346 // Normalization results in a well formed type if the input is well formed, so we
1347 // don't have to check it twice.
1349 // See #91068 for an example.
1350 self.prove_predicates(
1351 sig.inputs_and_output
1353 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1354 term_location.to_locations(),
1355 ConstraintCategory::Boring,
1357 let sig = self.normalize(sig, term_location);
1358 self.check_call_dest(body, term, &sig, *destination, *target, term_location);
1360 // The ordinary liveness rules will ensure that all
1361 // regions in the type of the callee are live here. We
1362 // then further constrain the late-bound regions that
1363 // were instantiated at the call site to be live as
1364 // well. The resulting is that all the input (and
1365 // output) types in the signature must be live, since
1366 // all the inputs that fed into it were live.
1367 for &late_bound_region in map.values() {
1369 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1370 self.borrowck_context
1372 .liveness_constraints
1373 .add_element(region_vid, term_location);
1376 self.check_call_inputs(body, term, &sig, args, term_location, *from_hir_call);
1378 TerminatorKind::Assert { cond, msg, .. } => {
1379 self.check_operand(cond, term_location);
1381 let cond_ty = cond.ty(body, tcx);
1382 if cond_ty != tcx.types.bool {
1383 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1386 if let AssertKind::BoundsCheck { len, index } = msg {
1387 if len.ty(body, tcx) != tcx.types.usize {
1388 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1390 if index.ty(body, tcx) != tcx.types.usize {
1391 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1395 TerminatorKind::Yield { value, .. } => {
1396 self.check_operand(value, term_location);
1398 let value_ty = value.ty(body, tcx);
1399 match body.yield_ty() {
1400 None => span_mirbug!(self, term, "yield in non-generator"),
1402 if let Err(terr) = self.sub_types(
1405 term_location.to_locations(),
1406 ConstraintCategory::Yield,
1411 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1426 term: &Terminator<'tcx>,
1427 sig: &ty::FnSig<'tcx>,
1428 destination: Place<'tcx>,
1429 target: Option<BasicBlock>,
1430 term_location: Location,
1432 let tcx = self.tcx();
1435 let dest_ty = destination.ty(body, tcx).ty;
1436 let dest_ty = self.normalize(dest_ty, term_location);
1437 let category = match destination.as_local() {
1438 Some(RETURN_PLACE) => {
1439 if let BorrowCheckContext {
1443 DefiningTy::Const(def_id, _)
1444 | DefiningTy::InlineConst(def_id, _),
1448 } = self.borrowck_context
1450 if tcx.is_static(*def_id) {
1451 ConstraintCategory::UseAsStatic
1453 ConstraintCategory::UseAsConst
1456 ConstraintCategory::Return(ReturnConstraint::Normal)
1459 Some(l) if !body.local_decls[l].is_user_variable() => {
1460 ConstraintCategory::Boring
1462 _ => ConstraintCategory::Assignment,
1465 let locations = term_location.to_locations();
1467 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1471 "call dest mismatch ({:?} <- {:?}): {:?}",
1478 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1479 // this check is done at `check_local`.
1480 if self.unsized_feature_enabled() {
1481 let span = term.source_info.span;
1482 self.ensure_place_sized(dest_ty, span);
1486 if !sig.output().is_privately_uninhabited(self.tcx(), self.param_env) {
1487 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1493 fn check_call_inputs(
1496 term: &Terminator<'tcx>,
1497 sig: &ty::FnSig<'tcx>,
1498 args: &[Operand<'tcx>],
1499 term_location: Location,
1500 from_hir_call: bool,
1502 debug!("check_call_inputs({:?}, {:?})", sig, args);
1503 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1504 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1507 let func_ty = if let TerminatorKind::Call { func, .. } = &term.kind {
1508 Some(func.ty(body, self.infcx.tcx))
1514 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1515 let op_arg_ty = op_arg.ty(body, self.tcx());
1517 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1518 let category = if from_hir_call {
1519 ConstraintCategory::CallArgument(self.infcx.tcx.erase_regions(func_ty))
1521 ConstraintCategory::Boring
1524 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
1529 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1539 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1540 let is_cleanup = block_data.is_cleanup;
1541 self.last_span = block_data.terminator().source_info.span;
1542 match block_data.terminator().kind {
1543 TerminatorKind::Goto { target } => {
1544 self.assert_iscleanup(body, block_data, target, is_cleanup)
1546 TerminatorKind::SwitchInt { ref targets, .. } => {
1547 for target in targets.all_targets() {
1548 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1551 TerminatorKind::Resume => {
1553 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1556 TerminatorKind::Abort => {
1558 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1561 TerminatorKind::Return => {
1563 span_mirbug!(self, block_data, "return on cleanup block")
1566 TerminatorKind::GeneratorDrop { .. } => {
1568 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1571 TerminatorKind::Yield { resume, drop, .. } => {
1573 span_mirbug!(self, block_data, "yield in cleanup block")
1575 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1576 if let Some(drop) = drop {
1577 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1580 TerminatorKind::Unreachable => {}
1581 TerminatorKind::Drop { target, unwind, .. }
1582 | TerminatorKind::DropAndReplace { target, unwind, .. }
1583 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1584 self.assert_iscleanup(body, block_data, target, is_cleanup);
1585 if let Some(unwind) = unwind {
1587 span_mirbug!(self, block_data, "unwind on cleanup block")
1589 self.assert_iscleanup(body, block_data, unwind, true);
1592 TerminatorKind::Call { ref target, cleanup, .. } => {
1593 if let &Some(target) = target {
1594 self.assert_iscleanup(body, block_data, target, is_cleanup);
1596 if let Some(cleanup) = cleanup {
1598 span_mirbug!(self, block_data, "cleanup on cleanup block")
1600 self.assert_iscleanup(body, block_data, cleanup, true);
1603 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1604 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1605 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1607 TerminatorKind::FalseUnwind { real_target, unwind } => {
1608 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1609 if let Some(unwind) = unwind {
1611 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1613 self.assert_iscleanup(body, block_data, unwind, true);
1616 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
1617 if let Some(target) = destination {
1618 self.assert_iscleanup(body, block_data, target, is_cleanup);
1620 if let Some(cleanup) = cleanup {
1622 span_mirbug!(self, block_data, "cleanup on cleanup block")
1624 self.assert_iscleanup(body, block_data, cleanup, true);
1630 fn assert_iscleanup(
1633 ctxt: &dyn fmt::Debug,
1637 if body[bb].is_cleanup != iscleanuppad {
1638 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1642 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1643 match body.local_kind(local) {
1644 LocalKind::ReturnPointer | LocalKind::Arg => {
1645 // return values of normal functions are required to be
1646 // sized by typeck, but return values of ADT constructors are
1647 // not because we don't include a `Self: Sized` bounds on them.
1649 // Unbound parts of arguments were never required to be Sized
1650 // - maybe we should make that a warning.
1653 LocalKind::Var | LocalKind::Temp => {}
1656 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1657 // and nullary ops are checked in `check_call_dest`.
1658 if !self.unsized_feature_enabled() {
1659 let span = local_decl.source_info.span;
1660 let ty = local_decl.ty;
1661 self.ensure_place_sized(ty, span);
1665 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1666 let tcx = self.tcx();
1668 // Erase the regions from `ty` to get a global type. The
1669 // `Sized` bound in no way depends on precise regions, so this
1670 // shouldn't affect `is_sized`.
1671 let erased_ty = tcx.erase_regions(ty);
1672 if !erased_ty.is_sized(tcx, self.param_env) {
1673 // in current MIR construction, all non-control-flow rvalue
1674 // expressions evaluate through `as_temp` or `into` a return
1675 // slot or local, so to find all unsized rvalues it is enough
1676 // to check all temps, return slots and locals.
1677 if self.reported_errors.replace((ty, span)).is_none() {
1678 // While this is located in `nll::typeck` this error is not
1679 // an NLL error, it's a required check to prevent creation
1680 // of unsized rvalues in a call expression.
1681 self.tcx().sess.emit_err(MoveUnsized { ty, span });
1686 fn aggregate_field_ty(
1688 ak: &AggregateKind<'tcx>,
1691 ) -> Result<Ty<'tcx>, FieldAccessError> {
1692 let tcx = self.tcx();
1695 AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => {
1696 let def = tcx.adt_def(adt_did);
1697 let variant = &def.variant(variant_index);
1698 let adj_field_index = active_field_index.unwrap_or(field_index);
1699 if let Some(field) = variant.fields.get(adj_field_index) {
1700 Ok(self.normalize(field.ty(tcx, substs), location))
1702 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1705 AggregateKind::Closure(_, substs) => {
1706 match substs.as_closure().upvar_tys().nth(field_index) {
1708 None => Err(FieldAccessError::OutOfRange {
1709 field_count: substs.as_closure().upvar_tys().count(),
1713 AggregateKind::Generator(_, substs, _) => {
1714 // It doesn't make sense to look at a field beyond the prefix;
1715 // these require a variant index, and are not initialized in
1716 // aggregate rvalues.
1717 match substs.as_generator().prefix_tys().nth(field_index) {
1719 None => Err(FieldAccessError::OutOfRange {
1720 field_count: substs.as_generator().prefix_tys().count(),
1724 AggregateKind::Array(ty) => Ok(ty),
1725 AggregateKind::Tuple => {
1726 unreachable!("This should have been covered in check_rvalues");
1731 fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1732 debug!(?op, ?location, "check_operand");
1734 if let Operand::Constant(constant) = op {
1735 let maybe_uneval = match constant.literal {
1736 ConstantKind::Val(..) | ConstantKind::Ty(_) => None,
1737 ConstantKind::Unevaluated(uv, _) => Some(uv),
1740 if let Some(uv) = maybe_uneval {
1741 if uv.promoted.is_none() {
1742 let tcx = self.tcx();
1743 let def_id = uv.def.def_id_for_type_of();
1744 if tcx.def_kind(def_id) == DefKind::InlineConst {
1745 let def_id = def_id.expect_local();
1747 self.prove_closure_bounds(tcx, def_id, uv.substs, location);
1748 self.normalize_and_prove_instantiated_predicates(
1751 location.to_locations(),
1759 #[instrument(skip(self, body), level = "debug")]
1760 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1761 let tcx = self.tcx();
1762 let span = body.source_info(location).span;
1765 Rvalue::Aggregate(ak, ops) => {
1767 self.check_operand(op, location);
1769 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1772 Rvalue::Repeat(operand, len) => {
1773 self.check_operand(operand, location);
1775 // If the length cannot be evaluated we must assume that the length can be larger
1777 // If the length is larger than 1, the repeat expression will need to copy the
1778 // element, so we require the `Copy` trait.
1779 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1781 Operand::Copy(..) | Operand::Constant(..) => {
1782 // These are always okay: direct use of a const, or a value that can evidently be copied.
1784 Operand::Move(place) => {
1785 // Make sure that repeated elements implement `Copy`.
1786 let ty = place.ty(body, tcx).ty;
1787 let trait_ref = tcx.at(span).mk_trait_ref(LangItem::Copy, [ty]);
1789 self.prove_trait_ref(
1791 Locations::Single(location),
1792 ConstraintCategory::CopyBound,
1799 &Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, ty) => {
1800 let trait_ref = tcx.at(span).mk_trait_ref(LangItem::Sized, [ty]);
1802 self.prove_trait_ref(
1804 location.to_locations(),
1805 ConstraintCategory::SizedBound,
1809 Rvalue::ShallowInitBox(operand, ty) => {
1810 self.check_operand(operand, location);
1812 let trait_ref = tcx.at(span).mk_trait_ref(LangItem::Sized, [*ty]);
1814 self.prove_trait_ref(
1816 location.to_locations(),
1817 ConstraintCategory::SizedBound,
1821 Rvalue::Cast(cast_kind, op, ty) => {
1822 self.check_operand(op, location);
1825 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1826 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1828 // The type that we see in the fcx is like
1829 // `foo::<'a, 'b>`, where `foo` is the path to a
1830 // function definition. When we extract the
1831 // signature, it comes from the `fn_sig` query,
1832 // and hence may contain unnormalized results.
1833 let fn_sig = self.normalize(fn_sig, location);
1835 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1837 if let Err(terr) = self.eq_types(
1840 location.to_locations(),
1841 ConstraintCategory::Cast,
1846 "equating {:?} with {:?} yields {:?}",
1854 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
1855 let sig = match op.ty(body, tcx).kind() {
1856 ty::Closure(_, substs) => substs.as_closure().sig(),
1859 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
1861 if let Err(terr) = self.eq_types(
1864 location.to_locations(),
1865 ConstraintCategory::Cast,
1870 "equating {:?} with {:?} yields {:?}",
1878 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
1879 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1881 // The type that we see in the fcx is like
1882 // `foo::<'a, 'b>`, where `foo` is the path to a
1883 // function definition. When we extract the
1884 // signature, it comes from the `fn_sig` query,
1885 // and hence may contain unnormalized results.
1886 let fn_sig = self.normalize(fn_sig, location);
1888 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1890 if let Err(terr) = self.eq_types(
1893 location.to_locations(),
1894 ConstraintCategory::Cast,
1899 "equating {:?} with {:?} yields {:?}",
1907 CastKind::Pointer(PointerCast::Unsize) => {
1911 .mk_trait_ref(LangItem::CoerceUnsized, [op.ty(body, tcx), ty]);
1913 self.prove_trait_ref(
1915 location.to_locations(),
1916 ConstraintCategory::Cast,
1920 CastKind::DynStar => {
1921 // get the constraints from the target type (`dyn* Clone`)
1923 // apply them to prove that the source type `Foo` implements `Clone` etc
1924 let (existential_predicates, region) = match ty.kind() {
1925 Dynamic(predicates, region, ty::DynStar) => (predicates, region),
1926 _ => panic!("Invalid dyn* cast_ty"),
1929 let self_ty = op.ty(body, tcx);
1931 self.prove_predicates(
1932 existential_predicates
1934 .map(|predicate| predicate.with_self_ty(tcx, self_ty)),
1935 location.to_locations(),
1936 ConstraintCategory::Cast,
1939 let outlives_predicate =
1940 tcx.mk_predicate(Binder::dummy(ty::PredicateKind::Clause(
1941 ty::Clause::TypeOutlives(ty::OutlivesPredicate(self_ty, *region)),
1943 self.prove_predicate(
1945 location.to_locations(),
1946 ConstraintCategory::Cast,
1950 CastKind::Pointer(PointerCast::MutToConstPointer) => {
1951 let ty::RawPtr(ty::TypeAndMut {
1953 mutbl: hir::Mutability::Mut,
1954 }) = op.ty(body, tcx).kind() else {
1958 "unexpected base type for cast {:?}",
1963 let ty::RawPtr(ty::TypeAndMut {
1965 mutbl: hir::Mutability::Not,
1966 }) = ty.kind() else {
1970 "unexpected target type for cast {:?}",
1975 if let Err(terr) = self.sub_types(
1978 location.to_locations(),
1979 ConstraintCategory::Cast,
1984 "relating {:?} with {:?} yields {:?}",
1992 CastKind::Pointer(PointerCast::ArrayToPointer) => {
1993 let ty_from = op.ty(body, tcx);
1995 let opt_ty_elem_mut = match ty_from.kind() {
1996 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
1997 match array_ty.kind() {
1998 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2005 let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
2009 "ArrayToPointer cast from unexpected type {:?}",
2015 let (ty_to, ty_to_mut) = match ty.kind() {
2016 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2023 "ArrayToPointer cast to unexpected type {:?}",
2030 if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2034 "ArrayToPointer cast from const {:?} to mut {:?}",
2041 if let Err(terr) = self.sub_types(
2044 location.to_locations(),
2045 ConstraintCategory::Cast,
2050 "relating {:?} with {:?} yields {:?}",
2058 CastKind::PointerExposeAddress => {
2059 let ty_from = op.ty(body, tcx);
2060 let cast_ty_from = CastTy::from_ty(ty_from);
2061 let cast_ty_to = CastTy::from_ty(*ty);
2062 match (cast_ty_from, cast_ty_to) {
2063 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => (),
2068 "Invalid PointerExposeAddress cast {:?} -> {:?}",
2076 CastKind::PointerFromExposedAddress => {
2077 let ty_from = op.ty(body, tcx);
2078 let cast_ty_from = CastTy::from_ty(ty_from);
2079 let cast_ty_to = CastTy::from_ty(*ty);
2080 match (cast_ty_from, cast_ty_to) {
2081 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
2086 "Invalid PointerFromExposedAddress cast {:?} -> {:?}",
2093 CastKind::IntToInt => {
2094 let ty_from = op.ty(body, tcx);
2095 let cast_ty_from = CastTy::from_ty(ty_from);
2096 let cast_ty_to = CastTy::from_ty(*ty);
2097 match (cast_ty_from, cast_ty_to) {
2098 (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => (),
2103 "Invalid IntToInt cast {:?} -> {:?}",
2110 CastKind::IntToFloat => {
2111 let ty_from = op.ty(body, tcx);
2112 let cast_ty_from = CastTy::from_ty(ty_from);
2113 let cast_ty_to = CastTy::from_ty(*ty);
2114 match (cast_ty_from, cast_ty_to) {
2115 (Some(CastTy::Int(_)), Some(CastTy::Float)) => (),
2120 "Invalid IntToFloat cast {:?} -> {:?}",
2127 CastKind::FloatToInt => {
2128 let ty_from = op.ty(body, tcx);
2129 let cast_ty_from = CastTy::from_ty(ty_from);
2130 let cast_ty_to = CastTy::from_ty(*ty);
2131 match (cast_ty_from, cast_ty_to) {
2132 (Some(CastTy::Float), Some(CastTy::Int(_))) => (),
2137 "Invalid FloatToInt cast {:?} -> {:?}",
2144 CastKind::FloatToFloat => {
2145 let ty_from = op.ty(body, tcx);
2146 let cast_ty_from = CastTy::from_ty(ty_from);
2147 let cast_ty_to = CastTy::from_ty(*ty);
2148 match (cast_ty_from, cast_ty_to) {
2149 (Some(CastTy::Float), Some(CastTy::Float)) => (),
2154 "Invalid FloatToFloat cast {:?} -> {:?}",
2161 CastKind::FnPtrToPtr => {
2162 let ty_from = op.ty(body, tcx);
2163 let cast_ty_from = CastTy::from_ty(ty_from);
2164 let cast_ty_to = CastTy::from_ty(*ty);
2165 match (cast_ty_from, cast_ty_to) {
2166 (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
2171 "Invalid FnPtrToPtr cast {:?} -> {:?}",
2178 CastKind::PtrToPtr => {
2179 let ty_from = op.ty(body, tcx);
2180 let cast_ty_from = CastTy::from_ty(ty_from);
2181 let cast_ty_to = CastTy::from_ty(*ty);
2182 match (cast_ty_from, cast_ty_to) {
2183 (Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_))) => (),
2188 "Invalid PtrToPtr cast {:?} -> {:?}",
2198 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2199 self.add_reborrow_constraint(&body, location, *region, borrowed_place);
2203 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2206 self.check_operand(left, location);
2207 self.check_operand(right, location);
2209 let ty_left = left.ty(body, tcx);
2210 match ty_left.kind() {
2211 // Types with regions are comparable if they have a common super-type.
2212 ty::RawPtr(_) | ty::FnPtr(_) => {
2213 let ty_right = right.ty(body, tcx);
2214 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2215 kind: TypeVariableOriginKind::MiscVariable,
2216 span: body.source_info(location).span,
2221 location.to_locations(),
2222 ConstraintCategory::Boring,
2224 .unwrap_or_else(|err| {
2225 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2227 if let Err(terr) = self.sub_types(
2230 location.to_locations(),
2231 ConstraintCategory::Boring,
2236 "unexpected comparison types {:?} and {:?} yields {:?}",
2243 // For types with no regions we can just check that the
2244 // both operands have the same type.
2245 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2246 if ty_left == right.ty(body, tcx) => {}
2247 // Other types are compared by trait methods, not by
2248 // `Rvalue::BinaryOp`.
2252 "unexpected comparison types {:?} and {:?}",
2259 Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => {
2260 self.check_operand(operand, location);
2262 Rvalue::CopyForDeref(place) => {
2263 let op = &Operand::Copy(*place);
2264 self.check_operand(op, location);
2267 Rvalue::BinaryOp(_, box (left, right))
2268 | Rvalue::CheckedBinaryOp(_, box (left, right)) => {
2269 self.check_operand(left, location);
2270 self.check_operand(right, location);
2273 Rvalue::AddressOf(..)
2274 | Rvalue::ThreadLocalRef(..)
2276 | Rvalue::Discriminant(..) => {}
2280 /// If this rvalue supports a user-given type annotation, then
2281 /// extract and return it. This represents the final type of the
2282 /// rvalue and will be unified with the inferred type.
2283 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2286 | Rvalue::ThreadLocalRef(_)
2287 | Rvalue::Repeat(..)
2289 | Rvalue::AddressOf(..)
2292 | Rvalue::ShallowInitBox(..)
2293 | Rvalue::BinaryOp(..)
2294 | Rvalue::CheckedBinaryOp(..)
2295 | Rvalue::NullaryOp(..)
2296 | Rvalue::CopyForDeref(..)
2297 | Rvalue::UnaryOp(..)
2298 | Rvalue::Discriminant(..) => None,
2300 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2301 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2302 AggregateKind::Array(_) => None,
2303 AggregateKind::Tuple => None,
2304 AggregateKind::Closure(_, _) => None,
2305 AggregateKind::Generator(_, _, _) => None,
2310 fn check_aggregate_rvalue(
2313 rvalue: &Rvalue<'tcx>,
2314 aggregate_kind: &AggregateKind<'tcx>,
2315 operands: &[Operand<'tcx>],
2318 let tcx = self.tcx();
2320 self.prove_aggregate_predicates(aggregate_kind, location);
2322 if *aggregate_kind == AggregateKind::Tuple {
2323 // tuple rvalue field type is always the type of the op. Nothing to check here.
2327 for (i, operand) in operands.iter().enumerate() {
2328 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2329 Ok(field_ty) => field_ty,
2330 Err(FieldAccessError::OutOfRange { field_count }) => {
2334 "accessed field #{} but variant only has {}",
2341 let operand_ty = operand.ty(body, tcx);
2342 let operand_ty = self.normalize(operand_ty, location);
2344 if let Err(terr) = self.sub_types(
2347 location.to_locations(),
2348 ConstraintCategory::Boring,
2353 "{:?} is not a subtype of {:?}: {:?}",
2362 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2366 /// - `location`: the location `L` where the borrow expression occurs
2367 /// - `borrow_region`: the region `'a` associated with the borrow
2368 /// - `borrowed_place`: the place `P` being borrowed
2369 fn add_reborrow_constraint(
2373 borrow_region: ty::Region<'tcx>,
2374 borrowed_place: &Place<'tcx>,
2376 // These constraints are only meaningful during borrowck:
2377 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2378 self.borrowck_context;
2380 // In Polonius mode, we also push a `loan_issued_at` fact
2381 // linking the loan to the region (in some cases, though,
2382 // there is no loan associated with this borrow expression --
2383 // that occurs when we are borrowing an unsafe place, for
2385 if let Some(all_facts) = all_facts {
2386 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2387 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2388 let region_vid = borrow_region.to_region_vid();
2389 all_facts.loan_issued_at.push((
2392 location_table.mid_index(location),
2397 // If we are reborrowing the referent of another reference, we
2398 // need to add outlives relationships. In a case like `&mut
2399 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2400 // need to ensure that `'b: 'a`.
2403 "add_reborrow_constraint({:?}, {:?}, {:?})",
2404 location, borrow_region, borrowed_place
2407 let mut cursor = borrowed_place.projection.as_ref();
2408 let tcx = self.infcx.tcx;
2409 let field = path_utils::is_upvar_field_projection(
2411 &self.borrowck_context.upvars,
2412 borrowed_place.as_ref(),
2415 let category = if let Some(field) = field {
2416 ConstraintCategory::ClosureUpvar(field)
2418 ConstraintCategory::Boring
2421 while let [proj_base @ .., elem] = cursor {
2424 debug!("add_reborrow_constraint - iteration {:?}", elem);
2427 ProjectionElem::Deref => {
2428 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2430 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2431 match base_ty.kind() {
2432 ty::Ref(ref_region, _, mutbl) => {
2433 constraints.outlives_constraints.push(OutlivesConstraint {
2434 sup: ref_region.to_region_vid(),
2435 sub: borrow_region.to_region_vid(),
2436 locations: location.to_locations(),
2437 span: location.to_locations().span(body),
2439 variance_info: ty::VarianceDiagInfo::default(),
2440 from_closure: false,
2444 hir::Mutability::Not => {
2445 // Immutable reference. We don't need the base
2446 // to be valid for the entire lifetime of
2450 hir::Mutability::Mut => {
2451 // Mutable reference. We *do* need the base
2452 // to be valid, because after the base becomes
2453 // invalid, someone else can use our mutable deref.
2455 // This is in order to make the following function
2458 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2463 // As otherwise you could clone `&mut T` using the
2464 // following function:
2466 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2467 // let my_clone = unsafe_deref(&'a x);
2476 // deref of raw pointer, guaranteed to be valid
2479 ty::Adt(def, _) if def.is_box() => {
2480 // deref of `Box`, need the base to be valid - propagate
2482 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2485 ProjectionElem::Field(..)
2486 | ProjectionElem::Downcast(..)
2487 | ProjectionElem::OpaqueCast(..)
2488 | ProjectionElem::Index(..)
2489 | ProjectionElem::ConstantIndex { .. }
2490 | ProjectionElem::Subslice { .. } => {
2491 // other field access
2497 fn prove_aggregate_predicates(
2499 aggregate_kind: &AggregateKind<'tcx>,
2502 let tcx = self.tcx();
2505 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2506 aggregate_kind, location
2509 let (def_id, instantiated_predicates) = match *aggregate_kind {
2510 AggregateKind::Adt(adt_did, _, substs, _, _) => {
2511 (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, substs))
2514 // For closures, we have some **extra requirements** we
2515 // have to check. In particular, in their upvars and
2516 // signatures, closures often reference various regions
2517 // from the surrounding function -- we call those the
2518 // closure's free regions. When we borrow-check (and hence
2519 // region-check) closures, we may find that the closure
2520 // requires certain relationships between those free
2521 // regions. However, because those free regions refer to
2522 // portions of the CFG of their caller, the closure is not
2523 // in a position to verify those relationships. In that
2524 // case, the requirements get "propagated" to us, and so
2525 // we have to solve them here where we instantiate the
2528 // Despite the opacity of the previous paragraph, this is
2529 // actually relatively easy to understand in terms of the
2530 // desugaring. A closure gets desugared to a struct, and
2531 // these extra requirements are basically like where
2532 // clauses on the struct.
2533 AggregateKind::Closure(def_id, substs)
2534 | AggregateKind::Generator(def_id, substs, _) => {
2535 (def_id.to_def_id(), self.prove_closure_bounds(tcx, def_id, substs, location))
2538 AggregateKind::Array(_) | AggregateKind::Tuple => {
2539 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2543 self.normalize_and_prove_instantiated_predicates(
2545 instantiated_predicates,
2546 location.to_locations(),
2550 fn prove_closure_bounds(
2554 substs: SubstsRef<'tcx>,
2556 ) -> ty::InstantiatedPredicates<'tcx> {
2557 if let Some(closure_requirements) = &tcx.mir_borrowck(def_id).closure_requirements {
2558 constraint_conversion::ConstraintConversion::new(
2560 self.borrowck_context.universal_regions,
2561 self.region_bound_pairs,
2562 self.implicit_region_bound,
2564 location.to_locations(),
2565 DUMMY_SP, // irrelevant; will be overrided.
2566 ConstraintCategory::Boring, // same as above.
2567 &mut self.borrowck_context.constraints,
2569 .apply_closure_requirements(
2570 &closure_requirements,
2576 // Now equate closure substs to regions inherited from `typeck_root_def_id`. Fixes #98589.
2577 let typeck_root_def_id = tcx.typeck_root_def_id(self.body.source.def_id());
2578 let typeck_root_substs = ty::InternalSubsts::identity_for_item(tcx, typeck_root_def_id);
2580 let parent_substs = match tcx.def_kind(def_id) {
2581 DefKind::Closure => substs.as_closure().parent_substs(),
2582 DefKind::Generator => substs.as_generator().parent_substs(),
2583 DefKind::InlineConst => substs.as_inline_const().parent_substs(),
2584 other => bug!("unexpected item {:?}", other),
2586 let parent_substs = tcx.mk_substs(parent_substs.iter());
2588 assert_eq!(typeck_root_substs.len(), parent_substs.len());
2589 if let Err(_) = self.eq_substs(
2592 location.to_locations(),
2593 ConstraintCategory::BoringNoLocation,
2598 "could not relate closure to parent {:?} != {:?}",
2604 tcx.predicates_of(def_id).instantiate(tcx, substs)
2607 #[instrument(skip(self, body), level = "debug")]
2608 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2609 self.last_span = body.span;
2612 for (local, local_decl) in body.local_decls.iter_enumerated() {
2613 self.check_local(&body, local, local_decl);
2616 for (block, block_data) in body.basic_blocks.iter_enumerated() {
2617 let mut location = Location { block, statement_index: 0 };
2618 for stmt in &block_data.statements {
2619 if !stmt.source_info.span.is_dummy() {
2620 self.last_span = stmt.source_info.span;
2622 self.check_stmt(body, stmt, location);
2623 location.statement_index += 1;
2626 self.check_terminator(&body, block_data.terminator(), location);
2627 self.check_iscleanup(&body, block_data);
2632 trait NormalizeLocation: fmt::Debug + Copy {
2633 fn to_locations(self) -> Locations;
2636 impl NormalizeLocation for Locations {
2637 fn to_locations(self) -> Locations {
2642 impl NormalizeLocation for Location {
2643 fn to_locations(self) -> Locations {
2644 Locations::Single(self)
2648 /// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2649 /// this is not canonicalized - it directly affects the main `InferCtxt`
2650 /// that we use during MIR borrowchecking.
2652 pub(super) struct InstantiateOpaqueType<'tcx> {
2653 pub base_universe: Option<ty::UniverseIndex>,
2654 pub region_constraints: Option<RegionConstraintData<'tcx>>,
2655 pub obligations: Vec<PredicateObligation<'tcx>>,
2658 impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2660 /// We use this type itself to store the information used
2661 /// when reporting errors. Since this is not a query, we don't
2662 /// re-run anything during error reporting - we just use the information
2663 /// we saved to help extract an error from the already-existing region
2664 /// constraints in our `InferCtxt`
2665 type ErrorInfo = InstantiateOpaqueType<'tcx>;
2667 fn fully_perform(mut self, infcx: &InferCtxt<'tcx>) -> Fallible<TypeOpOutput<'tcx, Self>> {
2668 let (mut output, region_constraints) = scrape_region_constraints(infcx, || {
2669 Ok(InferOk { value: (), obligations: self.obligations.clone() })
2671 self.region_constraints = Some(region_constraints);
2672 output.error_info = Some(self);