1 //! This pass type-checks the MIR to ensure it is not broken.
4 use std::{fmt, iter, mem};
8 use hir::OpaqueTyOrigin;
9 use rustc_data_structures::frozen::Frozen;
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_data_structures::vec_map::VecMap;
12 use rustc_errors::struct_span_err;
14 use rustc_hir::def::DefKind;
15 use rustc_hir::def_id::LocalDefId;
16 use rustc_hir::lang_items::LangItem;
17 use rustc_index::vec::{Idx, IndexVec};
18 use rustc_infer::infer::canonical::QueryRegionConstraints;
19 use rustc_infer::infer::outlives::env::RegionBoundPairs;
20 use rustc_infer::infer::region_constraints::RegionConstraintData;
21 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
22 use rustc_infer::infer::{
23 InferCtxt, InferOk, LateBoundRegionConversionTime, NllRegionVariableOrigin,
25 use rustc_middle::mir::tcx::PlaceTy;
26 use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
27 use rustc_middle::mir::AssertKind;
28 use rustc_middle::mir::*;
29 use rustc_middle::ty::adjustment::PointerCast;
30 use rustc_middle::ty::cast::CastTy;
31 use rustc_middle::ty::fold::TypeFoldable;
32 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef, UserSubsts};
33 use rustc_middle::ty::{
34 self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, OpaqueHiddenType,
35 OpaqueTypeKey, RegionVid, ToPredicate, Ty, TyCtxt, UserType, UserTypeAnnotationIndex,
37 use rustc_span::def_id::CRATE_DEF_ID;
38 use rustc_span::{Span, DUMMY_SP};
39 use rustc_target::abi::VariantIdx;
40 use rustc_trait_selection::infer::InferCtxtExt as _;
41 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
42 use rustc_trait_selection::traits::query::type_op;
43 use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
44 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
45 use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
46 use rustc_trait_selection::traits::query::Fallible;
47 use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligation};
49 use rustc_const_eval::transform::{
50 check_consts::ConstCx, promote_consts::is_const_fn_in_array_repeat_expression,
52 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
53 use rustc_mir_dataflow::move_paths::MoveData;
54 use rustc_mir_dataflow::ResultsCursor;
57 borrow_set::BorrowSet,
58 constraints::{OutlivesConstraint, OutlivesConstraintSet},
59 diagnostics::UniverseInfo,
61 location::LocationTable,
62 member_constraints::MemberConstraintSet,
65 region_infer::values::{
66 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
68 region_infer::{ClosureRegionRequirementsExt, TypeTest},
69 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
70 universal_regions::{DefiningTy, UniversalRegions},
74 macro_rules! span_mirbug {
75 ($context:expr, $elem:expr, $($message:tt)*) => ({
76 $crate::type_check::mirbug(
80 "broken MIR in {:?} ({:?}): {}",
81 $context.body().source.def_id(),
83 format_args!($($message)*),
89 macro_rules! span_mirbug_and_err {
90 ($context:expr, $elem:expr, $($message:tt)*) => ({
92 span_mirbug!($context, $elem, $($message)*);
99 mod constraint_conversion;
100 pub mod free_region_relations;
105 /// Type checks the given `mir` in the context of the inference
106 /// context `infcx`. Returns any region constraints that have yet to
107 /// be proven. This result includes liveness constraints that
108 /// ensure that regions appearing in the types of all local variables
109 /// are live at all points where that local variable may later be
112 /// This phase of type-check ought to be infallible -- this is because
113 /// the original, HIR-based type-check succeeded. So if any errors
114 /// occur here, we will get a `bug!` reported.
118 /// - `infcx` -- inference context to use
119 /// - `param_env` -- parameter environment to use for trait solving
120 /// - `body` -- MIR body to type-check
121 /// - `promoted` -- map of promoted constants within `body`
122 /// - `universal_regions` -- the universal regions from `body`s function signature
123 /// - `location_table` -- MIR location map of `body`
124 /// - `borrow_set` -- information about borrows occurring in `body`
125 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
126 /// - `flow_inits` -- results of a maybe-init dataflow analysis
127 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
128 /// - `elements` -- MIR region map
129 pub(crate) fn type_check<'mir, 'tcx>(
130 infcx: &InferCtxt<'_, 'tcx>,
131 param_env: ty::ParamEnv<'tcx>,
133 promoted: &IndexVec<Promoted, Body<'tcx>>,
134 universal_regions: &Rc<UniversalRegions<'tcx>>,
135 location_table: &LocationTable,
136 borrow_set: &BorrowSet<'tcx>,
137 all_facts: &mut Option<AllFacts>,
138 flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
139 move_data: &MoveData<'tcx>,
140 elements: &Rc<RegionValueElements>,
141 upvars: &[Upvar<'tcx>],
143 ) -> MirTypeckResults<'tcx> {
144 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
145 let mut universe_causes = FxHashMap::default();
146 universe_causes.insert(ty::UniverseIndex::from_u32(0), UniverseInfo::other());
147 let mut constraints = MirTypeckRegionConstraints {
148 placeholder_indices: PlaceholderIndices::default(),
149 placeholder_index_to_region: IndexVec::default(),
150 liveness_constraints: LivenessValues::new(elements.clone()),
151 outlives_constraints: OutlivesConstraintSet::default(),
152 member_constraints: MemberConstraintSet::default(),
153 closure_bounds_mapping: Default::default(),
154 type_tests: Vec::default(),
159 universal_region_relations,
161 normalized_inputs_and_output,
162 } = free_region_relations::create(
165 Some(implicit_region_bound),
170 for u in ty::UniverseIndex::ROOT..infcx.universe() {
171 let info = UniverseInfo::other();
172 constraints.universe_causes.insert(u, info);
175 let mut borrowck_context = BorrowCheckContext {
180 constraints: &mut constraints,
184 let opaque_type_values = type_check_internal(
190 implicit_region_bound,
191 &mut borrowck_context,
193 cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
204 translate_outlives_facts(&mut cx);
205 let opaque_type_values =
206 infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
210 .map(|(opaque_type_key, decl)| {
212 Locations::All(body.span),
213 ConstraintCategory::OpaqueType,
216 infcx.register_member_constraints(
220 decl.hidden_type.span,
222 Ok(InferOk { value: (), obligations: vec![] })
224 || "opaque_type_map".to_string(),
228 let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
230 "finalized opaque type {:?} to {:#?}",
232 hidden_type.ty.kind()
234 if hidden_type.has_infer_types_or_consts() {
235 infcx.tcx.sess.delay_span_bug(
236 decl.hidden_type.span,
237 &format!("could not resolve {:#?}", hidden_type.ty.kind()),
239 hidden_type.ty = infcx.tcx.ty_error();
242 (opaque_type_key, (hidden_type, decl.origin))
248 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
252 skip(infcx, body, promoted, region_bound_pairs, borrowck_context, extra),
255 fn type_check_internal<'a, 'tcx, R>(
256 infcx: &'a InferCtxt<'a, 'tcx>,
257 param_env: ty::ParamEnv<'tcx>,
258 body: &'a Body<'tcx>,
259 promoted: &'a IndexVec<Promoted, Body<'tcx>>,
260 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
261 implicit_region_bound: ty::Region<'tcx>,
262 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
263 extra: impl FnOnce(TypeChecker<'a, 'tcx>) -> R,
265 let mut checker = TypeChecker::new(
270 implicit_region_bound,
273 let errors_reported = {
274 let mut verifier = TypeVerifier::new(&mut checker, promoted);
275 verifier.visit_body(&body);
276 verifier.errors_reported
279 if !errors_reported {
280 // if verifier failed, don't do further checks to avoid ICEs
281 checker.typeck_mir(body);
287 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
288 let cx = &mut typeck.borrowck_context;
289 if let Some(facts) = cx.all_facts {
290 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
291 let location_table = cx.location_table;
292 facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
293 |constraint: &OutlivesConstraint<'_>| {
294 if let Some(from_location) = constraint.locations.from_location() {
295 Either::Left(iter::once((
298 location_table.mid_index(from_location),
304 .map(move |location| (constraint.sup, constraint.sub, location)),
313 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
314 // We sometimes see MIR failures (notably predicate failures) due to
315 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
316 // to avoid reporting bugs in those cases.
317 tcx.sess.diagnostic().delay_span_bug(span, msg);
320 enum FieldAccessError {
321 OutOfRange { field_count: usize },
324 /// Verifies that MIR types are sane to not crash further checks.
326 /// The sanitize_XYZ methods here take an MIR object and compute its
327 /// type, calling `span_mirbug` and returning an error type if there
329 struct TypeVerifier<'a, 'b, 'tcx> {
330 cx: &'a mut TypeChecker<'b, 'tcx>,
331 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
333 errors_reported: bool,
336 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
337 fn visit_span(&mut self, span: &Span) {
338 if !span.is_dummy() {
339 self.last_span = *span;
343 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
344 self.sanitize_place(place, location, context);
347 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
348 self.super_constant(constant, location);
349 let ty = self.sanitize_type(constant, constant.literal.ty());
351 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
352 let live_region_vid =
353 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
357 .liveness_constraints
358 .add_element(live_region_vid, location);
361 if let Some(annotation_index) = constant.user_ty {
362 if let Err(terr) = self.cx.relate_type_and_user_type(
363 constant.literal.ty(),
364 ty::Variance::Invariant,
365 &UserTypeProjection { base: annotation_index, projs: vec![] },
366 location.to_locations(),
367 ConstraintCategory::Boring,
369 let annotation = &self.cx.user_type_annotations[annotation_index];
373 "bad constant user type {:?} vs {:?}: {:?}",
375 constant.literal.ty(),
380 let tcx = self.tcx();
381 let maybe_uneval = match constant.literal {
382 ConstantKind::Ty(ct) => match ct.val() {
383 ty::ConstKind::Unevaluated(uv) => Some(uv),
388 if let Some(uv) = maybe_uneval {
389 if let Some(promoted) = uv.promoted {
390 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
391 promoted: &Body<'tcx>,
394 if let Err(terr) = verifier.cx.eq_types(
397 location.to_locations(),
398 ConstraintCategory::Boring,
403 "bad promoted type ({:?}: {:?}): {:?}",
411 if !self.errors_reported {
412 let promoted_body = &self.promoted[promoted];
413 self.sanitize_promoted(promoted_body, location);
415 let promoted_ty = promoted_body.return_ty();
416 check_err(self, promoted_body, ty, promoted_ty);
419 if let Err(terr) = self.cx.fully_perform_op(
420 location.to_locations(),
421 ConstraintCategory::Boring,
422 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
423 constant.literal.ty(),
425 UserSubsts { substs: uv.substs, user_self_ty: None },
431 "bad constant type {:?} ({:?})",
437 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
438 let unnormalized_ty = tcx.type_of(static_def_id);
439 let locations = location.to_locations();
440 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
441 let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty;
443 if let Err(terr) = self.cx.eq_types(
447 ConstraintCategory::Boring,
449 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
453 if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() {
454 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
455 self.cx.normalize_and_prove_instantiated_predicates(
457 instantiated_predicates,
458 location.to_locations(),
464 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
465 self.super_rvalue(rvalue, location);
466 let rval_ty = rvalue.ty(self.body(), self.tcx());
467 self.sanitize_type(rvalue, rval_ty);
470 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
471 self.super_local_decl(local, local_decl);
472 self.sanitize_type(local_decl, local_decl.ty);
474 if let Some(user_ty) = &local_decl.user_ty {
475 for (user_ty, span) in user_ty.projections_and_spans() {
476 let ty = if !local_decl.is_nonref_binding() {
477 // If we have a binding of the form `let ref x: T = ..`
478 // then remove the outermost reference so we can check the
479 // type annotation for the remaining type.
480 if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
483 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
489 if let Err(terr) = self.cx.relate_type_and_user_type(
491 ty::Variance::Invariant,
493 Locations::All(*span),
494 ConstraintCategory::TypeAnnotation,
499 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
510 fn visit_body(&mut self, body: &Body<'tcx>) {
511 self.sanitize_type(&"return type", body.return_ty());
512 for local_decl in &body.local_decls {
513 self.sanitize_type(local_decl, local_decl.ty);
515 if self.errors_reported {
518 self.super_body(body);
522 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
524 cx: &'a mut TypeChecker<'b, 'tcx>,
525 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
527 TypeVerifier { promoted, last_span: cx.body.span, cx, errors_reported: false }
530 fn body(&self) -> &Body<'tcx> {
534 fn tcx(&self) -> TyCtxt<'tcx> {
538 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
539 if ty.has_escaping_bound_vars() || ty.references_error() {
540 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
546 /// Checks that the types internal to the `place` match up with
547 /// what would be expected.
552 context: PlaceContext,
554 debug!("sanitize_place: {:?}", place);
556 let mut place_ty = PlaceTy::from_ty(self.body().local_decls[place.local].ty);
558 for elem in place.projection.iter() {
559 if place_ty.variant_index.is_none() {
560 if place_ty.ty.references_error() {
561 assert!(self.errors_reported);
562 return PlaceTy::from_ty(self.tcx().ty_error());
565 place_ty = self.sanitize_projection(place_ty, elem, place, location);
568 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
569 let tcx = self.tcx();
570 let trait_ref = ty::TraitRef {
571 def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
572 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
575 // To have a `Copy` operand, the type `T` of the
576 // value must be `Copy`. Note that we prove that `T: Copy`,
577 // rather than using the `is_copy_modulo_regions`
578 // test. This is important because
579 // `is_copy_modulo_regions` ignores the resulting region
580 // obligations and assumes they pass. This can result in
581 // bounds from `Copy` impls being unsoundly ignored (e.g.,
582 // #29149). Note that we decide to use `Copy` before knowing
583 // whether the bounds fully apply: in effect, the rule is
584 // that if a value of some type could implement `Copy`, then
586 self.cx.prove_trait_ref(
588 location.to_locations(),
589 ConstraintCategory::CopyBound,
596 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
597 // Determine the constraints from the promoted MIR by running the type
598 // checker on the promoted MIR, then transfer the constraints back to
599 // the main MIR, changing the locations to the provided location.
601 let parent_body = mem::replace(&mut self.cx.body, promoted_body);
603 // Use new sets of constraints and closure bounds so that we can
604 // modify their locations.
605 let all_facts = &mut None;
606 let mut constraints = Default::default();
607 let mut closure_bounds = Default::default();
608 let mut liveness_constraints =
609 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
610 // Don't try to add borrow_region facts for the promoted MIR
612 let mut swap_constraints = |this: &mut Self| {
613 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
615 &mut this.cx.borrowck_context.constraints.outlives_constraints,
619 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
623 &mut this.cx.borrowck_context.constraints.liveness_constraints,
624 &mut liveness_constraints,
628 swap_constraints(self);
630 self.visit_body(&promoted_body);
632 if !self.errors_reported {
633 // if verifier failed, don't do further checks to avoid ICEs
634 self.cx.typeck_mir(promoted_body);
637 self.cx.body = parent_body;
638 // Merge the outlives constraints back in, at the given location.
639 swap_constraints(self);
641 let locations = location.to_locations();
642 for constraint in constraints.outlives().iter() {
643 let mut constraint = constraint.clone();
644 constraint.locations = locations;
645 if let ConstraintCategory::Return(_)
646 | ConstraintCategory::UseAsConst
647 | ConstraintCategory::UseAsStatic = constraint.category
649 // "Returning" from a promoted is an assignment to a
650 // temporary from the user's point of view.
651 constraint.category = ConstraintCategory::Boring;
653 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
655 for region in liveness_constraints.rows() {
656 // If the region is live at at least one location in the promoted MIR,
657 // then add a liveness constraint to the main MIR for this region
658 // at the location provided as an argument to this method
659 if liveness_constraints.get_elements(region).next().is_some() {
663 .liveness_constraints
664 .add_element(region, location);
668 if !closure_bounds.is_empty() {
669 let combined_bounds_mapping =
670 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
675 .closure_bounds_mapping
676 .insert(location, combined_bounds_mapping);
677 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
681 fn sanitize_projection(
688 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
689 let tcx = self.tcx();
690 let base_ty = base.ty;
692 ProjectionElem::Deref => {
693 let deref_ty = base_ty.builtin_deref(true);
694 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
695 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
698 ProjectionElem::Index(i) => {
699 let index_ty = Place::from(i).ty(self.body(), tcx).ty;
700 if index_ty != tcx.types.usize {
701 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
703 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
704 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
708 ProjectionElem::ConstantIndex { .. } => {
709 // consider verifying in-bounds
710 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
711 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
714 ProjectionElem::Subslice { from, to, from_end } => {
715 PlaceTy::from_ty(match base_ty.kind() {
716 ty::Array(inner, _) => {
717 assert!(!from_end, "array subslices should not use from_end");
718 tcx.mk_array(*inner, to - from)
721 assert!(from_end, "slice subslices should use from_end");
724 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
727 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
728 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
729 if index.as_usize() >= adt_def.variants().len() {
730 PlaceTy::from_ty(span_mirbug_and_err!(
733 "cast to variant #{:?} but enum only has {:?}",
735 adt_def.variants().len()
738 PlaceTy { ty: base_ty, variant_index: Some(index) }
741 // We do not need to handle generators here, because this runs
742 // before the generator transform stage.
744 let ty = if let Some(name) = maybe_name {
745 span_mirbug_and_err!(
748 "can't downcast {:?} as {:?}",
753 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
758 ProjectionElem::Field(field, fty) => {
759 let fty = self.sanitize_type(place, fty);
760 let fty = self.cx.normalize(fty, location);
761 match self.field_ty(place, base, field, location) {
763 let ty = self.cx.normalize(ty, location);
764 if let Err(terr) = self.cx.eq_types(
767 location.to_locations(),
768 ConstraintCategory::Boring,
773 "bad field access ({:?}: {:?}): {:?}",
780 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
783 "accessed field #{} but variant only has {}",
788 PlaceTy::from_ty(fty)
793 fn error(&mut self) -> Ty<'tcx> {
794 self.errors_reported = true;
795 self.tcx().ty_error()
800 parent: &dyn fmt::Debug,
801 base_ty: PlaceTy<'tcx>,
804 ) -> Result<Ty<'tcx>, FieldAccessError> {
805 let tcx = self.tcx();
807 let (variant, substs) = match base_ty {
808 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
809 ty::Adt(adt_def, substs) => (adt_def.variant(variant_index), substs),
810 ty::Generator(def_id, substs, _) => {
811 let mut variants = substs.as_generator().state_tys(def_id, tcx);
812 let Some(mut variant) = variants.nth(variant_index.into()) else {
814 "variant_index of generator out of range: {:?}/{:?}",
816 substs.as_generator().state_tys(def_id, tcx).count()
819 return match variant.nth(field.index()) {
821 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
824 _ => bug!("can't have downcast of non-adt non-generator type"),
826 PlaceTy { ty, variant_index: None } => match *ty.kind() {
827 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
828 (adt_def.variant(VariantIdx::new(0)), substs)
830 ty::Closure(_, substs) => {
838 None => Err(FieldAccessError::OutOfRange {
839 field_count: substs.as_closure().upvar_tys().count(),
843 ty::Generator(_, substs, _) => {
844 // Only prefix fields (upvars and current state) are
845 // accessible without a variant index.
846 return match substs.as_generator().prefix_tys().nth(field.index()) {
848 None => Err(FieldAccessError::OutOfRange {
849 field_count: substs.as_generator().prefix_tys().count(),
854 return match tys.get(field.index()) {
856 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
860 return Ok(span_mirbug_and_err!(
863 "can't project out of {:?}",
870 if let Some(field) = variant.fields.get(field.index()) {
871 Ok(self.cx.normalize(field.ty(tcx, substs), location))
873 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
878 /// The MIR type checker. Visits the MIR and enforces all the
879 /// constraints needed for it to be valid and well-typed. Along the
880 /// way, it accrues region constraints -- these can later be used by
881 /// NLL region checking.
882 struct TypeChecker<'a, 'tcx> {
883 infcx: &'a InferCtxt<'a, 'tcx>,
884 param_env: ty::ParamEnv<'tcx>,
886 body: &'a Body<'tcx>,
887 /// User type annotations are shared between the main MIR and the MIR of
888 /// all of the promoted items.
889 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
890 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
891 implicit_region_bound: ty::Region<'tcx>,
892 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
893 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
896 struct BorrowCheckContext<'a, 'tcx> {
897 pub(crate) universal_regions: &'a UniversalRegions<'tcx>,
898 location_table: &'a LocationTable,
899 all_facts: &'a mut Option<AllFacts>,
900 borrow_set: &'a BorrowSet<'tcx>,
901 pub(crate) constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
902 upvars: &'a [Upvar<'tcx>],
905 crate struct MirTypeckResults<'tcx> {
906 crate constraints: MirTypeckRegionConstraints<'tcx>,
907 crate universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
908 crate opaque_type_values: VecMap<OpaqueTypeKey<'tcx>, (OpaqueHiddenType<'tcx>, OpaqueTyOrigin)>,
911 /// A collection of region constraints that must be satisfied for the
912 /// program to be considered well-typed.
913 crate struct MirTypeckRegionConstraints<'tcx> {
914 /// Maps from a `ty::Placeholder` to the corresponding
915 /// `PlaceholderIndex` bit that we will use for it.
917 /// To keep everything in sync, do not insert this set
918 /// directly. Instead, use the `placeholder_region` helper.
919 crate placeholder_indices: PlaceholderIndices,
921 /// Each time we add a placeholder to `placeholder_indices`, we
922 /// also create a corresponding "representative" region vid for
923 /// that wraps it. This vector tracks those. This way, when we
924 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
925 /// the same underlying `RegionVid`.
926 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
928 /// In general, the type-checker is not responsible for enforcing
929 /// liveness constraints; this job falls to the region inferencer,
930 /// which performs a liveness analysis. However, in some limited
931 /// cases, the MIR type-checker creates temporary regions that do
932 /// not otherwise appear in the MIR -- in particular, the
933 /// late-bound regions that it instantiates at call-sites -- and
934 /// hence it must report on their liveness constraints.
935 crate liveness_constraints: LivenessValues<RegionVid>,
937 crate outlives_constraints: OutlivesConstraintSet<'tcx>,
939 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
941 crate closure_bounds_mapping:
942 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
944 crate universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
946 crate type_tests: Vec<TypeTest<'tcx>>,
949 impl<'tcx> MirTypeckRegionConstraints<'tcx> {
950 fn placeholder_region(
952 infcx: &InferCtxt<'_, 'tcx>,
953 placeholder: ty::PlaceholderRegion,
954 ) -> ty::Region<'tcx> {
955 let placeholder_index = self.placeholder_indices.insert(placeholder);
956 match self.placeholder_index_to_region.get(placeholder_index) {
959 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
960 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
961 self.placeholder_index_to_region.push(region);
968 /// The `Locations` type summarizes *where* region constraints are
969 /// required to hold. Normally, this is at a particular point which
970 /// created the obligation, but for constraints that the user gave, we
971 /// want the constraint to hold at all points.
972 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
974 /// Indicates that a type constraint should always be true. This
975 /// is particularly important in the new borrowck analysis for
976 /// things like the type of the return slot. Consider this
980 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
982 /// return &y; // error
986 /// Here, we wind up with the signature from the return type being
987 /// something like `&'1 u32` where `'1` is a universal region. But
988 /// the type of the return slot `_0` is something like `&'2 u32`
989 /// where `'2` is an existential region variable. The type checker
990 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
991 /// older NLL analysis, we required this only at the entry point
992 /// to the function. By the nature of the constraints, this wound
993 /// up propagating to all points reachable from start (because
994 /// `'1` -- as a universal region -- is live everywhere). In the
995 /// newer analysis, though, this doesn't work: `_0` is considered
996 /// dead at the start (it has no usable value) and hence this type
997 /// equality is basically a no-op. Then, later on, when we do `_0
998 /// = &'3 y`, that region `'3` never winds up related to the
999 /// universal region `'1` and hence no error occurs. Therefore, we
1000 /// use Locations::All instead, which ensures that the `'1` and
1001 /// `'2` are equal everything. We also use this for other
1002 /// user-given type annotations; e.g., if the user wrote `let mut
1003 /// x: &'static u32 = ...`, we would ensure that all values
1004 /// assigned to `x` are of `'static` lifetime.
1006 /// The span points to the place the constraint arose. For example,
1007 /// it points to the type in a user-given type annotation. If
1008 /// there's no sensible span then it's DUMMY_SP.
1011 /// An outlives constraint that only has to hold at a single location,
1012 /// usually it represents a point where references flow from one spot to
1013 /// another (e.g., `x = y`)
1018 pub fn from_location(&self) -> Option<Location> {
1020 Locations::All(_) => None,
1021 Locations::Single(from_location) => Some(*from_location),
1025 /// Gets a span representing the location.
1026 pub fn span(&self, body: &Body<'_>) -> Span {
1028 Locations::All(span) => *span,
1029 Locations::Single(l) => body.source_info(*l).span,
1034 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1036 infcx: &'a InferCtxt<'a, 'tcx>,
1037 body: &'a Body<'tcx>,
1038 param_env: ty::ParamEnv<'tcx>,
1039 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1040 implicit_region_bound: ty::Region<'tcx>,
1041 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1043 let mut checker = Self {
1045 last_span: DUMMY_SP,
1047 user_type_annotations: &body.user_type_annotations,
1050 implicit_region_bound,
1052 reported_errors: Default::default(),
1054 checker.check_user_type_annotations();
1058 fn body(&self) -> &Body<'tcx> {
1062 fn unsized_feature_enabled(&self) -> bool {
1063 let features = self.tcx().features();
1064 features.unsized_locals || features.unsized_fn_params
1067 /// Equate the inferred type and the annotated type for user type annotations
1068 #[instrument(skip(self), level = "debug")]
1069 fn check_user_type_annotations(&mut self) {
1070 debug!(?self.user_type_annotations);
1071 for user_annotation in self.user_type_annotations {
1072 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1073 let inferred_ty = self.normalize(inferred_ty, Locations::All(span));
1074 let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1076 UserType::Ty(mut ty) => {
1077 ty = self.normalize(ty, Locations::All(span));
1079 if let Err(terr) = self.eq_types(
1082 Locations::All(span),
1083 ConstraintCategory::BoringNoLocation,
1088 "bad user type ({:?} = {:?}): {:?}",
1095 self.prove_predicate(
1096 ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into()))
1097 .to_predicate(self.tcx()),
1098 Locations::All(span),
1099 ConstraintCategory::TypeAnnotation,
1102 UserType::TypeOf(def_id, user_substs) => {
1103 if let Err(terr) = self.fully_perform_op(
1104 Locations::All(span),
1105 ConstraintCategory::BoringNoLocation,
1106 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1115 "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}",
1119 self.tcx().type_of(def_id),
1128 #[instrument(skip(self, data), level = "debug")]
1129 fn push_region_constraints(
1131 locations: Locations,
1132 category: ConstraintCategory,
1133 data: &QueryRegionConstraints<'tcx>,
1135 debug!("constraints generated: {:#?}", data);
1137 constraint_conversion::ConstraintConversion::new(
1139 self.borrowck_context.universal_regions,
1140 self.region_bound_pairs,
1141 Some(self.implicit_region_bound),
1145 &mut self.borrowck_context.constraints,
1150 /// Try to relate `sub <: sup`
1155 locations: Locations,
1156 category: ConstraintCategory,
1158 // Use this order of parameters because the sup type is usually the
1159 // "expected" type in diagnostics.
1160 self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
1163 #[instrument(skip(self, category), level = "debug")]
1168 locations: Locations,
1169 category: ConstraintCategory,
1171 self.relate_types(expected, ty::Variance::Invariant, found, locations, category)
1174 #[instrument(skip(self), level = "debug")]
1175 fn relate_type_and_user_type(
1179 user_ty: &UserTypeProjection,
1180 locations: Locations,
1181 category: ConstraintCategory,
1183 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1184 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1186 let tcx = self.infcx.tcx;
1188 for proj in &user_ty.projs {
1189 let projected_ty = curr_projected_ty.projection_ty_core(
1194 let ty = this.field_ty(tcx, field);
1195 self.normalize(ty, locations)
1198 curr_projected_ty = projected_ty;
1201 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1202 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1205 let ty = curr_projected_ty.ty;
1206 self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1211 fn tcx(&self) -> TyCtxt<'tcx> {
1215 #[instrument(skip(self, body, location), level = "debug")]
1216 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1217 let tcx = self.tcx();
1219 StatementKind::Assign(box (ref place, ref rv)) => {
1220 // Assignments to temporaries are not "interesting";
1221 // they are not caused by the user, but rather artifacts
1222 // of lowering. Assignments to other sorts of places *are* interesting
1224 let category = match place.as_local() {
1225 Some(RETURN_PLACE) => {
1226 let defining_ty = &self.borrowck_context.universal_regions.defining_ty;
1227 if defining_ty.is_const() {
1228 if tcx.is_static(defining_ty.def_id()) {
1229 ConstraintCategory::UseAsStatic
1231 ConstraintCategory::UseAsConst
1234 ConstraintCategory::Return(ReturnConstraint::Normal)
1239 body.local_decls[l].local_info,
1240 Some(box LocalInfo::AggregateTemp)
1243 ConstraintCategory::Usage
1245 Some(l) if !body.local_decls[l].is_user_variable() => {
1246 ConstraintCategory::Boring
1248 _ => ConstraintCategory::Assignment,
1251 "assignment category: {:?} {:?}",
1253 place.as_local().map(|l| &body.local_decls[l])
1256 let place_ty = place.ty(body, tcx).ty;
1257 let place_ty = self.normalize(place_ty, location);
1258 let rv_ty = rv.ty(body, tcx);
1259 let rv_ty = self.normalize(rv_ty, location);
1261 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1266 "bad assignment ({:?} = {:?}): {:?}",
1273 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1274 if let Err(terr) = self.relate_type_and_user_type(
1276 ty::Variance::Invariant,
1277 &UserTypeProjection { base: annotation_index, projs: vec![] },
1278 location.to_locations(),
1279 ConstraintCategory::Boring,
1281 let annotation = &self.user_type_annotations[annotation_index];
1285 "bad user type on rvalue ({:?} = {:?}): {:?}",
1293 self.check_rvalue(body, rv, location);
1294 if !self.unsized_feature_enabled() {
1295 let trait_ref = ty::TraitRef {
1296 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1297 substs: tcx.mk_substs_trait(place_ty, &[]),
1299 self.prove_trait_ref(
1301 location.to_locations(),
1302 ConstraintCategory::SizedBound,
1306 StatementKind::SetDiscriminant { ref place, variant_index } => {
1307 let place_type = place.ty(body, tcx).ty;
1308 let adt = match place_type.kind() {
1309 ty::Adt(adt, _) if adt.is_enum() => adt,
1312 stmt.source_info.span,
1313 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1319 if variant_index.as_usize() >= adt.variants().len() {
1321 stmt.source_info.span,
1322 "bad set discriminant ({:?} = {:?}): value of of range",
1328 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1329 let place_ty = place.ty(body, tcx).ty;
1330 if let Err(terr) = self.relate_type_and_user_type(
1334 Locations::All(stmt.source_info.span),
1335 ConstraintCategory::TypeAnnotation,
1337 let annotation = &self.user_type_annotations[projection.base];
1341 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1349 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
1352 stmt.source_info.span,
1353 "Unexpected StatementKind::CopyNonOverlapping, should only appear after lowering_intrinsics",
1355 StatementKind::FakeRead(..)
1356 | StatementKind::StorageLive(..)
1357 | StatementKind::StorageDead(..)
1358 | StatementKind::Retag { .. }
1359 | StatementKind::Coverage(..)
1360 | StatementKind::Nop => {}
1364 #[instrument(skip(self, body, term_location), level = "debug")]
1365 fn check_terminator(
1368 term: &Terminator<'tcx>,
1369 term_location: Location,
1371 let tcx = self.tcx();
1373 TerminatorKind::Goto { .. }
1374 | TerminatorKind::Resume
1375 | TerminatorKind::Abort
1376 | TerminatorKind::Return
1377 | TerminatorKind::GeneratorDrop
1378 | TerminatorKind::Unreachable
1379 | TerminatorKind::Drop { .. }
1380 | TerminatorKind::FalseEdge { .. }
1381 | TerminatorKind::FalseUnwind { .. }
1382 | TerminatorKind::InlineAsm { .. } => {
1383 // no checks needed for these
1386 TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1387 let place_ty = place.ty(body, tcx).ty;
1388 let rv_ty = value.ty(body, tcx);
1390 let locations = term_location.to_locations();
1392 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1397 "bad DropAndReplace ({:?} = {:?}): {:?}",
1404 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1405 self.check_operand(discr, term_location);
1407 let discr_ty = discr.ty(body, tcx);
1408 if let Err(terr) = self.sub_types(
1411 term_location.to_locations(),
1412 ConstraintCategory::Assignment,
1417 "bad SwitchInt ({:?} on {:?}): {:?}",
1423 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1424 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1426 // FIXME: check the values
1428 TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1429 self.check_operand(func, term_location);
1431 self.check_operand(arg, term_location);
1434 let func_ty = func.ty(body, tcx);
1435 debug!("check_terminator: call, func_ty={:?}", func_ty);
1436 let sig = match func_ty.kind() {
1437 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1439 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1443 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1444 term.source_info.span,
1445 LateBoundRegionConversionTime::FnCall,
1448 let sig = self.normalize(sig, term_location);
1449 self.check_call_dest(body, term, &sig, destination, term_location);
1451 self.prove_predicates(
1452 sig.inputs_and_output
1454 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1455 term_location.to_locations(),
1456 ConstraintCategory::Boring,
1459 // The ordinary liveness rules will ensure that all
1460 // regions in the type of the callee are live here. We
1461 // then further constrain the late-bound regions that
1462 // were instantiated at the call site to be live as
1463 // well. The resulting is that all the input (and
1464 // output) types in the signature must be live, since
1465 // all the inputs that fed into it were live.
1466 for &late_bound_region in map.values() {
1468 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1469 self.borrowck_context
1471 .liveness_constraints
1472 .add_element(region_vid, term_location);
1475 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1477 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1478 self.check_operand(cond, term_location);
1480 let cond_ty = cond.ty(body, tcx);
1481 if cond_ty != tcx.types.bool {
1482 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1485 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1486 if len.ty(body, tcx) != tcx.types.usize {
1487 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1489 if index.ty(body, tcx) != tcx.types.usize {
1490 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1494 TerminatorKind::Yield { ref value, .. } => {
1495 self.check_operand(value, term_location);
1497 let value_ty = value.ty(body, tcx);
1498 match body.yield_ty() {
1499 None => span_mirbug!(self, term, "yield in non-generator"),
1501 if let Err(terr) = self.sub_types(
1504 term_location.to_locations(),
1505 ConstraintCategory::Yield,
1510 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1525 term: &Terminator<'tcx>,
1526 sig: &ty::FnSig<'tcx>,
1527 destination: &Option<(Place<'tcx>, BasicBlock)>,
1528 term_location: Location,
1530 let tcx = self.tcx();
1531 match *destination {
1532 Some((ref dest, _target_block)) => {
1533 let dest_ty = dest.ty(body, tcx).ty;
1534 let dest_ty = self.normalize(dest_ty, term_location);
1535 let category = match dest.as_local() {
1536 Some(RETURN_PLACE) => {
1537 if let BorrowCheckContext {
1541 DefiningTy::Const(def_id, _)
1542 | DefiningTy::InlineConst(def_id, _),
1546 } = self.borrowck_context
1548 if tcx.is_static(*def_id) {
1549 ConstraintCategory::UseAsStatic
1551 ConstraintCategory::UseAsConst
1554 ConstraintCategory::Return(ReturnConstraint::Normal)
1557 Some(l) if !body.local_decls[l].is_user_variable() => {
1558 ConstraintCategory::Boring
1560 _ => ConstraintCategory::Assignment,
1563 let locations = term_location.to_locations();
1565 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1569 "call dest mismatch ({:?} <- {:?}): {:?}",
1576 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1577 // this check is done at `check_local`.
1578 if self.unsized_feature_enabled() {
1579 let span = term.source_info.span;
1580 self.ensure_place_sized(dest_ty, span);
1586 .conservative_is_privately_uninhabited(self.param_env.and(sig.output()))
1588 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1594 fn check_call_inputs(
1597 term: &Terminator<'tcx>,
1598 sig: &ty::FnSig<'tcx>,
1599 args: &[Operand<'tcx>],
1600 term_location: Location,
1601 from_hir_call: bool,
1603 debug!("check_call_inputs({:?}, {:?})", sig, args);
1604 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1605 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1607 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1608 let op_arg_ty = op_arg.ty(body, self.tcx());
1609 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1610 let category = if from_hir_call {
1611 ConstraintCategory::CallArgument
1613 ConstraintCategory::Boring
1616 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
1621 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1631 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1632 let is_cleanup = block_data.is_cleanup;
1633 self.last_span = block_data.terminator().source_info.span;
1634 match block_data.terminator().kind {
1635 TerminatorKind::Goto { target } => {
1636 self.assert_iscleanup(body, block_data, target, is_cleanup)
1638 TerminatorKind::SwitchInt { ref targets, .. } => {
1639 for target in targets.all_targets() {
1640 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1643 TerminatorKind::Resume => {
1645 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1648 TerminatorKind::Abort => {
1650 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1653 TerminatorKind::Return => {
1655 span_mirbug!(self, block_data, "return on cleanup block")
1658 TerminatorKind::GeneratorDrop { .. } => {
1660 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1663 TerminatorKind::Yield { resume, drop, .. } => {
1665 span_mirbug!(self, block_data, "yield in cleanup block")
1667 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1668 if let Some(drop) = drop {
1669 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1672 TerminatorKind::Unreachable => {}
1673 TerminatorKind::Drop { target, unwind, .. }
1674 | TerminatorKind::DropAndReplace { target, unwind, .. }
1675 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1676 self.assert_iscleanup(body, block_data, target, is_cleanup);
1677 if let Some(unwind) = unwind {
1679 span_mirbug!(self, block_data, "unwind on cleanup block")
1681 self.assert_iscleanup(body, block_data, unwind, true);
1684 TerminatorKind::Call { ref destination, cleanup, .. } => {
1685 if let &Some((_, target)) = destination {
1686 self.assert_iscleanup(body, block_data, target, is_cleanup);
1688 if let Some(cleanup) = cleanup {
1690 span_mirbug!(self, block_data, "cleanup on cleanup block")
1692 self.assert_iscleanup(body, block_data, cleanup, true);
1695 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1696 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1697 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1699 TerminatorKind::FalseUnwind { real_target, unwind } => {
1700 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1701 if let Some(unwind) = unwind {
1703 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1705 self.assert_iscleanup(body, block_data, unwind, true);
1708 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
1709 if let Some(target) = destination {
1710 self.assert_iscleanup(body, block_data, target, is_cleanup);
1712 if let Some(cleanup) = cleanup {
1714 span_mirbug!(self, block_data, "cleanup on cleanup block")
1716 self.assert_iscleanup(body, block_data, cleanup, true);
1722 fn assert_iscleanup(
1725 ctxt: &dyn fmt::Debug,
1729 if body[bb].is_cleanup != iscleanuppad {
1730 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1734 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1735 match body.local_kind(local) {
1736 LocalKind::ReturnPointer | LocalKind::Arg => {
1737 // return values of normal functions are required to be
1738 // sized by typeck, but return values of ADT constructors are
1739 // not because we don't include a `Self: Sized` bounds on them.
1741 // Unbound parts of arguments were never required to be Sized
1742 // - maybe we should make that a warning.
1745 LocalKind::Var | LocalKind::Temp => {}
1748 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1749 // and nullary ops are checked in `check_call_dest`.
1750 if !self.unsized_feature_enabled() {
1751 let span = local_decl.source_info.span;
1752 let ty = local_decl.ty;
1753 self.ensure_place_sized(ty, span);
1757 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1758 let tcx = self.tcx();
1760 // Erase the regions from `ty` to get a global type. The
1761 // `Sized` bound in no way depends on precise regions, so this
1762 // shouldn't affect `is_sized`.
1763 let erased_ty = tcx.erase_regions(ty);
1764 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1765 // in current MIR construction, all non-control-flow rvalue
1766 // expressions evaluate through `as_temp` or `into` a return
1767 // slot or local, so to find all unsized rvalues it is enough
1768 // to check all temps, return slots and locals.
1769 if self.reported_errors.replace((ty, span)).is_none() {
1770 let mut diag = struct_span_err!(
1774 "cannot move a value of type {0}: the size of {0} \
1775 cannot be statically determined",
1779 // While this is located in `nll::typeck` this error is not
1780 // an NLL error, it's a required check to prevent creation
1781 // of unsized rvalues in a call expression.
1787 fn aggregate_field_ty(
1789 ak: &AggregateKind<'tcx>,
1792 ) -> Result<Ty<'tcx>, FieldAccessError> {
1793 let tcx = self.tcx();
1796 AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => {
1797 let def = tcx.adt_def(adt_did);
1798 let variant = &def.variant(variant_index);
1799 let adj_field_index = active_field_index.unwrap_or(field_index);
1800 if let Some(field) = variant.fields.get(adj_field_index) {
1801 Ok(self.normalize(field.ty(tcx, substs), location))
1803 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1806 AggregateKind::Closure(_, substs) => {
1807 match substs.as_closure().upvar_tys().nth(field_index) {
1809 None => Err(FieldAccessError::OutOfRange {
1810 field_count: substs.as_closure().upvar_tys().count(),
1814 AggregateKind::Generator(_, substs, _) => {
1815 // It doesn't make sense to look at a field beyond the prefix;
1816 // these require a variant index, and are not initialized in
1817 // aggregate rvalues.
1818 match substs.as_generator().prefix_tys().nth(field_index) {
1820 None => Err(FieldAccessError::OutOfRange {
1821 field_count: substs.as_generator().prefix_tys().count(),
1825 AggregateKind::Array(ty) => Ok(ty),
1826 AggregateKind::Tuple => {
1827 unreachable!("This should have been covered in check_rvalues");
1832 fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1833 if let Operand::Constant(constant) = op {
1834 let maybe_uneval = match constant.literal {
1835 ConstantKind::Ty(ct) => match ct.val() {
1836 ty::ConstKind::Unevaluated(uv) => Some(uv),
1841 if let Some(uv) = maybe_uneval {
1842 if uv.promoted.is_none() {
1843 let tcx = self.tcx();
1844 let def_id = uv.def.def_id_for_type_of();
1845 if tcx.def_kind(def_id) == DefKind::InlineConst {
1846 let predicates = self.prove_closure_bounds(
1848 def_id.expect_local(),
1852 self.normalize_and_prove_instantiated_predicates(
1855 location.to_locations(),
1863 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1864 let tcx = self.tcx();
1867 Rvalue::Aggregate(ak, ops) => {
1869 self.check_operand(op, location);
1871 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1874 Rvalue::Repeat(operand, len) => {
1875 self.check_operand(operand, location);
1877 // If the length cannot be evaluated we must assume that the length can be larger
1879 // If the length is larger than 1, the repeat expression will need to copy the
1880 // element, so we require the `Copy` trait.
1881 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1883 Operand::Copy(..) | Operand::Constant(..) => {
1884 // These are always okay: direct use of a const, or a value that can evidently be copied.
1886 Operand::Move(place) => {
1887 // Make sure that repeated elements implement `Copy`.
1888 let span = body.source_info(location).span;
1889 let ty = operand.ty(body, tcx);
1890 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1891 let ccx = ConstCx::new_with_param_env(tcx, body, self.param_env);
1893 is_const_fn_in_array_repeat_expression(&ccx, &place, &body);
1895 debug!("check_rvalue: is_const_fn={:?}", is_const_fn);
1897 let def_id = body.source.def_id().expect_local();
1898 let obligation = traits::Obligation::new(
1899 ObligationCause::new(
1901 self.tcx().hir().local_def_id_to_hir_id(def_id),
1902 traits::ObligationCauseCode::RepeatElementCopy {
1907 ty::Binder::dummy(ty::TraitRef::new(
1908 self.tcx().require_lang_item(
1910 Some(self.last_span),
1912 tcx.mk_substs_trait(ty, &[]),
1915 .to_predicate(self.tcx()),
1917 self.infcx.report_selection_error(
1920 &traits::SelectionError::Unimplemented,
1929 &Rvalue::NullaryOp(_, ty) => {
1930 let trait_ref = ty::TraitRef {
1931 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1932 substs: tcx.mk_substs_trait(ty, &[]),
1935 self.prove_trait_ref(
1937 location.to_locations(),
1938 ConstraintCategory::SizedBound,
1942 Rvalue::ShallowInitBox(operand, ty) => {
1943 self.check_operand(operand, location);
1945 let trait_ref = ty::TraitRef {
1946 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1947 substs: tcx.mk_substs_trait(*ty, &[]),
1950 self.prove_trait_ref(
1952 location.to_locations(),
1953 ConstraintCategory::SizedBound,
1957 Rvalue::Cast(cast_kind, op, ty) => {
1958 self.check_operand(op, location);
1961 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1962 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1964 // The type that we see in the fcx is like
1965 // `foo::<'a, 'b>`, where `foo` is the path to a
1966 // function definition. When we extract the
1967 // signature, it comes from the `fn_sig` query,
1968 // and hence may contain unnormalized results.
1969 let fn_sig = self.normalize(fn_sig, location);
1971 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1973 if let Err(terr) = self.eq_types(
1976 location.to_locations(),
1977 ConstraintCategory::Cast,
1982 "equating {:?} with {:?} yields {:?}",
1990 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
1991 let sig = match op.ty(body, tcx).kind() {
1992 ty::Closure(_, substs) => substs.as_closure().sig(),
1995 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
1997 if let Err(terr) = self.eq_types(
2000 location.to_locations(),
2001 ConstraintCategory::Cast,
2006 "equating {:?} with {:?} yields {:?}",
2014 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2015 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2017 // The type that we see in the fcx is like
2018 // `foo::<'a, 'b>`, where `foo` is the path to a
2019 // function definition. When we extract the
2020 // signature, it comes from the `fn_sig` query,
2021 // and hence may contain unnormalized results.
2022 let fn_sig = self.normalize(fn_sig, location);
2024 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2026 if let Err(terr) = self.eq_types(
2029 location.to_locations(),
2030 ConstraintCategory::Cast,
2035 "equating {:?} with {:?} yields {:?}",
2043 CastKind::Pointer(PointerCast::Unsize) => {
2045 let trait_ref = ty::TraitRef {
2047 .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2048 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2051 self.prove_trait_ref(
2053 location.to_locations(),
2054 ConstraintCategory::Cast,
2058 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2059 let ty::RawPtr(ty::TypeAndMut {
2061 mutbl: hir::Mutability::Mut,
2062 }) = op.ty(body, tcx).kind() else {
2066 "unexpected base type for cast {:?}",
2071 let ty::RawPtr(ty::TypeAndMut {
2073 mutbl: hir::Mutability::Not,
2074 }) = ty.kind() else {
2078 "unexpected target type for cast {:?}",
2083 if let Err(terr) = self.sub_types(
2086 location.to_locations(),
2087 ConstraintCategory::Cast,
2092 "relating {:?} with {:?} yields {:?}",
2100 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2101 let ty_from = op.ty(body, tcx);
2103 let opt_ty_elem_mut = match ty_from.kind() {
2104 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2105 match array_ty.kind() {
2106 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2113 let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
2117 "ArrayToPointer cast from unexpected type {:?}",
2123 let (ty_to, ty_to_mut) = match ty.kind() {
2124 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2131 "ArrayToPointer cast to unexpected type {:?}",
2138 if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2142 "ArrayToPointer cast from const {:?} to mut {:?}",
2149 if let Err(terr) = self.sub_types(
2152 location.to_locations(),
2153 ConstraintCategory::Cast,
2158 "relating {:?} with {:?} yields {:?}",
2167 let ty_from = op.ty(body, tcx);
2168 let cast_ty_from = CastTy::from_ty(ty_from);
2169 let cast_ty_to = CastTy::from_ty(*ty);
2170 match (cast_ty_from, cast_ty_to) {
2172 | (_, None | Some(CastTy::FnPtr))
2173 | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2174 | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => {
2175 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2178 Some(CastTy::Int(_)),
2179 Some(CastTy::Int(_) | CastTy::Float | CastTy::Ptr(_)),
2181 | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float))
2182 | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_)))
2183 | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (),
2189 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2190 self.add_reborrow_constraint(&body, location, *region, borrowed_place);
2194 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2197 self.check_operand(left, location);
2198 self.check_operand(right, location);
2200 let ty_left = left.ty(body, tcx);
2201 match ty_left.kind() {
2202 // Types with regions are comparable if they have a common super-type.
2203 ty::RawPtr(_) | ty::FnPtr(_) => {
2204 let ty_right = right.ty(body, tcx);
2205 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2206 kind: TypeVariableOriginKind::MiscVariable,
2207 span: body.source_info(location).span,
2212 location.to_locations(),
2213 ConstraintCategory::Boring,
2215 .unwrap_or_else(|err| {
2216 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2218 if let Err(terr) = self.sub_types(
2221 location.to_locations(),
2222 ConstraintCategory::Boring,
2227 "unexpected comparison types {:?} and {:?} yields {:?}",
2234 // For types with no regions we can just check that the
2235 // both operands have the same type.
2236 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2237 if ty_left == right.ty(body, tcx) => {}
2238 // Other types are compared by trait methods, not by
2239 // `Rvalue::BinaryOp`.
2243 "unexpected comparison types {:?} and {:?}",
2250 Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => {
2251 self.check_operand(operand, location);
2254 Rvalue::BinaryOp(_, box (left, right))
2255 | Rvalue::CheckedBinaryOp(_, box (left, right)) => {
2256 self.check_operand(left, location);
2257 self.check_operand(right, location);
2260 Rvalue::AddressOf(..)
2261 | Rvalue::ThreadLocalRef(..)
2263 | Rvalue::Discriminant(..) => {}
2267 /// If this rvalue supports a user-given type annotation, then
2268 /// extract and return it. This represents the final type of the
2269 /// rvalue and will be unified with the inferred type.
2270 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2273 | Rvalue::ThreadLocalRef(_)
2274 | Rvalue::Repeat(..)
2276 | Rvalue::AddressOf(..)
2279 | Rvalue::ShallowInitBox(..)
2280 | Rvalue::BinaryOp(..)
2281 | Rvalue::CheckedBinaryOp(..)
2282 | Rvalue::NullaryOp(..)
2283 | Rvalue::UnaryOp(..)
2284 | Rvalue::Discriminant(..) => None,
2286 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2287 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2288 AggregateKind::Array(_) => None,
2289 AggregateKind::Tuple => None,
2290 AggregateKind::Closure(_, _) => None,
2291 AggregateKind::Generator(_, _, _) => None,
2296 fn check_aggregate_rvalue(
2299 rvalue: &Rvalue<'tcx>,
2300 aggregate_kind: &AggregateKind<'tcx>,
2301 operands: &[Operand<'tcx>],
2304 let tcx = self.tcx();
2306 self.prove_aggregate_predicates(aggregate_kind, location);
2308 if *aggregate_kind == AggregateKind::Tuple {
2309 // tuple rvalue field type is always the type of the op. Nothing to check here.
2313 for (i, operand) in operands.iter().enumerate() {
2314 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2315 Ok(field_ty) => field_ty,
2316 Err(FieldAccessError::OutOfRange { field_count }) => {
2320 "accessed field #{} but variant only has {}",
2327 let operand_ty = operand.ty(body, tcx);
2328 let operand_ty = self.normalize(operand_ty, location);
2330 if let Err(terr) = self.sub_types(
2333 location.to_locations(),
2334 ConstraintCategory::Boring,
2339 "{:?} is not a subtype of {:?}: {:?}",
2348 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2352 /// - `location`: the location `L` where the borrow expression occurs
2353 /// - `borrow_region`: the region `'a` associated with the borrow
2354 /// - `borrowed_place`: the place `P` being borrowed
2355 fn add_reborrow_constraint(
2359 borrow_region: ty::Region<'tcx>,
2360 borrowed_place: &Place<'tcx>,
2362 // These constraints are only meaningful during borrowck:
2363 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2364 self.borrowck_context;
2366 // In Polonius mode, we also push a `loan_issued_at` fact
2367 // linking the loan to the region (in some cases, though,
2368 // there is no loan associated with this borrow expression --
2369 // that occurs when we are borrowing an unsafe place, for
2371 if let Some(all_facts) = all_facts {
2372 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2373 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2374 let region_vid = borrow_region.to_region_vid();
2375 all_facts.loan_issued_at.push((
2378 location_table.mid_index(location),
2383 // If we are reborrowing the referent of another reference, we
2384 // need to add outlives relationships. In a case like `&mut
2385 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2386 // need to ensure that `'b: 'a`.
2389 "add_reborrow_constraint({:?}, {:?}, {:?})",
2390 location, borrow_region, borrowed_place
2393 let mut cursor = borrowed_place.projection.as_ref();
2394 let tcx = self.infcx.tcx;
2395 let field = path_utils::is_upvar_field_projection(
2397 &self.borrowck_context.upvars,
2398 borrowed_place.as_ref(),
2401 let category = if let Some(field) = field {
2402 ConstraintCategory::ClosureUpvar(field)
2404 ConstraintCategory::Boring
2407 while let [proj_base @ .., elem] = cursor {
2410 debug!("add_reborrow_constraint - iteration {:?}", elem);
2413 ProjectionElem::Deref => {
2414 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2416 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2417 match base_ty.kind() {
2418 ty::Ref(ref_region, _, mutbl) => {
2419 constraints.outlives_constraints.push(OutlivesConstraint {
2420 sup: ref_region.to_region_vid(),
2421 sub: borrow_region.to_region_vid(),
2422 locations: location.to_locations(),
2424 variance_info: ty::VarianceDiagInfo::default(),
2428 hir::Mutability::Not => {
2429 // Immutable reference. We don't need the base
2430 // to be valid for the entire lifetime of
2434 hir::Mutability::Mut => {
2435 // Mutable reference. We *do* need the base
2436 // to be valid, because after the base becomes
2437 // invalid, someone else can use our mutable deref.
2439 // This is in order to make the following function
2442 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2447 // As otherwise you could clone `&mut T` using the
2448 // following function:
2450 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2451 // let my_clone = unsafe_deref(&'a x);
2460 // deref of raw pointer, guaranteed to be valid
2463 ty::Adt(def, _) if def.is_box() => {
2464 // deref of `Box`, need the base to be valid - propagate
2466 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2469 ProjectionElem::Field(..)
2470 | ProjectionElem::Downcast(..)
2471 | ProjectionElem::Index(..)
2472 | ProjectionElem::ConstantIndex { .. }
2473 | ProjectionElem::Subslice { .. } => {
2474 // other field access
2480 fn prove_aggregate_predicates(
2482 aggregate_kind: &AggregateKind<'tcx>,
2485 let tcx = self.tcx();
2488 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2489 aggregate_kind, location
2492 let (def_id, instantiated_predicates) = match aggregate_kind {
2493 AggregateKind::Adt(adt_did, _, substs, _, _) => {
2494 (*adt_did, tcx.predicates_of(*adt_did).instantiate(tcx, substs))
2497 // For closures, we have some **extra requirements** we
2499 // have to check. In particular, in their upvars and
2500 // signatures, closures often reference various regions
2501 // from the surrounding function -- we call those the
2502 // closure's free regions. When we borrow-check (and hence
2503 // region-check) closures, we may find that the closure
2504 // requires certain relationships between those free
2505 // regions. However, because those free regions refer to
2506 // portions of the CFG of their caller, the closure is not
2507 // in a position to verify those relationships. In that
2508 // case, the requirements get "propagated" to us, and so
2509 // we have to solve them here where we instantiate the
2512 // Despite the opacity of the previous paragraph, this is
2513 // actually relatively easy to understand in terms of the
2514 // desugaring. A closure gets desugared to a struct, and
2515 // these extra requirements are basically like where
2516 // clauses on the struct.
2517 AggregateKind::Closure(def_id, substs)
2518 | AggregateKind::Generator(def_id, substs, _) => {
2519 (*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location))
2522 AggregateKind::Array(_) | AggregateKind::Tuple => {
2523 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2527 self.normalize_and_prove_instantiated_predicates(
2529 instantiated_predicates,
2530 location.to_locations(),
2534 fn prove_closure_bounds(
2538 substs: SubstsRef<'tcx>,
2540 ) -> ty::InstantiatedPredicates<'tcx> {
2541 if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2543 let closure_constraints = QueryRegionConstraints {
2544 outlives: closure_region_requirements.apply_requirements(
2550 // Presently, closures never propagate member
2551 // constraints to their parents -- they are enforced
2552 // locally. This is largely a non-issue as member
2553 // constraints only come from `-> impl Trait` and
2554 // friends which don't appear (thus far...) in
2556 member_constraints: vec![],
2559 let bounds_mapping = closure_constraints
2563 .filter_map(|(idx, constraint)| {
2564 let ty::OutlivesPredicate(k1, r2) =
2565 constraint.no_bound_vars().unwrap_or_else(|| {
2566 bug!("query_constraint {:?} contained bound vars", constraint,);
2570 GenericArgKind::Lifetime(r1) => {
2571 // constraint is r1: r2
2572 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2573 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2574 let outlives_requirements =
2575 &closure_region_requirements.outlives_requirements[idx];
2578 (outlives_requirements.category, outlives_requirements.blame_span),
2581 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2589 .closure_bounds_mapping
2590 .insert(location, bounds_mapping);
2591 assert!(existing.is_none(), "Multiple closures at the same location.");
2593 self.push_region_constraints(
2594 location.to_locations(),
2595 ConstraintCategory::ClosureBounds,
2596 &closure_constraints,
2600 tcx.predicates_of(def_id).instantiate(tcx, substs)
2603 #[instrument(skip(self, body), level = "debug")]
2604 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2605 self.last_span = body.span;
2608 for (local, local_decl) in body.local_decls.iter_enumerated() {
2609 self.check_local(&body, local, local_decl);
2612 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2613 let mut location = Location { block, statement_index: 0 };
2614 for stmt in &block_data.statements {
2615 if !stmt.source_info.span.is_dummy() {
2616 self.last_span = stmt.source_info.span;
2618 self.check_stmt(body, stmt, location);
2619 location.statement_index += 1;
2622 self.check_terminator(&body, block_data.terminator(), location);
2623 self.check_iscleanup(&body, block_data);
2628 trait NormalizeLocation: fmt::Debug + Copy {
2629 fn to_locations(self) -> Locations;
2632 impl NormalizeLocation for Locations {
2633 fn to_locations(self) -> Locations {
2638 impl NormalizeLocation for Location {
2639 fn to_locations(self) -> Locations {
2640 Locations::Single(self)
2644 /// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2645 /// this is not canonicalized - it directly affects the main `InferCtxt`
2646 /// that we use during MIR borrowchecking.
2648 pub(super) struct InstantiateOpaqueType<'tcx> {
2649 pub base_universe: Option<ty::UniverseIndex>,
2650 pub region_constraints: Option<RegionConstraintData<'tcx>>,
2651 pub obligations: Vec<PredicateObligation<'tcx>>,
2654 impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2656 /// We use this type itself to store the information used
2657 /// when reporting errors. Since this is not a query, we don't
2658 /// re-run anything during error reporting - we just use the information
2659 /// we saved to help extract an error from the already-existing region
2660 /// constraints in our `InferCtxt`
2661 type ErrorInfo = InstantiateOpaqueType<'tcx>;
2663 fn fully_perform(mut self, infcx: &InferCtxt<'_, 'tcx>) -> Fallible<TypeOpOutput<'tcx, Self>> {
2664 let (mut output, region_constraints) = scrape_region_constraints(infcx, || {
2665 Ok(InferOk { value: (), obligations: self.obligations.clone() })
2667 self.region_constraints = Some(region_constraints);
2668 output.error_info = Some(self);