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::ConstEvalCounter
1262 | StatementKind::Nop => {}
1263 StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
1264 bug!("Statement not allowed in this MIR phase")
1269 #[instrument(skip(self, body, term_location), level = "debug")]
1270 fn check_terminator(
1273 term: &Terminator<'tcx>,
1274 term_location: Location,
1276 let tcx = self.tcx();
1277 debug!("terminator kind: {:?}", term.kind);
1279 TerminatorKind::Goto { .. }
1280 | TerminatorKind::Resume
1281 | TerminatorKind::Abort
1282 | TerminatorKind::Return
1283 | TerminatorKind::GeneratorDrop
1284 | TerminatorKind::Unreachable
1285 | TerminatorKind::Drop { .. }
1286 | TerminatorKind::FalseEdge { .. }
1287 | TerminatorKind::FalseUnwind { .. }
1288 | TerminatorKind::InlineAsm { .. } => {
1289 // no checks needed for these
1292 TerminatorKind::DropAndReplace { place, value, target: _, unwind: _ } => {
1293 let place_ty = place.ty(body, tcx).ty;
1294 let rv_ty = value.ty(body, tcx);
1296 let locations = term_location.to_locations();
1298 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1303 "bad DropAndReplace ({:?} = {:?}): {:?}",
1310 TerminatorKind::SwitchInt { discr, .. } => {
1311 self.check_operand(discr, term_location);
1313 let switch_ty = discr.ty(body, tcx);
1314 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1315 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1317 // FIXME: check the values
1319 TerminatorKind::Call { func, args, destination, from_hir_call, target, .. } => {
1320 self.check_operand(func, term_location);
1322 self.check_operand(arg, term_location);
1325 let func_ty = func.ty(body, tcx);
1326 debug!("func_ty.kind: {:?}", func_ty.kind());
1328 let sig = match func_ty.kind() {
1329 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1331 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1335 let (sig, map) = tcx.replace_late_bound_regions(sig, |br| {
1336 self.infcx.next_region_var(LateBoundRegion(
1337 term.source_info.span,
1339 LateBoundRegionConversionTime::FnCall,
1343 // IMPORTANT: We have to prove well formed for the function signature before
1344 // we normalize it, as otherwise types like `<&'a &'b () as Trait>::Assoc`
1345 // get normalized away, causing us to ignore the `'b: 'a` bound used by the function.
1347 // Normalization results in a well formed type if the input is well formed, so we
1348 // don't have to check it twice.
1350 // See #91068 for an example.
1351 self.prove_predicates(
1352 sig.inputs_and_output
1354 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1355 term_location.to_locations(),
1356 ConstraintCategory::Boring,
1358 let sig = self.normalize(sig, term_location);
1359 self.check_call_dest(body, term, &sig, *destination, *target, term_location);
1361 // The ordinary liveness rules will ensure that all
1362 // regions in the type of the callee are live here. We
1363 // then further constrain the late-bound regions that
1364 // were instantiated at the call site to be live as
1365 // well. The resulting is that all the input (and
1366 // output) types in the signature must be live, since
1367 // all the inputs that fed into it were live.
1368 for &late_bound_region in map.values() {
1370 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1371 self.borrowck_context
1373 .liveness_constraints
1374 .add_element(region_vid, term_location);
1377 self.check_call_inputs(body, term, &sig, args, term_location, *from_hir_call);
1379 TerminatorKind::Assert { cond, msg, .. } => {
1380 self.check_operand(cond, term_location);
1382 let cond_ty = cond.ty(body, tcx);
1383 if cond_ty != tcx.types.bool {
1384 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1387 if let AssertKind::BoundsCheck { len, index } = msg {
1388 if len.ty(body, tcx) != tcx.types.usize {
1389 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1391 if index.ty(body, tcx) != tcx.types.usize {
1392 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1396 TerminatorKind::Yield { value, .. } => {
1397 self.check_operand(value, term_location);
1399 let value_ty = value.ty(body, tcx);
1400 match body.yield_ty() {
1401 None => span_mirbug!(self, term, "yield in non-generator"),
1403 if let Err(terr) = self.sub_types(
1406 term_location.to_locations(),
1407 ConstraintCategory::Yield,
1412 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1427 term: &Terminator<'tcx>,
1428 sig: &ty::FnSig<'tcx>,
1429 destination: Place<'tcx>,
1430 target: Option<BasicBlock>,
1431 term_location: Location,
1433 let tcx = self.tcx();
1436 let dest_ty = destination.ty(body, tcx).ty;
1437 let dest_ty = self.normalize(dest_ty, term_location);
1438 let category = match destination.as_local() {
1439 Some(RETURN_PLACE) => {
1440 if let BorrowCheckContext {
1444 DefiningTy::Const(def_id, _)
1445 | DefiningTy::InlineConst(def_id, _),
1449 } = self.borrowck_context
1451 if tcx.is_static(*def_id) {
1452 ConstraintCategory::UseAsStatic
1454 ConstraintCategory::UseAsConst
1457 ConstraintCategory::Return(ReturnConstraint::Normal)
1460 Some(l) if !body.local_decls[l].is_user_variable() => {
1461 ConstraintCategory::Boring
1463 _ => ConstraintCategory::Assignment,
1466 let locations = term_location.to_locations();
1468 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1472 "call dest mismatch ({:?} <- {:?}): {:?}",
1479 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1480 // this check is done at `check_local`.
1481 if self.unsized_feature_enabled() {
1482 let span = term.source_info.span;
1483 self.ensure_place_sized(dest_ty, span);
1487 // The signature in this call can reference region variables,
1488 // so erase them before calling a query.
1489 let output_ty = self.tcx().erase_regions(sig.output());
1490 if !output_ty.is_privately_uninhabited(self.tcx(), self.param_env) {
1491 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1497 fn check_call_inputs(
1500 term: &Terminator<'tcx>,
1501 sig: &ty::FnSig<'tcx>,
1502 args: &[Operand<'tcx>],
1503 term_location: Location,
1504 from_hir_call: bool,
1506 debug!("check_call_inputs({:?}, {:?})", sig, args);
1507 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1508 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1511 let func_ty = if let TerminatorKind::Call { func, .. } = &term.kind {
1512 Some(func.ty(body, self.infcx.tcx))
1518 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1519 let op_arg_ty = op_arg.ty(body, self.tcx());
1521 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1522 let category = if from_hir_call {
1523 ConstraintCategory::CallArgument(self.infcx.tcx.erase_regions(func_ty))
1525 ConstraintCategory::Boring
1528 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
1533 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1543 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1544 let is_cleanup = block_data.is_cleanup;
1545 self.last_span = block_data.terminator().source_info.span;
1546 match block_data.terminator().kind {
1547 TerminatorKind::Goto { target } => {
1548 self.assert_iscleanup(body, block_data, target, is_cleanup)
1550 TerminatorKind::SwitchInt { ref targets, .. } => {
1551 for target in targets.all_targets() {
1552 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1555 TerminatorKind::Resume => {
1557 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1560 TerminatorKind::Abort => {
1562 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1565 TerminatorKind::Return => {
1567 span_mirbug!(self, block_data, "return on cleanup block")
1570 TerminatorKind::GeneratorDrop { .. } => {
1572 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1575 TerminatorKind::Yield { resume, drop, .. } => {
1577 span_mirbug!(self, block_data, "yield in cleanup block")
1579 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1580 if let Some(drop) = drop {
1581 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1584 TerminatorKind::Unreachable => {}
1585 TerminatorKind::Drop { target, unwind, .. }
1586 | TerminatorKind::DropAndReplace { target, unwind, .. }
1587 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1588 self.assert_iscleanup(body, block_data, target, is_cleanup);
1589 if let Some(unwind) = unwind {
1591 span_mirbug!(self, block_data, "unwind on cleanup block")
1593 self.assert_iscleanup(body, block_data, unwind, true);
1596 TerminatorKind::Call { ref target, cleanup, .. } => {
1597 if let &Some(target) = target {
1598 self.assert_iscleanup(body, block_data, target, is_cleanup);
1600 if let Some(cleanup) = cleanup {
1602 span_mirbug!(self, block_data, "cleanup on cleanup block")
1604 self.assert_iscleanup(body, block_data, cleanup, true);
1607 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1608 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1609 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1611 TerminatorKind::FalseUnwind { real_target, unwind } => {
1612 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1613 if let Some(unwind) = unwind {
1615 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1617 self.assert_iscleanup(body, block_data, unwind, true);
1620 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
1621 if let Some(target) = destination {
1622 self.assert_iscleanup(body, block_data, target, is_cleanup);
1624 if let Some(cleanup) = cleanup {
1626 span_mirbug!(self, block_data, "cleanup on cleanup block")
1628 self.assert_iscleanup(body, block_data, cleanup, true);
1634 fn assert_iscleanup(
1637 ctxt: &dyn fmt::Debug,
1641 if body[bb].is_cleanup != iscleanuppad {
1642 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1646 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1647 match body.local_kind(local) {
1648 LocalKind::ReturnPointer | LocalKind::Arg => {
1649 // return values of normal functions are required to be
1650 // sized by typeck, but return values of ADT constructors are
1651 // not because we don't include a `Self: Sized` bounds on them.
1653 // Unbound parts of arguments were never required to be Sized
1654 // - maybe we should make that a warning.
1657 LocalKind::Var | LocalKind::Temp => {}
1660 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1661 // and nullary ops are checked in `check_call_dest`.
1662 if !self.unsized_feature_enabled() {
1663 let span = local_decl.source_info.span;
1664 let ty = local_decl.ty;
1665 self.ensure_place_sized(ty, span);
1669 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1670 let tcx = self.tcx();
1672 // Erase the regions from `ty` to get a global type. The
1673 // `Sized` bound in no way depends on precise regions, so this
1674 // shouldn't affect `is_sized`.
1675 let erased_ty = tcx.erase_regions(ty);
1676 if !erased_ty.is_sized(tcx, self.param_env) {
1677 // in current MIR construction, all non-control-flow rvalue
1678 // expressions evaluate through `as_temp` or `into` a return
1679 // slot or local, so to find all unsized rvalues it is enough
1680 // to check all temps, return slots and locals.
1681 if self.reported_errors.replace((ty, span)).is_none() {
1682 // While this is located in `nll::typeck` this error is not
1683 // an NLL error, it's a required check to prevent creation
1684 // of unsized rvalues in a call expression.
1685 self.tcx().sess.emit_err(MoveUnsized { ty, span });
1690 fn aggregate_field_ty(
1692 ak: &AggregateKind<'tcx>,
1695 ) -> Result<Ty<'tcx>, FieldAccessError> {
1696 let tcx = self.tcx();
1699 AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => {
1700 let def = tcx.adt_def(adt_did);
1701 let variant = &def.variant(variant_index);
1702 let adj_field_index = active_field_index.unwrap_or(field_index);
1703 if let Some(field) = variant.fields.get(adj_field_index) {
1704 Ok(self.normalize(field.ty(tcx, substs), location))
1706 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1709 AggregateKind::Closure(_, substs) => {
1710 match substs.as_closure().upvar_tys().nth(field_index) {
1712 None => Err(FieldAccessError::OutOfRange {
1713 field_count: substs.as_closure().upvar_tys().count(),
1717 AggregateKind::Generator(_, substs, _) => {
1718 // It doesn't make sense to look at a field beyond the prefix;
1719 // these require a variant index, and are not initialized in
1720 // aggregate rvalues.
1721 match substs.as_generator().prefix_tys().nth(field_index) {
1723 None => Err(FieldAccessError::OutOfRange {
1724 field_count: substs.as_generator().prefix_tys().count(),
1728 AggregateKind::Array(ty) => Ok(ty),
1729 AggregateKind::Tuple => {
1730 unreachable!("This should have been covered in check_rvalues");
1735 fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1736 debug!(?op, ?location, "check_operand");
1738 if let Operand::Constant(constant) = op {
1739 let maybe_uneval = match constant.literal {
1740 ConstantKind::Val(..) | ConstantKind::Ty(_) => None,
1741 ConstantKind::Unevaluated(uv, _) => Some(uv),
1744 if let Some(uv) = maybe_uneval {
1745 if uv.promoted.is_none() {
1746 let tcx = self.tcx();
1747 let def_id = uv.def.def_id_for_type_of();
1748 if tcx.def_kind(def_id) == DefKind::InlineConst {
1749 let def_id = def_id.expect_local();
1751 self.prove_closure_bounds(tcx, def_id, uv.substs, location);
1752 self.normalize_and_prove_instantiated_predicates(
1755 location.to_locations(),
1763 #[instrument(skip(self, body), level = "debug")]
1764 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1765 let tcx = self.tcx();
1766 let span = body.source_info(location).span;
1769 Rvalue::Aggregate(ak, ops) => {
1771 self.check_operand(op, location);
1773 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1776 Rvalue::Repeat(operand, len) => {
1777 self.check_operand(operand, location);
1779 // If the length cannot be evaluated we must assume that the length can be larger
1781 // If the length is larger than 1, the repeat expression will need to copy the
1782 // element, so we require the `Copy` trait.
1783 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1785 Operand::Copy(..) | Operand::Constant(..) => {
1786 // These are always okay: direct use of a const, or a value that can evidently be copied.
1788 Operand::Move(place) => {
1789 // Make sure that repeated elements implement `Copy`.
1790 let ty = place.ty(body, tcx).ty;
1791 let trait_ref = tcx.at(span).mk_trait_ref(LangItem::Copy, [ty]);
1793 self.prove_trait_ref(
1795 Locations::Single(location),
1796 ConstraintCategory::CopyBound,
1803 &Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, ty) => {
1804 let trait_ref = tcx.at(span).mk_trait_ref(LangItem::Sized, [ty]);
1806 self.prove_trait_ref(
1808 location.to_locations(),
1809 ConstraintCategory::SizedBound,
1813 Rvalue::ShallowInitBox(operand, ty) => {
1814 self.check_operand(operand, location);
1816 let trait_ref = tcx.at(span).mk_trait_ref(LangItem::Sized, [*ty]);
1818 self.prove_trait_ref(
1820 location.to_locations(),
1821 ConstraintCategory::SizedBound,
1825 Rvalue::Cast(cast_kind, op, ty) => {
1826 self.check_operand(op, location);
1829 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1830 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1832 // The type that we see in the fcx is like
1833 // `foo::<'a, 'b>`, where `foo` is the path to a
1834 // function definition. When we extract the
1835 // signature, it comes from the `fn_sig` query,
1836 // and hence may contain unnormalized results.
1837 let fn_sig = self.normalize(fn_sig, location);
1839 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1841 if let Err(terr) = self.eq_types(
1844 location.to_locations(),
1845 ConstraintCategory::Cast,
1850 "equating {:?} with {:?} yields {:?}",
1858 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
1859 let sig = match op.ty(body, tcx).kind() {
1860 ty::Closure(_, substs) => substs.as_closure().sig(),
1863 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
1865 if let Err(terr) = self.eq_types(
1868 location.to_locations(),
1869 ConstraintCategory::Cast,
1874 "equating {:?} with {:?} yields {:?}",
1882 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
1883 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1885 // The type that we see in the fcx is like
1886 // `foo::<'a, 'b>`, where `foo` is the path to a
1887 // function definition. When we extract the
1888 // signature, it comes from the `fn_sig` query,
1889 // and hence may contain unnormalized results.
1890 let fn_sig = self.normalize(fn_sig, location);
1892 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1894 if let Err(terr) = self.eq_types(
1897 location.to_locations(),
1898 ConstraintCategory::Cast,
1903 "equating {:?} with {:?} yields {:?}",
1911 CastKind::Pointer(PointerCast::Unsize) => {
1915 .mk_trait_ref(LangItem::CoerceUnsized, [op.ty(body, tcx), ty]);
1917 self.prove_trait_ref(
1919 location.to_locations(),
1920 ConstraintCategory::Cast,
1924 CastKind::DynStar => {
1925 // get the constraints from the target type (`dyn* Clone`)
1927 // apply them to prove that the source type `Foo` implements `Clone` etc
1928 let (existential_predicates, region) = match ty.kind() {
1929 Dynamic(predicates, region, ty::DynStar) => (predicates, region),
1930 _ => panic!("Invalid dyn* cast_ty"),
1933 let self_ty = op.ty(body, tcx);
1935 self.prove_predicates(
1936 existential_predicates
1938 .map(|predicate| predicate.with_self_ty(tcx, self_ty)),
1939 location.to_locations(),
1940 ConstraintCategory::Cast,
1943 let outlives_predicate =
1944 tcx.mk_predicate(Binder::dummy(ty::PredicateKind::Clause(
1945 ty::Clause::TypeOutlives(ty::OutlivesPredicate(self_ty, *region)),
1947 self.prove_predicate(
1949 location.to_locations(),
1950 ConstraintCategory::Cast,
1954 CastKind::Pointer(PointerCast::MutToConstPointer) => {
1955 let ty::RawPtr(ty::TypeAndMut {
1957 mutbl: hir::Mutability::Mut,
1958 }) = op.ty(body, tcx).kind() else {
1962 "unexpected base type for cast {:?}",
1967 let ty::RawPtr(ty::TypeAndMut {
1969 mutbl: hir::Mutability::Not,
1970 }) = ty.kind() else {
1974 "unexpected target type for cast {:?}",
1979 if let Err(terr) = self.sub_types(
1982 location.to_locations(),
1983 ConstraintCategory::Cast,
1988 "relating {:?} with {:?} yields {:?}",
1996 CastKind::Pointer(PointerCast::ArrayToPointer) => {
1997 let ty_from = op.ty(body, tcx);
1999 let opt_ty_elem_mut = match ty_from.kind() {
2000 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2001 match array_ty.kind() {
2002 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2009 let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
2013 "ArrayToPointer cast from unexpected type {:?}",
2019 let (ty_to, ty_to_mut) = match ty.kind() {
2020 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2027 "ArrayToPointer cast to unexpected type {:?}",
2034 if ty_to_mut.is_mut() && ty_mut.is_not() {
2038 "ArrayToPointer cast from const {:?} to mut {:?}",
2045 if let Err(terr) = self.sub_types(
2048 location.to_locations(),
2049 ConstraintCategory::Cast,
2054 "relating {:?} with {:?} yields {:?}",
2062 CastKind::PointerExposeAddress => {
2063 let ty_from = op.ty(body, tcx);
2064 let cast_ty_from = CastTy::from_ty(ty_from);
2065 let cast_ty_to = CastTy::from_ty(*ty);
2066 match (cast_ty_from, cast_ty_to) {
2067 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => (),
2072 "Invalid PointerExposeAddress cast {:?} -> {:?}",
2080 CastKind::PointerFromExposedAddress => {
2081 let ty_from = op.ty(body, tcx);
2082 let cast_ty_from = CastTy::from_ty(ty_from);
2083 let cast_ty_to = CastTy::from_ty(*ty);
2084 match (cast_ty_from, cast_ty_to) {
2085 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
2090 "Invalid PointerFromExposedAddress cast {:?} -> {:?}",
2097 CastKind::IntToInt => {
2098 let ty_from = op.ty(body, tcx);
2099 let cast_ty_from = CastTy::from_ty(ty_from);
2100 let cast_ty_to = CastTy::from_ty(*ty);
2101 match (cast_ty_from, cast_ty_to) {
2102 (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => (),
2107 "Invalid IntToInt cast {:?} -> {:?}",
2114 CastKind::IntToFloat => {
2115 let ty_from = op.ty(body, tcx);
2116 let cast_ty_from = CastTy::from_ty(ty_from);
2117 let cast_ty_to = CastTy::from_ty(*ty);
2118 match (cast_ty_from, cast_ty_to) {
2119 (Some(CastTy::Int(_)), Some(CastTy::Float)) => (),
2124 "Invalid IntToFloat cast {:?} -> {:?}",
2131 CastKind::FloatToInt => {
2132 let ty_from = op.ty(body, tcx);
2133 let cast_ty_from = CastTy::from_ty(ty_from);
2134 let cast_ty_to = CastTy::from_ty(*ty);
2135 match (cast_ty_from, cast_ty_to) {
2136 (Some(CastTy::Float), Some(CastTy::Int(_))) => (),
2141 "Invalid FloatToInt cast {:?} -> {:?}",
2148 CastKind::FloatToFloat => {
2149 let ty_from = op.ty(body, tcx);
2150 let cast_ty_from = CastTy::from_ty(ty_from);
2151 let cast_ty_to = CastTy::from_ty(*ty);
2152 match (cast_ty_from, cast_ty_to) {
2153 (Some(CastTy::Float), Some(CastTy::Float)) => (),
2158 "Invalid FloatToFloat cast {:?} -> {:?}",
2165 CastKind::FnPtrToPtr => {
2166 let ty_from = op.ty(body, tcx);
2167 let cast_ty_from = CastTy::from_ty(ty_from);
2168 let cast_ty_to = CastTy::from_ty(*ty);
2169 match (cast_ty_from, cast_ty_to) {
2170 (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
2175 "Invalid FnPtrToPtr cast {:?} -> {:?}",
2182 CastKind::PtrToPtr => {
2183 let ty_from = op.ty(body, tcx);
2184 let cast_ty_from = CastTy::from_ty(ty_from);
2185 let cast_ty_to = CastTy::from_ty(*ty);
2186 match (cast_ty_from, cast_ty_to) {
2187 (Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_))) => (),
2192 "Invalid PtrToPtr cast {:?} -> {:?}",
2202 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2203 self.add_reborrow_constraint(&body, location, *region, borrowed_place);
2207 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2210 self.check_operand(left, location);
2211 self.check_operand(right, location);
2213 let ty_left = left.ty(body, tcx);
2214 match ty_left.kind() {
2215 // Types with regions are comparable if they have a common super-type.
2216 ty::RawPtr(_) | ty::FnPtr(_) => {
2217 let ty_right = right.ty(body, tcx);
2218 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2219 kind: TypeVariableOriginKind::MiscVariable,
2220 span: body.source_info(location).span,
2225 location.to_locations(),
2226 ConstraintCategory::Boring,
2228 .unwrap_or_else(|err| {
2229 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2231 if let Err(terr) = self.sub_types(
2234 location.to_locations(),
2235 ConstraintCategory::Boring,
2240 "unexpected comparison types {:?} and {:?} yields {:?}",
2247 // For types with no regions we can just check that the
2248 // both operands have the same type.
2249 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2250 if ty_left == right.ty(body, tcx) => {}
2251 // Other types are compared by trait methods, not by
2252 // `Rvalue::BinaryOp`.
2256 "unexpected comparison types {:?} and {:?}",
2263 Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => {
2264 self.check_operand(operand, location);
2266 Rvalue::CopyForDeref(place) => {
2267 let op = &Operand::Copy(*place);
2268 self.check_operand(op, location);
2271 Rvalue::BinaryOp(_, box (left, right))
2272 | Rvalue::CheckedBinaryOp(_, box (left, right)) => {
2273 self.check_operand(left, location);
2274 self.check_operand(right, location);
2277 Rvalue::AddressOf(..)
2278 | Rvalue::ThreadLocalRef(..)
2280 | Rvalue::Discriminant(..) => {}
2284 /// If this rvalue supports a user-given type annotation, then
2285 /// extract and return it. This represents the final type of the
2286 /// rvalue and will be unified with the inferred type.
2287 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2290 | Rvalue::ThreadLocalRef(_)
2291 | Rvalue::Repeat(..)
2293 | Rvalue::AddressOf(..)
2296 | Rvalue::ShallowInitBox(..)
2297 | Rvalue::BinaryOp(..)
2298 | Rvalue::CheckedBinaryOp(..)
2299 | Rvalue::NullaryOp(..)
2300 | Rvalue::CopyForDeref(..)
2301 | Rvalue::UnaryOp(..)
2302 | Rvalue::Discriminant(..) => None,
2304 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2305 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2306 AggregateKind::Array(_) => None,
2307 AggregateKind::Tuple => None,
2308 AggregateKind::Closure(_, _) => None,
2309 AggregateKind::Generator(_, _, _) => None,
2314 fn check_aggregate_rvalue(
2317 rvalue: &Rvalue<'tcx>,
2318 aggregate_kind: &AggregateKind<'tcx>,
2319 operands: &[Operand<'tcx>],
2322 let tcx = self.tcx();
2324 self.prove_aggregate_predicates(aggregate_kind, location);
2326 if *aggregate_kind == AggregateKind::Tuple {
2327 // tuple rvalue field type is always the type of the op. Nothing to check here.
2331 for (i, operand) in operands.iter().enumerate() {
2332 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2333 Ok(field_ty) => field_ty,
2334 Err(FieldAccessError::OutOfRange { field_count }) => {
2338 "accessed field #{} but variant only has {}",
2345 let operand_ty = operand.ty(body, tcx);
2346 let operand_ty = self.normalize(operand_ty, location);
2348 if let Err(terr) = self.sub_types(
2351 location.to_locations(),
2352 ConstraintCategory::Boring,
2357 "{:?} is not a subtype of {:?}: {:?}",
2366 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2370 /// - `location`: the location `L` where the borrow expression occurs
2371 /// - `borrow_region`: the region `'a` associated with the borrow
2372 /// - `borrowed_place`: the place `P` being borrowed
2373 fn add_reborrow_constraint(
2377 borrow_region: ty::Region<'tcx>,
2378 borrowed_place: &Place<'tcx>,
2380 // These constraints are only meaningful during borrowck:
2381 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2382 self.borrowck_context;
2384 // In Polonius mode, we also push a `loan_issued_at` fact
2385 // linking the loan to the region (in some cases, though,
2386 // there is no loan associated with this borrow expression --
2387 // that occurs when we are borrowing an unsafe place, for
2389 if let Some(all_facts) = all_facts {
2390 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2391 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2392 let region_vid = borrow_region.to_region_vid();
2393 all_facts.loan_issued_at.push((
2396 location_table.mid_index(location),
2401 // If we are reborrowing the referent of another reference, we
2402 // need to add outlives relationships. In a case like `&mut
2403 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2404 // need to ensure that `'b: 'a`.
2407 "add_reborrow_constraint({:?}, {:?}, {:?})",
2408 location, borrow_region, borrowed_place
2411 let mut cursor = borrowed_place.projection.as_ref();
2412 let tcx = self.infcx.tcx;
2413 let field = path_utils::is_upvar_field_projection(
2415 &self.borrowck_context.upvars,
2416 borrowed_place.as_ref(),
2419 let category = if let Some(field) = field {
2420 ConstraintCategory::ClosureUpvar(field)
2422 ConstraintCategory::Boring
2425 while let [proj_base @ .., elem] = cursor {
2428 debug!("add_reborrow_constraint - iteration {:?}", elem);
2431 ProjectionElem::Deref => {
2432 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2434 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2435 match base_ty.kind() {
2436 ty::Ref(ref_region, _, mutbl) => {
2437 constraints.outlives_constraints.push(OutlivesConstraint {
2438 sup: ref_region.to_region_vid(),
2439 sub: borrow_region.to_region_vid(),
2440 locations: location.to_locations(),
2441 span: location.to_locations().span(body),
2443 variance_info: ty::VarianceDiagInfo::default(),
2444 from_closure: false,
2448 hir::Mutability::Not => {
2449 // Immutable reference. We don't need the base
2450 // to be valid for the entire lifetime of
2454 hir::Mutability::Mut => {
2455 // Mutable reference. We *do* need the base
2456 // to be valid, because after the base becomes
2457 // invalid, someone else can use our mutable deref.
2459 // This is in order to make the following function
2462 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2467 // As otherwise you could clone `&mut T` using the
2468 // following function:
2470 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2471 // let my_clone = unsafe_deref(&'a x);
2480 // deref of raw pointer, guaranteed to be valid
2483 ty::Adt(def, _) if def.is_box() => {
2484 // deref of `Box`, need the base to be valid - propagate
2486 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2489 ProjectionElem::Field(..)
2490 | ProjectionElem::Downcast(..)
2491 | ProjectionElem::OpaqueCast(..)
2492 | ProjectionElem::Index(..)
2493 | ProjectionElem::ConstantIndex { .. }
2494 | ProjectionElem::Subslice { .. } => {
2495 // other field access
2501 fn prove_aggregate_predicates(
2503 aggregate_kind: &AggregateKind<'tcx>,
2506 let tcx = self.tcx();
2509 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2510 aggregate_kind, location
2513 let (def_id, instantiated_predicates) = match *aggregate_kind {
2514 AggregateKind::Adt(adt_did, _, substs, _, _) => {
2515 (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, substs))
2518 // For closures, we have some **extra requirements** we
2519 // have to check. In particular, in their upvars and
2520 // signatures, closures often reference various regions
2521 // from the surrounding function -- we call those the
2522 // closure's free regions. When we borrow-check (and hence
2523 // region-check) closures, we may find that the closure
2524 // requires certain relationships between those free
2525 // regions. However, because those free regions refer to
2526 // portions of the CFG of their caller, the closure is not
2527 // in a position to verify those relationships. In that
2528 // case, the requirements get "propagated" to us, and so
2529 // we have to solve them here where we instantiate the
2532 // Despite the opacity of the previous paragraph, this is
2533 // actually relatively easy to understand in terms of the
2534 // desugaring. A closure gets desugared to a struct, and
2535 // these extra requirements are basically like where
2536 // clauses on the struct.
2537 AggregateKind::Closure(def_id, substs)
2538 | AggregateKind::Generator(def_id, substs, _) => {
2539 (def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location))
2542 AggregateKind::Array(_) | AggregateKind::Tuple => {
2543 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2547 self.normalize_and_prove_instantiated_predicates(
2549 instantiated_predicates,
2550 location.to_locations(),
2554 fn prove_closure_bounds(
2558 substs: SubstsRef<'tcx>,
2560 ) -> ty::InstantiatedPredicates<'tcx> {
2561 if let Some(closure_requirements) = &tcx.mir_borrowck(def_id).closure_requirements {
2562 constraint_conversion::ConstraintConversion::new(
2564 self.borrowck_context.universal_regions,
2565 self.region_bound_pairs,
2566 self.implicit_region_bound,
2568 location.to_locations(),
2569 DUMMY_SP, // irrelevant; will be overrided.
2570 ConstraintCategory::Boring, // same as above.
2571 &mut self.borrowck_context.constraints,
2573 .apply_closure_requirements(
2574 &closure_requirements,
2580 // Now equate closure substs to regions inherited from `typeck_root_def_id`. Fixes #98589.
2581 let typeck_root_def_id = tcx.typeck_root_def_id(self.body.source.def_id());
2582 let typeck_root_substs = ty::InternalSubsts::identity_for_item(tcx, typeck_root_def_id);
2584 let parent_substs = match tcx.def_kind(def_id) {
2585 DefKind::Closure => substs.as_closure().parent_substs(),
2586 DefKind::Generator => substs.as_generator().parent_substs(),
2587 DefKind::InlineConst => substs.as_inline_const().parent_substs(),
2588 other => bug!("unexpected item {:?}", other),
2590 let parent_substs = tcx.mk_substs(parent_substs.iter());
2592 assert_eq!(typeck_root_substs.len(), parent_substs.len());
2593 if let Err(_) = self.eq_substs(
2596 location.to_locations(),
2597 ConstraintCategory::BoringNoLocation,
2602 "could not relate closure to parent {:?} != {:?}",
2608 tcx.predicates_of(def_id).instantiate(tcx, substs)
2611 #[instrument(skip(self, body), level = "debug")]
2612 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2613 self.last_span = body.span;
2616 for (local, local_decl) in body.local_decls.iter_enumerated() {
2617 self.check_local(&body, local, local_decl);
2620 for (block, block_data) in body.basic_blocks.iter_enumerated() {
2621 let mut location = Location { block, statement_index: 0 };
2622 for stmt in &block_data.statements {
2623 if !stmt.source_info.span.is_dummy() {
2624 self.last_span = stmt.source_info.span;
2626 self.check_stmt(body, stmt, location);
2627 location.statement_index += 1;
2630 self.check_terminator(&body, block_data.terminator(), location);
2631 self.check_iscleanup(&body, block_data);
2636 trait NormalizeLocation: fmt::Debug + Copy {
2637 fn to_locations(self) -> Locations;
2640 impl NormalizeLocation for Locations {
2641 fn to_locations(self) -> Locations {
2646 impl NormalizeLocation for Location {
2647 fn to_locations(self) -> Locations {
2648 Locations::Single(self)
2652 /// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2653 /// this is not canonicalized - it directly affects the main `InferCtxt`
2654 /// that we use during MIR borrowchecking.
2656 pub(super) struct InstantiateOpaqueType<'tcx> {
2657 pub base_universe: Option<ty::UniverseIndex>,
2658 pub region_constraints: Option<RegionConstraintData<'tcx>>,
2659 pub obligations: Vec<PredicateObligation<'tcx>>,
2662 impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2664 /// We use this type itself to store the information used
2665 /// when reporting errors. Since this is not a query, we don't
2666 /// re-run anything during error reporting - we just use the information
2667 /// we saved to help extract an error from the already-existing region
2668 /// constraints in our `InferCtxt`
2669 type ErrorInfo = InstantiateOpaqueType<'tcx>;
2671 fn fully_perform(mut self, infcx: &InferCtxt<'tcx>) -> Fallible<TypeOpOutput<'tcx, Self>> {
2672 let (mut output, region_constraints) = scrape_region_constraints(infcx, || {
2673 Ok(InferOk { value: (), obligations: self.obligations.clone() })
2675 self.region_constraints = Some(region_constraints);
2676 output.error_info = Some(self);