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;
42 use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
43 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
44 use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
45 use rustc_trait_selection::traits::query::Fallible;
46 use rustc_trait_selection::traits::PredicateObligation;
48 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
49 use rustc_mir_dataflow::move_paths::MoveData;
50 use rustc_mir_dataflow::ResultsCursor;
52 use crate::session_diagnostics::MoveUnsized;
54 borrow_set::BorrowSet,
55 constraints::{OutlivesConstraint, OutlivesConstraintSet},
56 diagnostics::UniverseInfo,
58 location::LocationTable,
59 member_constraints::MemberConstraintSet,
62 region_infer::values::{
63 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
65 region_infer::TypeTest,
66 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
67 universal_regions::{DefiningTy, UniversalRegions},
71 macro_rules! span_mirbug {
72 ($context:expr, $elem:expr, $($message:tt)*) => ({
73 $crate::type_check::mirbug(
77 "broken MIR in {:?} ({:?}): {}",
78 $context.body().source.def_id(),
80 format_args!($($message)*),
86 macro_rules! span_mirbug_and_err {
87 ($context:expr, $elem:expr, $($message:tt)*) => ({
89 span_mirbug!($context, $elem, $($message)*);
96 mod constraint_conversion;
97 pub mod free_region_relations;
99 pub(crate) mod liveness;
102 /// Type checks the given `mir` in the context of the inference
103 /// context `infcx`. Returns any region constraints that have yet to
104 /// be proven. This result includes liveness constraints that
105 /// ensure that regions appearing in the types of all local variables
106 /// are live at all points where that local variable may later be
109 /// This phase of type-check ought to be infallible -- this is because
110 /// the original, HIR-based type-check succeeded. So if any errors
111 /// occur here, we will get a `bug!` reported.
115 /// - `infcx` -- inference context to use
116 /// - `param_env` -- parameter environment to use for trait solving
117 /// - `body` -- MIR body to type-check
118 /// - `promoted` -- map of promoted constants within `body`
119 /// - `universal_regions` -- the universal regions from `body`s function signature
120 /// - `location_table` -- MIR location map of `body`
121 /// - `borrow_set` -- information about borrows occurring in `body`
122 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
123 /// - `flow_inits` -- results of a maybe-init dataflow analysis
124 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
125 /// - `elements` -- MIR region map
126 pub(crate) fn type_check<'mir, 'tcx>(
127 infcx: &InferCtxt<'tcx>,
128 param_env: ty::ParamEnv<'tcx>,
130 promoted: &IndexVec<Promoted, Body<'tcx>>,
131 universal_regions: &Rc<UniversalRegions<'tcx>>,
132 location_table: &LocationTable,
133 borrow_set: &BorrowSet<'tcx>,
134 all_facts: &mut Option<AllFacts>,
135 flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
136 move_data: &MoveData<'tcx>,
137 elements: &Rc<RegionValueElements>,
138 upvars: &[Upvar<'tcx>],
140 ) -> MirTypeckResults<'tcx> {
141 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
142 let mut constraints = MirTypeckRegionConstraints {
143 placeholder_indices: PlaceholderIndices::default(),
144 placeholder_index_to_region: IndexVec::default(),
145 liveness_constraints: LivenessValues::new(elements.clone()),
146 outlives_constraints: OutlivesConstraintSet::default(),
147 member_constraints: MemberConstraintSet::default(),
148 type_tests: Vec::default(),
149 universe_causes: FxHashMap::default(),
153 universal_region_relations,
155 normalized_inputs_and_output,
156 } = free_region_relations::create(
159 implicit_region_bound,
164 debug!(?normalized_inputs_and_output);
166 for u in ty::UniverseIndex::ROOT..=infcx.universe() {
167 constraints.universe_causes.insert(u, UniverseInfo::other());
170 let mut borrowck_context = BorrowCheckContext {
175 constraints: &mut constraints,
179 let mut checker = TypeChecker::new(
184 implicit_region_bound,
185 &mut borrowck_context,
188 let errors_reported = {
189 let mut verifier = TypeVerifier::new(&mut checker, promoted);
190 verifier.visit_body(&body);
191 verifier.errors_reported
194 if !errors_reported {
195 // if verifier failed, don't do further checks to avoid ICEs
196 checker.typeck_mir(body);
199 checker.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
210 translate_outlives_facts(&mut checker);
211 let opaque_type_values = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
213 let opaque_type_values = opaque_type_values
215 .map(|(opaque_type_key, decl)| {
218 Locations::All(body.span),
219 ConstraintCategory::OpaqueType,
222 infcx.register_member_constraints(
226 decl.hidden_type.span,
228 Ok(InferOk { value: (), obligations: vec![] })
230 || "opaque_type_map".to_string(),
234 let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
235 trace!("finalized opaque type {:?} to {:#?}", opaque_type_key, hidden_type.ty.kind());
236 if hidden_type.has_non_region_infer() {
237 let reported = infcx.tcx.sess.delay_span_bug(
238 decl.hidden_type.span,
239 &format!("could not resolve {:#?}", hidden_type.ty.kind()),
241 hidden_type.ty = infcx.tcx.ty_error_with_guaranteed(reported);
244 (opaque_type_key, (hidden_type, decl.origin))
248 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
251 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
252 let cx = &mut typeck.borrowck_context;
253 if let Some(facts) = cx.all_facts {
254 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
255 let location_table = cx.location_table;
256 facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
257 |constraint: &OutlivesConstraint<'_>| {
258 if let Some(from_location) = constraint.locations.from_location() {
259 Either::Left(iter::once((
262 location_table.mid_index(from_location),
268 .map(move |location| (constraint.sup, constraint.sub, location)),
277 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
278 // We sometimes see MIR failures (notably predicate failures) due to
279 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
280 // to avoid reporting bugs in those cases.
281 tcx.sess.diagnostic().delay_span_bug(span, msg);
284 enum FieldAccessError {
285 OutOfRange { field_count: usize },
288 /// Verifies that MIR types are sane to not crash further checks.
290 /// The sanitize_XYZ methods here take an MIR object and compute its
291 /// type, calling `span_mirbug` and returning an error type if there
293 struct TypeVerifier<'a, 'b, 'tcx> {
294 cx: &'a mut TypeChecker<'b, 'tcx>,
295 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
297 errors_reported: bool,
300 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
301 fn visit_span(&mut self, span: Span) {
302 if !span.is_dummy() {
303 self.last_span = span;
307 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
308 self.sanitize_place(place, location, context);
311 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
312 debug!(?constant, ?location, "visit_constant");
314 self.super_constant(constant, location);
315 let ty = self.sanitize_type(constant, constant.literal.ty());
317 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
318 let live_region_vid =
319 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
323 .liveness_constraints
324 .add_element(live_region_vid, location);
327 // HACK(compiler-errors): Constants that are gathered into Body.required_consts
328 // have their locations erased...
329 let locations = if location != Location::START {
330 location.to_locations()
332 Locations::All(constant.span)
335 if let Some(annotation_index) = constant.user_ty {
336 if let Err(terr) = self.cx.relate_type_and_user_type(
337 constant.literal.ty(),
338 ty::Variance::Invariant,
339 &UserTypeProjection { base: annotation_index, projs: vec![] },
341 ConstraintCategory::Boring,
343 let annotation = &self.cx.user_type_annotations[annotation_index];
347 "bad constant user type {:?} vs {:?}: {:?}",
349 constant.literal.ty(),
354 let tcx = self.tcx();
355 let maybe_uneval = match constant.literal {
356 ConstantKind::Ty(ct) => match ct.kind() {
357 ty::ConstKind::Unevaluated(_) => {
358 bug!("should not encounter unevaluated ConstantKind::Ty here, got {:?}", ct)
362 ConstantKind::Unevaluated(uv, _) => Some(uv),
366 if let Some(uv) = maybe_uneval {
367 if let Some(promoted) = uv.promoted {
368 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
369 promoted: &Body<'tcx>,
373 verifier.cx.eq_types(ty, san_ty, locations, ConstraintCategory::Boring)
378 "bad promoted type ({:?}: {:?}): {:?}",
386 if !self.errors_reported {
387 let promoted_body = &self.promoted[promoted];
388 self.sanitize_promoted(promoted_body, location);
390 let promoted_ty = promoted_body.return_ty();
391 check_err(self, promoted_body, ty, promoted_ty);
394 if let Err(terr) = self.cx.fully_perform_op(
396 ConstraintCategory::Boring,
397 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
398 constant.literal.ty(),
400 UserSubsts { substs: uv.substs, user_self_ty: None },
406 "bad constant type {:?} ({:?})",
412 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
413 let unnormalized_ty = tcx.type_of(static_def_id);
414 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
415 let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty;
417 if let Err(terr) = self.cx.eq_types(
421 ConstraintCategory::Boring,
423 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
427 if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() {
428 // const_trait_impl: use a non-const param env when checking that a FnDef type is well formed.
429 // this is because the well-formedness of the function does not need to be proved to have `const`
430 // impls for trait bounds.
431 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
432 let prev = self.cx.param_env;
433 self.cx.param_env = prev.without_const();
434 self.cx.normalize_and_prove_instantiated_predicates(
436 instantiated_predicates,
439 self.cx.param_env = prev;
444 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
445 self.super_rvalue(rvalue, location);
446 let rval_ty = rvalue.ty(self.body(), self.tcx());
447 self.sanitize_type(rvalue, rval_ty);
450 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
451 self.super_local_decl(local, local_decl);
452 self.sanitize_type(local_decl, local_decl.ty);
454 if let Some(user_ty) = &local_decl.user_ty {
455 for (user_ty, span) in user_ty.projections_and_spans() {
456 let ty = if !local_decl.is_nonref_binding() {
457 // If we have a binding of the form `let ref x: T = ..`
458 // then remove the outermost reference so we can check the
459 // type annotation for the remaining type.
460 if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
463 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
469 if let Err(terr) = self.cx.relate_type_and_user_type(
471 ty::Variance::Invariant,
473 Locations::All(*span),
474 ConstraintCategory::TypeAnnotation,
479 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
490 fn visit_body(&mut self, body: &Body<'tcx>) {
491 self.sanitize_type(&"return type", body.return_ty());
492 for local_decl in &body.local_decls {
493 self.sanitize_type(local_decl, local_decl.ty);
495 if self.errors_reported {
498 self.super_body(body);
502 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
504 cx: &'a mut TypeChecker<'b, 'tcx>,
505 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
507 TypeVerifier { promoted, last_span: cx.body.span, cx, errors_reported: false }
510 fn body(&self) -> &Body<'tcx> {
514 fn tcx(&self) -> TyCtxt<'tcx> {
518 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
519 if ty.has_escaping_bound_vars() || ty.references_error() {
520 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
526 /// Checks that the types internal to the `place` match up with
527 /// what would be expected.
532 context: PlaceContext,
534 debug!("sanitize_place: {:?}", place);
536 let mut place_ty = PlaceTy::from_ty(self.body().local_decls[place.local].ty);
538 for elem in place.projection.iter() {
539 if place_ty.variant_index.is_none() {
540 if place_ty.ty.references_error() {
541 assert!(self.errors_reported);
542 return PlaceTy::from_ty(self.tcx().ty_error());
545 place_ty = self.sanitize_projection(place_ty, elem, place, location);
548 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
549 let tcx = self.tcx();
550 let trait_ref = tcx.mk_trait_ref(
551 tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
556 // To have a `Copy` operand, the type `T` of the
557 // value must be `Copy`. Note that we prove that `T: Copy`,
558 // rather than using the `is_copy_modulo_regions`
559 // test. This is important because
560 // `is_copy_modulo_regions` ignores the resulting region
561 // obligations and assumes they pass. This can result in
562 // bounds from `Copy` impls being unsoundly ignored (e.g.,
563 // #29149). Note that we decide to use `Copy` before knowing
564 // whether the bounds fully apply: in effect, the rule is
565 // that if a value of some type could implement `Copy`, then
567 self.cx.prove_trait_ref(
569 location.to_locations(),
570 ConstraintCategory::CopyBound,
577 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
578 // Determine the constraints from the promoted MIR by running the type
579 // checker on the promoted MIR, then transfer the constraints back to
580 // the main MIR, changing the locations to the provided location.
582 let parent_body = mem::replace(&mut self.cx.body, promoted_body);
584 // Use new sets of constraints and closure bounds so that we can
585 // modify their locations.
586 let all_facts = &mut None;
587 let mut constraints = Default::default();
588 let mut liveness_constraints =
589 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
590 // Don't try to add borrow_region facts for the promoted MIR
592 let mut swap_constraints = |this: &mut Self| {
593 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
595 &mut this.cx.borrowck_context.constraints.outlives_constraints,
599 &mut this.cx.borrowck_context.constraints.liveness_constraints,
600 &mut liveness_constraints,
604 swap_constraints(self);
606 self.visit_body(&promoted_body);
608 if !self.errors_reported {
609 // if verifier failed, don't do further checks to avoid ICEs
610 self.cx.typeck_mir(promoted_body);
613 self.cx.body = parent_body;
614 // Merge the outlives constraints back in, at the given location.
615 swap_constraints(self);
617 let locations = location.to_locations();
618 for constraint in constraints.outlives().iter() {
619 let mut constraint = constraint.clone();
620 constraint.locations = locations;
621 if let ConstraintCategory::Return(_)
622 | ConstraintCategory::UseAsConst
623 | ConstraintCategory::UseAsStatic = constraint.category
625 // "Returning" from a promoted is an assignment to a
626 // temporary from the user's point of view.
627 constraint.category = ConstraintCategory::Boring;
629 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
631 for region in liveness_constraints.rows() {
632 // If the region is live at at least one location in the promoted MIR,
633 // then add a liveness constraint to the main MIR for this region
634 // at the location provided as an argument to this method
635 if liveness_constraints.get_elements(region).next().is_some() {
639 .liveness_constraints
640 .add_element(region, location);
645 fn sanitize_projection(
652 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
653 let tcx = self.tcx();
654 let base_ty = base.ty;
656 ProjectionElem::Deref => {
657 let deref_ty = base_ty.builtin_deref(true);
658 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
659 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
662 ProjectionElem::Index(i) => {
663 let index_ty = Place::from(i).ty(self.body(), tcx).ty;
664 if index_ty != tcx.types.usize {
665 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
667 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
668 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
672 ProjectionElem::ConstantIndex { .. } => {
673 // consider verifying in-bounds
674 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
675 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
678 ProjectionElem::Subslice { from, to, from_end } => {
679 PlaceTy::from_ty(match base_ty.kind() {
680 ty::Array(inner, _) => {
681 assert!(!from_end, "array subslices should not use from_end");
682 tcx.mk_array(*inner, to - from)
685 assert!(from_end, "slice subslices should use from_end");
688 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
691 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
692 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
693 if index.as_usize() >= adt_def.variants().len() {
694 PlaceTy::from_ty(span_mirbug_and_err!(
697 "cast to variant #{:?} but enum only has {:?}",
699 adt_def.variants().len()
702 PlaceTy { ty: base_ty, variant_index: Some(index) }
705 // We do not need to handle generators here, because this runs
706 // before the generator transform stage.
708 let ty = if let Some(name) = maybe_name {
709 span_mirbug_and_err!(
712 "can't downcast {:?} as {:?}",
717 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
722 ProjectionElem::Field(field, fty) => {
723 let fty = self.sanitize_type(place, fty);
724 let fty = self.cx.normalize(fty, location);
725 match self.field_ty(place, base, field, location) {
727 let ty = self.cx.normalize(ty, location);
728 if let Err(terr) = self.cx.eq_types(
731 location.to_locations(),
732 ConstraintCategory::Boring,
737 "bad field access ({:?}: {:?}): {:?}",
744 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
747 "accessed field #{} but variant only has {}",
752 PlaceTy::from_ty(fty)
754 ProjectionElem::OpaqueCast(ty) => {
755 let ty = self.sanitize_type(place, ty);
756 let ty = self.cx.normalize(ty, location);
761 location.to_locations(),
762 ConstraintCategory::TypeAnnotation,
770 fn error(&mut self) -> Ty<'tcx> {
771 self.errors_reported = true;
772 self.tcx().ty_error()
777 parent: &dyn fmt::Debug,
778 base_ty: PlaceTy<'tcx>,
781 ) -> Result<Ty<'tcx>, FieldAccessError> {
782 let tcx = self.tcx();
784 let (variant, substs) = match base_ty {
785 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
786 ty::Adt(adt_def, substs) => (adt_def.variant(variant_index), substs),
787 ty::Generator(def_id, substs, _) => {
788 let mut variants = substs.as_generator().state_tys(def_id, tcx);
789 let Some(mut variant) = variants.nth(variant_index.into()) else {
791 "variant_index of generator out of range: {:?}/{:?}",
793 substs.as_generator().state_tys(def_id, tcx).count()
796 return match variant.nth(field.index()) {
798 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
801 _ => bug!("can't have downcast of non-adt non-generator type"),
803 PlaceTy { ty, variant_index: None } => match *ty.kind() {
804 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
805 (adt_def.variant(VariantIdx::new(0)), substs)
807 ty::Closure(_, substs) => {
815 None => Err(FieldAccessError::OutOfRange {
816 field_count: substs.as_closure().upvar_tys().count(),
820 ty::Generator(_, substs, _) => {
821 // Only prefix fields (upvars and current state) are
822 // accessible without a variant index.
823 return match substs.as_generator().prefix_tys().nth(field.index()) {
825 None => Err(FieldAccessError::OutOfRange {
826 field_count: substs.as_generator().prefix_tys().count(),
831 return match tys.get(field.index()) {
833 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
837 return Ok(span_mirbug_and_err!(
840 "can't project out of {:?}",
847 if let Some(field) = variant.fields.get(field.index()) {
848 Ok(self.cx.normalize(field.ty(tcx, substs), location))
850 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
855 /// The MIR type checker. Visits the MIR and enforces all the
856 /// constraints needed for it to be valid and well-typed. Along the
857 /// way, it accrues region constraints -- these can later be used by
858 /// NLL region checking.
859 struct TypeChecker<'a, 'tcx> {
860 infcx: &'a InferCtxt<'tcx>,
861 param_env: ty::ParamEnv<'tcx>,
863 body: &'a Body<'tcx>,
864 /// User type annotations are shared between the main MIR and the MIR of
865 /// all of the promoted items.
866 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
867 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
868 implicit_region_bound: ty::Region<'tcx>,
869 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
870 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
873 struct BorrowCheckContext<'a, 'tcx> {
874 pub(crate) universal_regions: &'a UniversalRegions<'tcx>,
875 location_table: &'a LocationTable,
876 all_facts: &'a mut Option<AllFacts>,
877 borrow_set: &'a BorrowSet<'tcx>,
878 pub(crate) constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
879 upvars: &'a [Upvar<'tcx>],
882 pub(crate) struct MirTypeckResults<'tcx> {
883 pub(crate) constraints: MirTypeckRegionConstraints<'tcx>,
884 pub(crate) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
885 pub(crate) opaque_type_values:
886 VecMap<OpaqueTypeKey<'tcx>, (OpaqueHiddenType<'tcx>, OpaqueTyOrigin)>,
889 /// A collection of region constraints that must be satisfied for the
890 /// program to be considered well-typed.
891 pub(crate) struct MirTypeckRegionConstraints<'tcx> {
892 /// Maps from a `ty::Placeholder` to the corresponding
893 /// `PlaceholderIndex` bit that we will use for it.
895 /// To keep everything in sync, do not insert this set
896 /// directly. Instead, use the `placeholder_region` helper.
897 pub(crate) placeholder_indices: PlaceholderIndices,
899 /// Each time we add a placeholder to `placeholder_indices`, we
900 /// also create a corresponding "representative" region vid for
901 /// that wraps it. This vector tracks those. This way, when we
902 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
903 /// the same underlying `RegionVid`.
904 pub(crate) placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
906 /// In general, the type-checker is not responsible for enforcing
907 /// liveness constraints; this job falls to the region inferencer,
908 /// which performs a liveness analysis. However, in some limited
909 /// cases, the MIR type-checker creates temporary regions that do
910 /// not otherwise appear in the MIR -- in particular, the
911 /// late-bound regions that it instantiates at call-sites -- and
912 /// hence it must report on their liveness constraints.
913 pub(crate) liveness_constraints: LivenessValues<RegionVid>,
915 pub(crate) outlives_constraints: OutlivesConstraintSet<'tcx>,
917 pub(crate) member_constraints: MemberConstraintSet<'tcx, RegionVid>,
919 pub(crate) universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
921 pub(crate) type_tests: Vec<TypeTest<'tcx>>,
924 impl<'tcx> MirTypeckRegionConstraints<'tcx> {
925 fn placeholder_region(
927 infcx: &InferCtxt<'tcx>,
928 placeholder: ty::PlaceholderRegion,
929 ) -> ty::Region<'tcx> {
930 let placeholder_index = self.placeholder_indices.insert(placeholder);
931 match self.placeholder_index_to_region.get(placeholder_index) {
934 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
935 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
936 self.placeholder_index_to_region.push(region);
943 /// The `Locations` type summarizes *where* region constraints are
944 /// required to hold. Normally, this is at a particular point which
945 /// created the obligation, but for constraints that the user gave, we
946 /// want the constraint to hold at all points.
947 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
949 /// Indicates that a type constraint should always be true. This
950 /// is particularly important in the new borrowck analysis for
951 /// things like the type of the return slot. Consider this
954 /// ```compile_fail,E0515
955 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
957 /// return &y; // error
961 /// Here, we wind up with the signature from the return type being
962 /// something like `&'1 u32` where `'1` is a universal region. But
963 /// the type of the return slot `_0` is something like `&'2 u32`
964 /// where `'2` is an existential region variable. The type checker
965 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
966 /// older NLL analysis, we required this only at the entry point
967 /// to the function. By the nature of the constraints, this wound
968 /// up propagating to all points reachable from start (because
969 /// `'1` -- as a universal region -- is live everywhere). In the
970 /// newer analysis, though, this doesn't work: `_0` is considered
971 /// dead at the start (it has no usable value) and hence this type
972 /// equality is basically a no-op. Then, later on, when we do `_0
973 /// = &'3 y`, that region `'3` never winds up related to the
974 /// universal region `'1` and hence no error occurs. Therefore, we
975 /// use Locations::All instead, which ensures that the `'1` and
976 /// `'2` are equal everything. We also use this for other
977 /// user-given type annotations; e.g., if the user wrote `let mut
978 /// x: &'static u32 = ...`, we would ensure that all values
979 /// assigned to `x` are of `'static` lifetime.
981 /// The span points to the place the constraint arose. For example,
982 /// it points to the type in a user-given type annotation. If
983 /// there's no sensible span then it's DUMMY_SP.
986 /// An outlives constraint that only has to hold at a single location,
987 /// usually it represents a point where references flow from one spot to
988 /// another (e.g., `x = y`)
993 pub fn from_location(&self) -> Option<Location> {
995 Locations::All(_) => None,
996 Locations::Single(from_location) => Some(*from_location),
1000 /// Gets a span representing the location.
1001 pub fn span(&self, body: &Body<'_>) -> Span {
1003 Locations::All(span) => *span,
1004 Locations::Single(l) => body.source_info(*l).span,
1009 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1011 infcx: &'a InferCtxt<'tcx>,
1012 body: &'a Body<'tcx>,
1013 param_env: ty::ParamEnv<'tcx>,
1014 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1015 implicit_region_bound: ty::Region<'tcx>,
1016 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1018 let mut checker = Self {
1020 last_span: DUMMY_SP,
1022 user_type_annotations: &body.user_type_annotations,
1025 implicit_region_bound,
1027 reported_errors: Default::default(),
1029 checker.check_user_type_annotations();
1033 fn body(&self) -> &Body<'tcx> {
1037 fn unsized_feature_enabled(&self) -> bool {
1038 let features = self.tcx().features();
1039 features.unsized_locals || features.unsized_fn_params
1042 /// Equate the inferred type and the annotated type for user type annotations
1043 #[instrument(skip(self), level = "debug")]
1044 fn check_user_type_annotations(&mut self) {
1045 debug!(?self.user_type_annotations);
1046 for user_annotation in self.user_type_annotations {
1047 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1048 let inferred_ty = self.normalize(inferred_ty, Locations::All(span));
1049 let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1050 debug!(?annotation);
1052 UserType::Ty(mut ty) => {
1053 ty = self.normalize(ty, Locations::All(span));
1055 if let Err(terr) = self.eq_types(
1058 Locations::All(span),
1059 ConstraintCategory::BoringNoLocation,
1064 "bad user type ({:?} = {:?}): {:?}",
1071 self.prove_predicate(
1072 ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into())),
1073 Locations::All(span),
1074 ConstraintCategory::TypeAnnotation,
1077 UserType::TypeOf(def_id, user_substs) => {
1078 if let Err(terr) = self.fully_perform_op(
1079 Locations::All(span),
1080 ConstraintCategory::BoringNoLocation,
1081 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1090 "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}",
1094 self.tcx().type_of(def_id),
1103 #[instrument(skip(self, data), level = "debug")]
1104 fn push_region_constraints(
1106 locations: Locations,
1107 category: ConstraintCategory<'tcx>,
1108 data: &QueryRegionConstraints<'tcx>,
1110 debug!("constraints generated: {:#?}", data);
1112 constraint_conversion::ConstraintConversion::new(
1114 self.borrowck_context.universal_regions,
1115 self.region_bound_pairs,
1116 self.implicit_region_bound,
1119 locations.span(self.body),
1121 &mut self.borrowck_context.constraints,
1126 /// Try to relate `sub <: sup`
1131 locations: Locations,
1132 category: ConstraintCategory<'tcx>,
1134 // Use this order of parameters because the sup type is usually the
1135 // "expected" type in diagnostics.
1136 self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
1139 #[instrument(skip(self, category), level = "debug")]
1144 locations: Locations,
1145 category: ConstraintCategory<'tcx>,
1147 self.relate_types(expected, ty::Variance::Invariant, found, locations, category)
1150 #[instrument(skip(self), level = "debug")]
1151 fn relate_type_and_user_type(
1155 user_ty: &UserTypeProjection,
1156 locations: Locations,
1157 category: ConstraintCategory<'tcx>,
1159 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1160 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1162 let tcx = self.infcx.tcx;
1164 for proj in &user_ty.projs {
1165 let projected_ty = curr_projected_ty.projection_ty_core(
1170 let ty = this.field_ty(tcx, field);
1171 self.normalize(ty, locations)
1173 |_, _| unreachable!(),
1175 curr_projected_ty = projected_ty;
1178 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1179 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1182 let ty = curr_projected_ty.ty;
1183 self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1188 fn tcx(&self) -> TyCtxt<'tcx> {
1192 #[instrument(skip(self, body, location), level = "debug")]
1193 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1194 let tcx = self.tcx();
1195 debug!("stmt kind: {:?}", stmt.kind);
1197 StatementKind::Assign(box (ref place, ref rv)) => {
1198 // Assignments to temporaries are not "interesting";
1199 // they are not caused by the user, but rather artifacts
1200 // of lowering. Assignments to other sorts of places *are* interesting
1202 let category = match place.as_local() {
1203 Some(RETURN_PLACE) => {
1204 let defining_ty = &self.borrowck_context.universal_regions.defining_ty;
1205 if defining_ty.is_const() {
1206 if tcx.is_static(defining_ty.def_id()) {
1207 ConstraintCategory::UseAsStatic
1209 ConstraintCategory::UseAsConst
1212 ConstraintCategory::Return(ReturnConstraint::Normal)
1217 body.local_decls[l].local_info,
1218 Some(box LocalInfo::AggregateTemp)
1221 ConstraintCategory::Usage
1223 Some(l) if !body.local_decls[l].is_user_variable() => {
1224 ConstraintCategory::Boring
1226 _ => ConstraintCategory::Assignment,
1229 "assignment category: {:?} {:?}",
1231 place.as_local().map(|l| &body.local_decls[l])
1234 let place_ty = place.ty(body, tcx).ty;
1236 let place_ty = self.normalize(place_ty, location);
1237 debug!("place_ty normalized: {:?}", place_ty);
1238 let rv_ty = rv.ty(body, tcx);
1240 let rv_ty = self.normalize(rv_ty, location);
1241 debug!("normalized rv_ty: {:?}", rv_ty);
1243 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1248 "bad assignment ({:?} = {:?}): {:?}",
1255 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1256 if let Err(terr) = self.relate_type_and_user_type(
1258 ty::Variance::Invariant,
1259 &UserTypeProjection { base: annotation_index, projs: vec![] },
1260 location.to_locations(),
1261 ConstraintCategory::Boring,
1263 let annotation = &self.user_type_annotations[annotation_index];
1267 "bad user type on rvalue ({:?} = {:?}): {:?}",
1275 self.check_rvalue(body, rv, location);
1276 if !self.unsized_feature_enabled() {
1277 let trait_ref = tcx.mk_trait_ref(
1278 tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1282 self.prove_trait_ref(
1284 location.to_locations(),
1285 ConstraintCategory::SizedBound,
1289 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1290 let place_ty = place.ty(body, tcx).ty;
1291 if let Err(terr) = self.relate_type_and_user_type(
1295 Locations::All(stmt.source_info.span),
1296 ConstraintCategory::TypeAnnotation,
1298 let annotation = &self.user_type_annotations[projection.base];
1302 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1310 StatementKind::Intrinsic(box ref kind) => match kind {
1311 NonDivergingIntrinsic::Assume(op) => self.check_operand(op, location),
1312 NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
1313 stmt.source_info.span,
1314 "Unexpected NonDivergingIntrinsic::CopyNonOverlapping, should only appear after lowering_intrinsics",
1317 StatementKind::FakeRead(..)
1318 | StatementKind::StorageLive(..)
1319 | StatementKind::StorageDead(..)
1320 | StatementKind::Retag { .. }
1321 | StatementKind::Coverage(..)
1322 | StatementKind::Nop => {}
1323 StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
1324 bug!("Statement not allowed in this MIR phase")
1329 #[instrument(skip(self, body, term_location), level = "debug")]
1330 fn check_terminator(
1333 term: &Terminator<'tcx>,
1334 term_location: Location,
1336 let tcx = self.tcx();
1337 debug!("terminator kind: {:?}", term.kind);
1339 TerminatorKind::Goto { .. }
1340 | TerminatorKind::Resume
1341 | TerminatorKind::Abort
1342 | TerminatorKind::Return
1343 | TerminatorKind::GeneratorDrop
1344 | TerminatorKind::Unreachable
1345 | TerminatorKind::Drop { .. }
1346 | TerminatorKind::FalseEdge { .. }
1347 | TerminatorKind::FalseUnwind { .. }
1348 | TerminatorKind::InlineAsm { .. } => {
1349 // no checks needed for these
1352 TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1353 let place_ty = place.ty(body, tcx).ty;
1354 let rv_ty = value.ty(body, tcx);
1356 let locations = term_location.to_locations();
1358 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1363 "bad DropAndReplace ({:?} = {:?}): {:?}",
1370 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1371 self.check_operand(discr, term_location);
1373 let discr_ty = discr.ty(body, tcx);
1374 if let Err(terr) = self.sub_types(
1377 term_location.to_locations(),
1378 ConstraintCategory::Assignment,
1383 "bad SwitchInt ({:?} on {:?}): {:?}",
1389 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1390 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1392 // FIXME: check the values
1394 TerminatorKind::Call {
1402 self.check_operand(func, term_location);
1404 self.check_operand(arg, term_location);
1407 let func_ty = func.ty(body, tcx);
1408 debug!("func_ty.kind: {:?}", func_ty.kind());
1410 let sig = match func_ty.kind() {
1411 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1413 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1417 let (sig, map) = tcx.replace_late_bound_regions(sig, |br| {
1418 self.infcx.next_region_var(LateBoundRegion(
1419 term.source_info.span,
1421 LateBoundRegionConversionTime::FnCall,
1425 // IMPORTANT: We have to prove well formed for the function signature before
1426 // we normalize it, as otherwise types like `<&'a &'b () as Trait>::Assoc`
1427 // get normalized away, causing us to ignore the `'b: 'a` bound used by the function.
1429 // Normalization results in a well formed type if the input is well formed, so we
1430 // don't have to check it twice.
1432 // See #91068 for an example.
1433 self.prove_predicates(
1434 sig.inputs_and_output
1436 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1437 term_location.to_locations(),
1438 ConstraintCategory::Boring,
1440 let sig = self.normalize(sig, term_location);
1441 self.check_call_dest(body, term, &sig, *destination, target, term_location);
1443 // The ordinary liveness rules will ensure that all
1444 // regions in the type of the callee are live here. We
1445 // then further constrain the late-bound regions that
1446 // were instantiated at the call site to be live as
1447 // well. The resulting is that all the input (and
1448 // output) types in the signature must be live, since
1449 // all the inputs that fed into it were live.
1450 for &late_bound_region in map.values() {
1452 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1453 self.borrowck_context
1455 .liveness_constraints
1456 .add_element(region_vid, term_location);
1459 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1461 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1462 self.check_operand(cond, term_location);
1464 let cond_ty = cond.ty(body, tcx);
1465 if cond_ty != tcx.types.bool {
1466 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1469 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1470 if len.ty(body, tcx) != tcx.types.usize {
1471 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1473 if index.ty(body, tcx) != tcx.types.usize {
1474 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1478 TerminatorKind::Yield { ref value, .. } => {
1479 self.check_operand(value, term_location);
1481 let value_ty = value.ty(body, tcx);
1482 match body.yield_ty() {
1483 None => span_mirbug!(self, term, "yield in non-generator"),
1485 if let Err(terr) = self.sub_types(
1488 term_location.to_locations(),
1489 ConstraintCategory::Yield,
1494 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1509 term: &Terminator<'tcx>,
1510 sig: &ty::FnSig<'tcx>,
1511 destination: Place<'tcx>,
1512 target: Option<BasicBlock>,
1513 term_location: Location,
1515 let tcx = self.tcx();
1518 let dest_ty = destination.ty(body, tcx).ty;
1519 let dest_ty = self.normalize(dest_ty, term_location);
1520 let category = match destination.as_local() {
1521 Some(RETURN_PLACE) => {
1522 if let BorrowCheckContext {
1526 DefiningTy::Const(def_id, _)
1527 | DefiningTy::InlineConst(def_id, _),
1531 } = self.borrowck_context
1533 if tcx.is_static(*def_id) {
1534 ConstraintCategory::UseAsStatic
1536 ConstraintCategory::UseAsConst
1539 ConstraintCategory::Return(ReturnConstraint::Normal)
1542 Some(l) if !body.local_decls[l].is_user_variable() => {
1543 ConstraintCategory::Boring
1545 _ => ConstraintCategory::Assignment,
1548 let locations = term_location.to_locations();
1550 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1554 "call dest mismatch ({:?} <- {:?}): {:?}",
1561 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1562 // this check is done at `check_local`.
1563 if self.unsized_feature_enabled() {
1564 let span = term.source_info.span;
1565 self.ensure_place_sized(dest_ty, span);
1569 if !sig.output().is_privately_uninhabited(self.tcx(), self.param_env) {
1570 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1576 fn check_call_inputs(
1579 term: &Terminator<'tcx>,
1580 sig: &ty::FnSig<'tcx>,
1581 args: &[Operand<'tcx>],
1582 term_location: Location,
1583 from_hir_call: bool,
1585 debug!("check_call_inputs({:?}, {:?})", sig, args);
1586 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1587 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1590 let func_ty = if let TerminatorKind::Call { func, .. } = &term.kind {
1591 Some(func.ty(body, self.infcx.tcx))
1597 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1598 let op_arg_ty = op_arg.ty(body, self.tcx());
1600 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1601 let category = if from_hir_call {
1602 ConstraintCategory::CallArgument(self.infcx.tcx.erase_regions(func_ty))
1604 ConstraintCategory::Boring
1607 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
1612 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1622 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1623 let is_cleanup = block_data.is_cleanup;
1624 self.last_span = block_data.terminator().source_info.span;
1625 match block_data.terminator().kind {
1626 TerminatorKind::Goto { target } => {
1627 self.assert_iscleanup(body, block_data, target, is_cleanup)
1629 TerminatorKind::SwitchInt { ref targets, .. } => {
1630 for target in targets.all_targets() {
1631 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1634 TerminatorKind::Resume => {
1636 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1639 TerminatorKind::Abort => {
1641 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1644 TerminatorKind::Return => {
1646 span_mirbug!(self, block_data, "return on cleanup block")
1649 TerminatorKind::GeneratorDrop { .. } => {
1651 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1654 TerminatorKind::Yield { resume, drop, .. } => {
1656 span_mirbug!(self, block_data, "yield in cleanup block")
1658 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1659 if let Some(drop) = drop {
1660 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1663 TerminatorKind::Unreachable => {}
1664 TerminatorKind::Drop { target, unwind, .. }
1665 | TerminatorKind::DropAndReplace { target, unwind, .. }
1666 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1667 self.assert_iscleanup(body, block_data, target, is_cleanup);
1668 if let Some(unwind) = unwind {
1670 span_mirbug!(self, block_data, "unwind on cleanup block")
1672 self.assert_iscleanup(body, block_data, unwind, true);
1675 TerminatorKind::Call { ref target, cleanup, .. } => {
1676 if let &Some(target) = target {
1677 self.assert_iscleanup(body, block_data, target, is_cleanup);
1679 if let Some(cleanup) = cleanup {
1681 span_mirbug!(self, block_data, "cleanup on cleanup block")
1683 self.assert_iscleanup(body, block_data, cleanup, true);
1686 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1687 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1688 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1690 TerminatorKind::FalseUnwind { real_target, unwind } => {
1691 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1692 if let Some(unwind) = unwind {
1694 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1696 self.assert_iscleanup(body, block_data, unwind, true);
1699 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
1700 if let Some(target) = destination {
1701 self.assert_iscleanup(body, block_data, target, is_cleanup);
1703 if let Some(cleanup) = cleanup {
1705 span_mirbug!(self, block_data, "cleanup on cleanup block")
1707 self.assert_iscleanup(body, block_data, cleanup, true);
1713 fn assert_iscleanup(
1716 ctxt: &dyn fmt::Debug,
1720 if body[bb].is_cleanup != iscleanuppad {
1721 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1725 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1726 match body.local_kind(local) {
1727 LocalKind::ReturnPointer | LocalKind::Arg => {
1728 // return values of normal functions are required to be
1729 // sized by typeck, but return values of ADT constructors are
1730 // not because we don't include a `Self: Sized` bounds on them.
1732 // Unbound parts of arguments were never required to be Sized
1733 // - maybe we should make that a warning.
1736 LocalKind::Var | LocalKind::Temp => {}
1739 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1740 // and nullary ops are checked in `check_call_dest`.
1741 if !self.unsized_feature_enabled() {
1742 let span = local_decl.source_info.span;
1743 let ty = local_decl.ty;
1744 self.ensure_place_sized(ty, span);
1748 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1749 let tcx = self.tcx();
1751 // Erase the regions from `ty` to get a global type. The
1752 // `Sized` bound in no way depends on precise regions, so this
1753 // shouldn't affect `is_sized`.
1754 let erased_ty = tcx.erase_regions(ty);
1755 if !erased_ty.is_sized(tcx, self.param_env) {
1756 // in current MIR construction, all non-control-flow rvalue
1757 // expressions evaluate through `as_temp` or `into` a return
1758 // slot or local, so to find all unsized rvalues it is enough
1759 // to check all temps, return slots and locals.
1760 if self.reported_errors.replace((ty, span)).is_none() {
1761 // While this is located in `nll::typeck` this error is not
1762 // an NLL error, it's a required check to prevent creation
1763 // of unsized rvalues in a call expression.
1764 self.tcx().sess.emit_err(MoveUnsized { ty, span });
1769 fn aggregate_field_ty(
1771 ak: &AggregateKind<'tcx>,
1774 ) -> Result<Ty<'tcx>, FieldAccessError> {
1775 let tcx = self.tcx();
1778 AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => {
1779 let def = tcx.adt_def(adt_did);
1780 let variant = &def.variant(variant_index);
1781 let adj_field_index = active_field_index.unwrap_or(field_index);
1782 if let Some(field) = variant.fields.get(adj_field_index) {
1783 Ok(self.normalize(field.ty(tcx, substs), location))
1785 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1788 AggregateKind::Closure(_, substs) => {
1789 match substs.as_closure().upvar_tys().nth(field_index) {
1791 None => Err(FieldAccessError::OutOfRange {
1792 field_count: substs.as_closure().upvar_tys().count(),
1796 AggregateKind::Generator(_, substs, _) => {
1797 // It doesn't make sense to look at a field beyond the prefix;
1798 // these require a variant index, and are not initialized in
1799 // aggregate rvalues.
1800 match substs.as_generator().prefix_tys().nth(field_index) {
1802 None => Err(FieldAccessError::OutOfRange {
1803 field_count: substs.as_generator().prefix_tys().count(),
1807 AggregateKind::Array(ty) => Ok(ty),
1808 AggregateKind::Tuple => {
1809 unreachable!("This should have been covered in check_rvalues");
1814 fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1815 debug!(?op, ?location, "check_operand");
1817 if let Operand::Constant(constant) = op {
1818 let maybe_uneval = match constant.literal {
1819 ConstantKind::Val(..) | ConstantKind::Ty(_) => None,
1820 ConstantKind::Unevaluated(uv, _) => Some(uv),
1823 if let Some(uv) = maybe_uneval {
1824 if uv.promoted.is_none() {
1825 let tcx = self.tcx();
1826 let def_id = uv.def.def_id_for_type_of();
1827 if tcx.def_kind(def_id) == DefKind::InlineConst {
1828 let def_id = def_id.expect_local();
1830 self.prove_closure_bounds(tcx, def_id, uv.substs, location);
1831 self.normalize_and_prove_instantiated_predicates(
1834 location.to_locations(),
1842 #[instrument(skip(self, body), level = "debug")]
1843 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1844 let tcx = self.tcx();
1847 Rvalue::Aggregate(ak, ops) => {
1849 self.check_operand(op, location);
1851 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1854 Rvalue::Repeat(operand, len) => {
1855 self.check_operand(operand, location);
1857 // If the length cannot be evaluated we must assume that the length can be larger
1859 // If the length is larger than 1, the repeat expression will need to copy the
1860 // element, so we require the `Copy` trait.
1861 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1863 Operand::Copy(..) | Operand::Constant(..) => {
1864 // These are always okay: direct use of a const, or a value that can evidently be copied.
1866 Operand::Move(place) => {
1867 // Make sure that repeated elements implement `Copy`.
1868 let span = body.source_info(location).span;
1869 let ty = place.ty(body, tcx).ty;
1870 let trait_ref = tcx.mk_trait_ref(
1871 tcx.require_lang_item(LangItem::Copy, Some(span)),
1876 self.prove_trait_ref(
1878 Locations::Single(location),
1879 ConstraintCategory::CopyBound,
1886 &Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, ty) => {
1887 let trait_ref = tcx.mk_trait_ref(
1888 tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1893 self.prove_trait_ref(
1895 location.to_locations(),
1896 ConstraintCategory::SizedBound,
1900 Rvalue::ShallowInitBox(operand, ty) => {
1901 self.check_operand(operand, location);
1903 let trait_ref = tcx.mk_trait_ref(
1904 tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1909 self.prove_trait_ref(
1911 location.to_locations(),
1912 ConstraintCategory::SizedBound,
1916 Rvalue::Cast(cast_kind, op, ty) => {
1917 self.check_operand(op, location);
1920 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1921 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1923 // The type that we see in the fcx is like
1924 // `foo::<'a, 'b>`, where `foo` is the path to a
1925 // function definition. When we extract the
1926 // signature, it comes from the `fn_sig` query,
1927 // and hence may contain unnormalized results.
1928 let fn_sig = self.normalize(fn_sig, location);
1930 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1932 if let Err(terr) = self.eq_types(
1935 location.to_locations(),
1936 ConstraintCategory::Cast,
1941 "equating {:?} with {:?} yields {:?}",
1949 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
1950 let sig = match op.ty(body, tcx).kind() {
1951 ty::Closure(_, substs) => substs.as_closure().sig(),
1954 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
1956 if let Err(terr) = self.eq_types(
1959 location.to_locations(),
1960 ConstraintCategory::Cast,
1965 "equating {:?} with {:?} yields {:?}",
1973 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
1974 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1976 // The type that we see in the fcx is like
1977 // `foo::<'a, 'b>`, where `foo` is the path to a
1978 // function definition. When we extract the
1979 // signature, it comes from the `fn_sig` query,
1980 // and hence may contain unnormalized results.
1981 let fn_sig = self.normalize(fn_sig, location);
1983 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1985 if let Err(terr) = self.eq_types(
1988 location.to_locations(),
1989 ConstraintCategory::Cast,
1994 "equating {:?} with {:?} yields {:?}",
2002 CastKind::Pointer(PointerCast::Unsize) => {
2004 let trait_ref = tcx.mk_trait_ref(
2005 tcx.require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2010 self.prove_trait_ref(
2012 location.to_locations(),
2013 ConstraintCategory::Cast,
2017 CastKind::DynStar => {
2018 // get the constraints from the target type (`dyn* Clone`)
2020 // apply them to prove that the source type `Foo` implements `Clone` etc
2021 let (existential_predicates, region) = match ty.kind() {
2022 Dynamic(predicates, region, ty::DynStar) => (predicates, region),
2023 _ => panic!("Invalid dyn* cast_ty"),
2026 let self_ty = op.ty(body, tcx);
2028 self.prove_predicates(
2029 existential_predicates
2031 .map(|predicate| predicate.with_self_ty(tcx, self_ty)),
2032 location.to_locations(),
2033 ConstraintCategory::Cast,
2036 let outlives_predicate =
2037 tcx.mk_predicate(Binder::dummy(ty::PredicateKind::TypeOutlives(
2038 ty::OutlivesPredicate(self_ty, *region),
2040 self.prove_predicate(
2042 location.to_locations(),
2043 ConstraintCategory::Cast,
2047 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2048 let ty::RawPtr(ty::TypeAndMut {
2050 mutbl: hir::Mutability::Mut,
2051 }) = op.ty(body, tcx).kind() else {
2055 "unexpected base type for cast {:?}",
2060 let ty::RawPtr(ty::TypeAndMut {
2062 mutbl: hir::Mutability::Not,
2063 }) = ty.kind() else {
2067 "unexpected target type for cast {:?}",
2072 if let Err(terr) = self.sub_types(
2075 location.to_locations(),
2076 ConstraintCategory::Cast,
2081 "relating {:?} with {:?} yields {:?}",
2089 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2090 let ty_from = op.ty(body, tcx);
2092 let opt_ty_elem_mut = match ty_from.kind() {
2093 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2094 match array_ty.kind() {
2095 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2102 let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
2106 "ArrayToPointer cast from unexpected type {:?}",
2112 let (ty_to, ty_to_mut) = match ty.kind() {
2113 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2120 "ArrayToPointer cast to unexpected type {:?}",
2127 if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2131 "ArrayToPointer cast from const {:?} to mut {:?}",
2138 if let Err(terr) = self.sub_types(
2141 location.to_locations(),
2142 ConstraintCategory::Cast,
2147 "relating {:?} with {:?} yields {:?}",
2155 CastKind::PointerExposeAddress => {
2156 let ty_from = op.ty(body, tcx);
2157 let cast_ty_from = CastTy::from_ty(ty_from);
2158 let cast_ty_to = CastTy::from_ty(*ty);
2159 match (cast_ty_from, cast_ty_to) {
2160 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => (),
2165 "Invalid PointerExposeAddress cast {:?} -> {:?}",
2173 CastKind::PointerFromExposedAddress => {
2174 let ty_from = op.ty(body, tcx);
2175 let cast_ty_from = CastTy::from_ty(ty_from);
2176 let cast_ty_to = CastTy::from_ty(*ty);
2177 match (cast_ty_from, cast_ty_to) {
2178 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
2183 "Invalid PointerFromExposedAddress cast {:?} -> {:?}",
2190 CastKind::IntToInt => {
2191 let ty_from = op.ty(body, tcx);
2192 let cast_ty_from = CastTy::from_ty(ty_from);
2193 let cast_ty_to = CastTy::from_ty(*ty);
2194 match (cast_ty_from, cast_ty_to) {
2195 (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => (),
2200 "Invalid IntToInt cast {:?} -> {:?}",
2207 CastKind::IntToFloat => {
2208 let ty_from = op.ty(body, tcx);
2209 let cast_ty_from = CastTy::from_ty(ty_from);
2210 let cast_ty_to = CastTy::from_ty(*ty);
2211 match (cast_ty_from, cast_ty_to) {
2212 (Some(CastTy::Int(_)), Some(CastTy::Float)) => (),
2217 "Invalid IntToFloat cast {:?} -> {:?}",
2224 CastKind::FloatToInt => {
2225 let ty_from = op.ty(body, tcx);
2226 let cast_ty_from = CastTy::from_ty(ty_from);
2227 let cast_ty_to = CastTy::from_ty(*ty);
2228 match (cast_ty_from, cast_ty_to) {
2229 (Some(CastTy::Float), Some(CastTy::Int(_))) => (),
2234 "Invalid FloatToInt cast {:?} -> {:?}",
2241 CastKind::FloatToFloat => {
2242 let ty_from = op.ty(body, tcx);
2243 let cast_ty_from = CastTy::from_ty(ty_from);
2244 let cast_ty_to = CastTy::from_ty(*ty);
2245 match (cast_ty_from, cast_ty_to) {
2246 (Some(CastTy::Float), Some(CastTy::Float)) => (),
2251 "Invalid FloatToFloat cast {:?} -> {:?}",
2258 CastKind::FnPtrToPtr => {
2259 let ty_from = op.ty(body, tcx);
2260 let cast_ty_from = CastTy::from_ty(ty_from);
2261 let cast_ty_to = CastTy::from_ty(*ty);
2262 match (cast_ty_from, cast_ty_to) {
2263 (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
2268 "Invalid FnPtrToPtr cast {:?} -> {:?}",
2275 CastKind::PtrToPtr => {
2276 let ty_from = op.ty(body, tcx);
2277 let cast_ty_from = CastTy::from_ty(ty_from);
2278 let cast_ty_to = CastTy::from_ty(*ty);
2279 match (cast_ty_from, cast_ty_to) {
2280 (Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_))) => (),
2285 "Invalid PtrToPtr cast {:?} -> {:?}",
2295 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2296 self.add_reborrow_constraint(&body, location, *region, borrowed_place);
2300 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2303 self.check_operand(left, location);
2304 self.check_operand(right, location);
2306 let ty_left = left.ty(body, tcx);
2307 match ty_left.kind() {
2308 // Types with regions are comparable if they have a common super-type.
2309 ty::RawPtr(_) | ty::FnPtr(_) => {
2310 let ty_right = right.ty(body, tcx);
2311 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2312 kind: TypeVariableOriginKind::MiscVariable,
2313 span: body.source_info(location).span,
2318 location.to_locations(),
2319 ConstraintCategory::Boring,
2321 .unwrap_or_else(|err| {
2322 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2324 if let Err(terr) = self.sub_types(
2327 location.to_locations(),
2328 ConstraintCategory::Boring,
2333 "unexpected comparison types {:?} and {:?} yields {:?}",
2340 // For types with no regions we can just check that the
2341 // both operands have the same type.
2342 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2343 if ty_left == right.ty(body, tcx) => {}
2344 // Other types are compared by trait methods, not by
2345 // `Rvalue::BinaryOp`.
2349 "unexpected comparison types {:?} and {:?}",
2356 Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => {
2357 self.check_operand(operand, location);
2359 Rvalue::CopyForDeref(place) => {
2360 let op = &Operand::Copy(*place);
2361 self.check_operand(op, location);
2364 Rvalue::BinaryOp(_, box (left, right))
2365 | Rvalue::CheckedBinaryOp(_, box (left, right)) => {
2366 self.check_operand(left, location);
2367 self.check_operand(right, location);
2370 Rvalue::AddressOf(..)
2371 | Rvalue::ThreadLocalRef(..)
2373 | Rvalue::Discriminant(..) => {}
2377 /// If this rvalue supports a user-given type annotation, then
2378 /// extract and return it. This represents the final type of the
2379 /// rvalue and will be unified with the inferred type.
2380 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2383 | Rvalue::ThreadLocalRef(_)
2384 | Rvalue::Repeat(..)
2386 | Rvalue::AddressOf(..)
2389 | Rvalue::ShallowInitBox(..)
2390 | Rvalue::BinaryOp(..)
2391 | Rvalue::CheckedBinaryOp(..)
2392 | Rvalue::NullaryOp(..)
2393 | Rvalue::CopyForDeref(..)
2394 | Rvalue::UnaryOp(..)
2395 | Rvalue::Discriminant(..) => None,
2397 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2398 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2399 AggregateKind::Array(_) => None,
2400 AggregateKind::Tuple => None,
2401 AggregateKind::Closure(_, _) => None,
2402 AggregateKind::Generator(_, _, _) => None,
2407 fn check_aggregate_rvalue(
2410 rvalue: &Rvalue<'tcx>,
2411 aggregate_kind: &AggregateKind<'tcx>,
2412 operands: &[Operand<'tcx>],
2415 let tcx = self.tcx();
2417 self.prove_aggregate_predicates(aggregate_kind, location);
2419 if *aggregate_kind == AggregateKind::Tuple {
2420 // tuple rvalue field type is always the type of the op. Nothing to check here.
2424 for (i, operand) in operands.iter().enumerate() {
2425 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2426 Ok(field_ty) => field_ty,
2427 Err(FieldAccessError::OutOfRange { field_count }) => {
2431 "accessed field #{} but variant only has {}",
2438 let operand_ty = operand.ty(body, tcx);
2439 let operand_ty = self.normalize(operand_ty, location);
2441 if let Err(terr) = self.sub_types(
2444 location.to_locations(),
2445 ConstraintCategory::Boring,
2450 "{:?} is not a subtype of {:?}: {:?}",
2459 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2463 /// - `location`: the location `L` where the borrow expression occurs
2464 /// - `borrow_region`: the region `'a` associated with the borrow
2465 /// - `borrowed_place`: the place `P` being borrowed
2466 fn add_reborrow_constraint(
2470 borrow_region: ty::Region<'tcx>,
2471 borrowed_place: &Place<'tcx>,
2473 // These constraints are only meaningful during borrowck:
2474 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2475 self.borrowck_context;
2477 // In Polonius mode, we also push a `loan_issued_at` fact
2478 // linking the loan to the region (in some cases, though,
2479 // there is no loan associated with this borrow expression --
2480 // that occurs when we are borrowing an unsafe place, for
2482 if let Some(all_facts) = all_facts {
2483 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2484 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2485 let region_vid = borrow_region.to_region_vid();
2486 all_facts.loan_issued_at.push((
2489 location_table.mid_index(location),
2494 // If we are reborrowing the referent of another reference, we
2495 // need to add outlives relationships. In a case like `&mut
2496 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2497 // need to ensure that `'b: 'a`.
2500 "add_reborrow_constraint({:?}, {:?}, {:?})",
2501 location, borrow_region, borrowed_place
2504 let mut cursor = borrowed_place.projection.as_ref();
2505 let tcx = self.infcx.tcx;
2506 let field = path_utils::is_upvar_field_projection(
2508 &self.borrowck_context.upvars,
2509 borrowed_place.as_ref(),
2512 let category = if let Some(field) = field {
2513 ConstraintCategory::ClosureUpvar(field)
2515 ConstraintCategory::Boring
2518 while let [proj_base @ .., elem] = cursor {
2521 debug!("add_reborrow_constraint - iteration {:?}", elem);
2524 ProjectionElem::Deref => {
2525 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2527 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2528 match base_ty.kind() {
2529 ty::Ref(ref_region, _, mutbl) => {
2530 constraints.outlives_constraints.push(OutlivesConstraint {
2531 sup: ref_region.to_region_vid(),
2532 sub: borrow_region.to_region_vid(),
2533 locations: location.to_locations(),
2534 span: location.to_locations().span(body),
2536 variance_info: ty::VarianceDiagInfo::default(),
2537 from_closure: false,
2541 hir::Mutability::Not => {
2542 // Immutable reference. We don't need the base
2543 // to be valid for the entire lifetime of
2547 hir::Mutability::Mut => {
2548 // Mutable reference. We *do* need the base
2549 // to be valid, because after the base becomes
2550 // invalid, someone else can use our mutable deref.
2552 // This is in order to make the following function
2555 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2560 // As otherwise you could clone `&mut T` using the
2561 // following function:
2563 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2564 // let my_clone = unsafe_deref(&'a x);
2573 // deref of raw pointer, guaranteed to be valid
2576 ty::Adt(def, _) if def.is_box() => {
2577 // deref of `Box`, need the base to be valid - propagate
2579 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2582 ProjectionElem::Field(..)
2583 | ProjectionElem::Downcast(..)
2584 | ProjectionElem::OpaqueCast(..)
2585 | ProjectionElem::Index(..)
2586 | ProjectionElem::ConstantIndex { .. }
2587 | ProjectionElem::Subslice { .. } => {
2588 // other field access
2594 fn prove_aggregate_predicates(
2596 aggregate_kind: &AggregateKind<'tcx>,
2599 let tcx = self.tcx();
2602 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2603 aggregate_kind, location
2606 let (def_id, instantiated_predicates) = match *aggregate_kind {
2607 AggregateKind::Adt(adt_did, _, substs, _, _) => {
2608 (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, substs))
2611 // For closures, we have some **extra requirements** we
2613 // have to check. In particular, in their upvars and
2614 // signatures, closures often reference various regions
2615 // from the surrounding function -- we call those the
2616 // closure's free regions. When we borrow-check (and hence
2617 // region-check) closures, we may find that the closure
2618 // requires certain relationships between those free
2619 // regions. However, because those free regions refer to
2620 // portions of the CFG of their caller, the closure is not
2621 // in a position to verify those relationships. In that
2622 // case, the requirements get "propagated" to us, and so
2623 // we have to solve them here where we instantiate the
2626 // Despite the opacity of the previous paragraph, this is
2627 // actually relatively easy to understand in terms of the
2628 // desugaring. A closure gets desugared to a struct, and
2629 // these extra requirements are basically like where
2630 // clauses on the struct.
2631 AggregateKind::Closure(def_id, substs)
2632 | AggregateKind::Generator(def_id, substs, _) => {
2633 (def_id.to_def_id(), self.prove_closure_bounds(tcx, def_id, substs, location))
2636 AggregateKind::Array(_) | AggregateKind::Tuple => {
2637 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2641 self.normalize_and_prove_instantiated_predicates(
2643 instantiated_predicates,
2644 location.to_locations(),
2648 fn prove_closure_bounds(
2652 substs: SubstsRef<'tcx>,
2654 ) -> ty::InstantiatedPredicates<'tcx> {
2655 if let Some(ref closure_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2656 constraint_conversion::ConstraintConversion::new(
2658 self.borrowck_context.universal_regions,
2659 self.region_bound_pairs,
2660 self.implicit_region_bound,
2662 location.to_locations(),
2663 DUMMY_SP, // irrelevant; will be overrided.
2664 ConstraintCategory::Boring, // same as above.
2665 &mut self.borrowck_context.constraints,
2667 .apply_closure_requirements(
2668 &closure_requirements,
2674 // Now equate closure substs to regions inherited from `typeck_root_def_id`. Fixes #98589.
2675 let typeck_root_def_id = tcx.typeck_root_def_id(self.body.source.def_id());
2676 let typeck_root_substs = ty::InternalSubsts::identity_for_item(tcx, typeck_root_def_id);
2678 let parent_substs = match tcx.def_kind(def_id) {
2679 DefKind::Closure => substs.as_closure().parent_substs(),
2680 DefKind::Generator => substs.as_generator().parent_substs(),
2681 DefKind::InlineConst => substs.as_inline_const().parent_substs(),
2682 other => bug!("unexpected item {:?}", other),
2684 let parent_substs = tcx.mk_substs(parent_substs.iter());
2686 assert_eq!(typeck_root_substs.len(), parent_substs.len());
2687 if let Err(_) = self.eq_substs(
2690 location.to_locations(),
2691 ConstraintCategory::BoringNoLocation,
2696 "could not relate closure to parent {:?} != {:?}",
2702 tcx.predicates_of(def_id).instantiate(tcx, substs)
2705 #[instrument(skip(self, body), level = "debug")]
2706 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2707 self.last_span = body.span;
2710 for (local, local_decl) in body.local_decls.iter_enumerated() {
2711 self.check_local(&body, local, local_decl);
2714 for (block, block_data) in body.basic_blocks.iter_enumerated() {
2715 let mut location = Location { block, statement_index: 0 };
2716 for stmt in &block_data.statements {
2717 if !stmt.source_info.span.is_dummy() {
2718 self.last_span = stmt.source_info.span;
2720 self.check_stmt(body, stmt, location);
2721 location.statement_index += 1;
2724 self.check_terminator(&body, block_data.terminator(), location);
2725 self.check_iscleanup(&body, block_data);
2730 trait NormalizeLocation: fmt::Debug + Copy {
2731 fn to_locations(self) -> Locations;
2734 impl NormalizeLocation for Locations {
2735 fn to_locations(self) -> Locations {
2740 impl NormalizeLocation for Location {
2741 fn to_locations(self) -> Locations {
2742 Locations::Single(self)
2746 /// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2747 /// this is not canonicalized - it directly affects the main `InferCtxt`
2748 /// that we use during MIR borrowchecking.
2750 pub(super) struct InstantiateOpaqueType<'tcx> {
2751 pub base_universe: Option<ty::UniverseIndex>,
2752 pub region_constraints: Option<RegionConstraintData<'tcx>>,
2753 pub obligations: Vec<PredicateObligation<'tcx>>,
2756 impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2758 /// We use this type itself to store the information used
2759 /// when reporting errors. Since this is not a query, we don't
2760 /// re-run anything during error reporting - we just use the information
2761 /// we saved to help extract an error from the already-existing region
2762 /// constraints in our `InferCtxt`
2763 type ErrorInfo = InstantiateOpaqueType<'tcx>;
2765 fn fully_perform(mut self, infcx: &InferCtxt<'tcx>) -> Fallible<TypeOpOutput<'tcx, Self>> {
2766 let (mut output, region_constraints) = scrape_region_constraints(infcx, || {
2767 Ok(InferOk { value: (), obligations: self.obligations.clone() })
2769 self.region_constraints = Some(region_constraints);
2770 output.error_info = Some(self);