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;
13 use rustc_hir::def::DefKind;
14 use rustc_hir::def_id::LocalDefId;
15 use rustc_hir::lang_items::LangItem;
16 use rustc_index::vec::{Idx, IndexVec};
17 use rustc_infer::infer::canonical::QueryRegionConstraints;
18 use rustc_infer::infer::outlives::env::RegionBoundPairs;
19 use rustc_infer::infer::region_constraints::RegionConstraintData;
20 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
21 use rustc_infer::infer::{
22 InferCtxt, InferOk, LateBoundRegion, LateBoundRegionConversionTime, NllRegionVariableOrigin,
24 use rustc_middle::mir::tcx::PlaceTy;
25 use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
26 use rustc_middle::mir::AssertKind;
27 use rustc_middle::mir::*;
28 use rustc_middle::ty::adjustment::PointerCast;
29 use rustc_middle::ty::cast::CastTy;
30 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef, UserSubsts};
31 use rustc_middle::ty::visit::TypeVisitable;
32 use rustc_middle::ty::{
33 self, Binder, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, Dynamic,
34 OpaqueHiddenType, OpaqueTypeKey, RegionVid, ToPredicate, Ty, TyCtxt, UserType,
35 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::traits::query::type_op;
41 use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
42 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
43 use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
44 use rustc_trait_selection::traits::query::Fallible;
45 use rustc_trait_selection::traits::PredicateObligation;
47 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
48 use rustc_mir_dataflow::move_paths::MoveData;
49 use rustc_mir_dataflow::ResultsCursor;
51 use crate::session_diagnostics::MoveUnsized;
53 borrow_set::BorrowSet,
54 constraints::{OutlivesConstraint, OutlivesConstraintSet},
55 diagnostics::UniverseInfo,
57 location::LocationTable,
58 member_constraints::MemberConstraintSet,
61 region_infer::values::{
62 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
64 region_infer::{ClosureRegionRequirementsExt, TypeTest},
65 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
66 universal_regions::{DefiningTy, UniversalRegions},
70 macro_rules! span_mirbug {
71 ($context:expr, $elem:expr, $($message:tt)*) => ({
72 $crate::type_check::mirbug(
76 "broken MIR in {:?} ({:?}): {}",
77 $context.body().source.def_id(),
79 format_args!($($message)*),
85 macro_rules! span_mirbug_and_err {
86 ($context:expr, $elem:expr, $($message:tt)*) => ({
88 span_mirbug!($context, $elem, $($message)*);
95 mod constraint_conversion;
96 pub mod free_region_relations;
98 pub(crate) mod liveness;
101 /// Type checks the given `mir` in the context of the inference
102 /// context `infcx`. Returns any region constraints that have yet to
103 /// be proven. This result includes liveness constraints that
104 /// ensure that regions appearing in the types of all local variables
105 /// are live at all points where that local variable may later be
108 /// This phase of type-check ought to be infallible -- this is because
109 /// the original, HIR-based type-check succeeded. So if any errors
110 /// occur here, we will get a `bug!` reported.
114 /// - `infcx` -- inference context to use
115 /// - `param_env` -- parameter environment to use for trait solving
116 /// - `body` -- MIR body to type-check
117 /// - `promoted` -- map of promoted constants within `body`
118 /// - `universal_regions` -- the universal regions from `body`s function signature
119 /// - `location_table` -- MIR location map of `body`
120 /// - `borrow_set` -- information about borrows occurring in `body`
121 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
122 /// - `flow_inits` -- results of a maybe-init dataflow analysis
123 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
124 /// - `elements` -- MIR region map
125 pub(crate) fn type_check<'mir, 'tcx>(
126 infcx: &InferCtxt<'tcx>,
127 param_env: ty::ParamEnv<'tcx>,
129 promoted: &IndexVec<Promoted, Body<'tcx>>,
130 universal_regions: &Rc<UniversalRegions<'tcx>>,
131 location_table: &LocationTable,
132 borrow_set: &BorrowSet<'tcx>,
133 all_facts: &mut Option<AllFacts>,
134 flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
135 move_data: &MoveData<'tcx>,
136 elements: &Rc<RegionValueElements>,
137 upvars: &[Upvar<'tcx>],
139 ) -> MirTypeckResults<'tcx> {
140 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
141 let mut constraints = MirTypeckRegionConstraints {
142 placeholder_indices: PlaceholderIndices::default(),
143 placeholder_index_to_region: IndexVec::default(),
144 liveness_constraints: LivenessValues::new(elements.clone()),
145 outlives_constraints: OutlivesConstraintSet::default(),
146 member_constraints: MemberConstraintSet::default(),
147 closure_bounds_mapping: Default::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 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();
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 = ty::TraitRef {
551 def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
552 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
555 // To have a `Copy` operand, the type `T` of the
556 // value must be `Copy`. Note that we prove that `T: Copy`,
557 // rather than using the `is_copy_modulo_regions`
558 // test. This is important because
559 // `is_copy_modulo_regions` ignores the resulting region
560 // obligations and assumes they pass. This can result in
561 // bounds from `Copy` impls being unsoundly ignored (e.g.,
562 // #29149). Note that we decide to use `Copy` before knowing
563 // whether the bounds fully apply: in effect, the rule is
564 // that if a value of some type could implement `Copy`, then
566 self.cx.prove_trait_ref(
568 location.to_locations(),
569 ConstraintCategory::CopyBound,
576 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
577 // Determine the constraints from the promoted MIR by running the type
578 // checker on the promoted MIR, then transfer the constraints back to
579 // the main MIR, changing the locations to the provided location.
581 let parent_body = mem::replace(&mut self.cx.body, promoted_body);
583 // Use new sets of constraints and closure bounds so that we can
584 // modify their locations.
585 let all_facts = &mut None;
586 let mut constraints = Default::default();
587 let mut type_tests = Default::default();
588 let mut closure_bounds = Default::default();
589 let mut liveness_constraints =
590 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
591 // Don't try to add borrow_region facts for the promoted MIR
593 let mut swap_constraints = |this: &mut Self| {
594 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
596 &mut this.cx.borrowck_context.constraints.outlives_constraints,
599 mem::swap(&mut this.cx.borrowck_context.constraints.type_tests, &mut type_tests);
601 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
605 &mut this.cx.borrowck_context.constraints.liveness_constraints,
606 &mut liveness_constraints,
610 swap_constraints(self);
612 self.visit_body(&promoted_body);
614 if !self.errors_reported {
615 // if verifier failed, don't do further checks to avoid ICEs
616 self.cx.typeck_mir(promoted_body);
619 self.cx.body = parent_body;
620 // Merge the outlives constraints back in, at the given location.
621 swap_constraints(self);
623 let locations = location.to_locations();
625 // Use location of promoted const in collected constraints
626 for type_test in type_tests.iter() {
627 let mut type_test = type_test.clone();
628 type_test.locations = locations;
629 self.cx.borrowck_context.constraints.type_tests.push(type_test)
631 for constraint in constraints.outlives().iter() {
632 let mut constraint = constraint.clone();
633 constraint.locations = locations;
634 if let ConstraintCategory::Return(_)
635 | ConstraintCategory::UseAsConst
636 | ConstraintCategory::UseAsStatic = constraint.category
638 // "Returning" from a promoted is an assignment to a
639 // temporary from the user's point of view.
640 constraint.category = ConstraintCategory::Boring;
642 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
644 for region in liveness_constraints.rows() {
645 // If the region is live at at least one location in the promoted MIR,
646 // then add a liveness constraint to the main MIR for this region
647 // at the location provided as an argument to this method
648 if liveness_constraints.get_elements(region).next().is_some() {
652 .liveness_constraints
653 .add_element(region, location);
657 if !closure_bounds.is_empty() {
658 let combined_bounds_mapping =
659 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
664 .closure_bounds_mapping
665 .insert(location, combined_bounds_mapping);
666 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
670 fn sanitize_projection(
677 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
678 let tcx = self.tcx();
679 let base_ty = base.ty;
681 ProjectionElem::Deref => {
682 let deref_ty = base_ty.builtin_deref(true);
683 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
684 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
687 ProjectionElem::Index(i) => {
688 let index_ty = Place::from(i).ty(self.body(), tcx).ty;
689 if index_ty != tcx.types.usize {
690 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
692 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
693 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
697 ProjectionElem::ConstantIndex { .. } => {
698 // consider verifying in-bounds
699 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
700 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
703 ProjectionElem::Subslice { from, to, from_end } => {
704 PlaceTy::from_ty(match base_ty.kind() {
705 ty::Array(inner, _) => {
706 assert!(!from_end, "array subslices should not use from_end");
707 tcx.mk_array(*inner, to - from)
710 assert!(from_end, "slice subslices should use from_end");
713 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
716 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
717 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
718 if index.as_usize() >= adt_def.variants().len() {
719 PlaceTy::from_ty(span_mirbug_and_err!(
722 "cast to variant #{:?} but enum only has {:?}",
724 adt_def.variants().len()
727 PlaceTy { ty: base_ty, variant_index: Some(index) }
730 // We do not need to handle generators here, because this runs
731 // before the generator transform stage.
733 let ty = if let Some(name) = maybe_name {
734 span_mirbug_and_err!(
737 "can't downcast {:?} as {:?}",
742 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
747 ProjectionElem::Field(field, fty) => {
748 let fty = self.sanitize_type(place, fty);
749 let fty = self.cx.normalize(fty, location);
750 match self.field_ty(place, base, field, location) {
752 let ty = self.cx.normalize(ty, location);
753 if let Err(terr) = self.cx.eq_types(
756 location.to_locations(),
757 ConstraintCategory::Boring,
762 "bad field access ({:?}: {:?}): {:?}",
769 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
772 "accessed field #{} but variant only has {}",
777 PlaceTy::from_ty(fty)
779 ProjectionElem::OpaqueCast(ty) => {
780 let ty = self.sanitize_type(place, ty);
781 let ty = self.cx.normalize(ty, location);
786 location.to_locations(),
787 ConstraintCategory::TypeAnnotation,
795 fn error(&mut self) -> Ty<'tcx> {
796 self.errors_reported = true;
797 self.tcx().ty_error()
802 parent: &dyn fmt::Debug,
803 base_ty: PlaceTy<'tcx>,
806 ) -> Result<Ty<'tcx>, FieldAccessError> {
807 let tcx = self.tcx();
809 let (variant, substs) = match base_ty {
810 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
811 ty::Adt(adt_def, substs) => (adt_def.variant(variant_index), substs),
812 ty::Generator(def_id, substs, _) => {
813 let mut variants = substs.as_generator().state_tys(def_id, tcx);
814 let Some(mut variant) = variants.nth(variant_index.into()) else {
816 "variant_index of generator out of range: {:?}/{:?}",
818 substs.as_generator().state_tys(def_id, tcx).count()
821 return match variant.nth(field.index()) {
823 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
826 _ => bug!("can't have downcast of non-adt non-generator type"),
828 PlaceTy { ty, variant_index: None } => match *ty.kind() {
829 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
830 (adt_def.variant(VariantIdx::new(0)), substs)
832 ty::Closure(_, substs) => {
840 None => Err(FieldAccessError::OutOfRange {
841 field_count: substs.as_closure().upvar_tys().count(),
845 ty::Generator(_, substs, _) => {
846 // Only prefix fields (upvars and current state) are
847 // accessible without a variant index.
848 return match substs.as_generator().prefix_tys().nth(field.index()) {
850 None => Err(FieldAccessError::OutOfRange {
851 field_count: substs.as_generator().prefix_tys().count(),
856 return match tys.get(field.index()) {
858 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
862 return Ok(span_mirbug_and_err!(
865 "can't project out of {:?}",
872 if let Some(field) = variant.fields.get(field.index()) {
873 Ok(self.cx.normalize(field.ty(tcx, substs), location))
875 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
880 /// The MIR type checker. Visits the MIR and enforces all the
881 /// constraints needed for it to be valid and well-typed. Along the
882 /// way, it accrues region constraints -- these can later be used by
883 /// NLL region checking.
884 struct TypeChecker<'a, 'tcx> {
885 infcx: &'a InferCtxt<'tcx>,
886 param_env: ty::ParamEnv<'tcx>,
888 body: &'a Body<'tcx>,
889 /// User type annotations are shared between the main MIR and the MIR of
890 /// all of the promoted items.
891 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
892 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
893 implicit_region_bound: ty::Region<'tcx>,
894 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
895 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
898 struct BorrowCheckContext<'a, 'tcx> {
899 pub(crate) universal_regions: &'a UniversalRegions<'tcx>,
900 location_table: &'a LocationTable,
901 all_facts: &'a mut Option<AllFacts>,
902 borrow_set: &'a BorrowSet<'tcx>,
903 pub(crate) constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
904 upvars: &'a [Upvar<'tcx>],
907 pub(crate) struct MirTypeckResults<'tcx> {
908 pub(crate) constraints: MirTypeckRegionConstraints<'tcx>,
909 pub(crate) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
910 pub(crate) opaque_type_values:
911 VecMap<OpaqueTypeKey<'tcx>, (OpaqueHiddenType<'tcx>, OpaqueTyOrigin)>,
914 /// A collection of region constraints that must be satisfied for the
915 /// program to be considered well-typed.
916 pub(crate) struct MirTypeckRegionConstraints<'tcx> {
917 /// Maps from a `ty::Placeholder` to the corresponding
918 /// `PlaceholderIndex` bit that we will use for it.
920 /// To keep everything in sync, do not insert this set
921 /// directly. Instead, use the `placeholder_region` helper.
922 pub(crate) placeholder_indices: PlaceholderIndices,
924 /// Each time we add a placeholder to `placeholder_indices`, we
925 /// also create a corresponding "representative" region vid for
926 /// that wraps it. This vector tracks those. This way, when we
927 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
928 /// the same underlying `RegionVid`.
929 pub(crate) placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
931 /// In general, the type-checker is not responsible for enforcing
932 /// liveness constraints; this job falls to the region inferencer,
933 /// which performs a liveness analysis. However, in some limited
934 /// cases, the MIR type-checker creates temporary regions that do
935 /// not otherwise appear in the MIR -- in particular, the
936 /// late-bound regions that it instantiates at call-sites -- and
937 /// hence it must report on their liveness constraints.
938 pub(crate) liveness_constraints: LivenessValues<RegionVid>,
940 pub(crate) outlives_constraints: OutlivesConstraintSet<'tcx>,
942 pub(crate) member_constraints: MemberConstraintSet<'tcx, RegionVid>,
944 pub(crate) closure_bounds_mapping:
945 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
947 pub(crate) universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
949 pub(crate) type_tests: Vec<TypeTest<'tcx>>,
952 impl<'tcx> MirTypeckRegionConstraints<'tcx> {
953 fn placeholder_region(
955 infcx: &InferCtxt<'tcx>,
956 placeholder: ty::PlaceholderRegion,
957 ) -> ty::Region<'tcx> {
958 let placeholder_index = self.placeholder_indices.insert(placeholder);
959 match self.placeholder_index_to_region.get(placeholder_index) {
962 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
963 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
964 self.placeholder_index_to_region.push(region);
971 /// The `Locations` type summarizes *where* region constraints are
972 /// required to hold. Normally, this is at a particular point which
973 /// created the obligation, but for constraints that the user gave, we
974 /// want the constraint to hold at all points.
975 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
977 /// Indicates that a type constraint should always be true. This
978 /// is particularly important in the new borrowck analysis for
979 /// things like the type of the return slot. Consider this
982 /// ```compile_fail,E0515
983 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
985 /// return &y; // error
989 /// Here, we wind up with the signature from the return type being
990 /// something like `&'1 u32` where `'1` is a universal region. But
991 /// the type of the return slot `_0` is something like `&'2 u32`
992 /// where `'2` is an existential region variable. The type checker
993 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
994 /// older NLL analysis, we required this only at the entry point
995 /// to the function. By the nature of the constraints, this wound
996 /// up propagating to all points reachable from start (because
997 /// `'1` -- as a universal region -- is live everywhere). In the
998 /// newer analysis, though, this doesn't work: `_0` is considered
999 /// dead at the start (it has no usable value) and hence this type
1000 /// equality is basically a no-op. Then, later on, when we do `_0
1001 /// = &'3 y`, that region `'3` never winds up related to the
1002 /// universal region `'1` and hence no error occurs. Therefore, we
1003 /// use Locations::All instead, which ensures that the `'1` and
1004 /// `'2` are equal everything. We also use this for other
1005 /// user-given type annotations; e.g., if the user wrote `let mut
1006 /// x: &'static u32 = ...`, we would ensure that all values
1007 /// assigned to `x` are of `'static` lifetime.
1009 /// The span points to the place the constraint arose. For example,
1010 /// it points to the type in a user-given type annotation. If
1011 /// there's no sensible span then it's DUMMY_SP.
1014 /// An outlives constraint that only has to hold at a single location,
1015 /// usually it represents a point where references flow from one spot to
1016 /// another (e.g., `x = y`)
1021 pub fn from_location(&self) -> Option<Location> {
1023 Locations::All(_) => None,
1024 Locations::Single(from_location) => Some(*from_location),
1028 /// Gets a span representing the location.
1029 pub fn span(&self, body: &Body<'_>) -> Span {
1031 Locations::All(span) => *span,
1032 Locations::Single(l) => body.source_info(*l).span,
1037 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1039 infcx: &'a InferCtxt<'tcx>,
1040 body: &'a Body<'tcx>,
1041 param_env: ty::ParamEnv<'tcx>,
1042 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1043 implicit_region_bound: ty::Region<'tcx>,
1044 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1046 let mut checker = Self {
1048 last_span: DUMMY_SP,
1050 user_type_annotations: &body.user_type_annotations,
1053 implicit_region_bound,
1055 reported_errors: Default::default(),
1057 checker.check_user_type_annotations();
1061 fn body(&self) -> &Body<'tcx> {
1065 fn unsized_feature_enabled(&self) -> bool {
1066 let features = self.tcx().features();
1067 features.unsized_locals || features.unsized_fn_params
1070 /// Equate the inferred type and the annotated type for user type annotations
1071 #[instrument(skip(self), level = "debug")]
1072 fn check_user_type_annotations(&mut self) {
1073 debug!(?self.user_type_annotations);
1074 for user_annotation in self.user_type_annotations {
1075 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1076 let inferred_ty = self.normalize(inferred_ty, Locations::All(span));
1077 let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1078 debug!(?annotation);
1080 UserType::Ty(mut ty) => {
1081 ty = self.normalize(ty, Locations::All(span));
1083 if let Err(terr) = self.eq_types(
1086 Locations::All(span),
1087 ConstraintCategory::BoringNoLocation,
1092 "bad user type ({:?} = {:?}): {:?}",
1099 self.prove_predicate(
1100 ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into()))
1101 .to_predicate(self.tcx()),
1102 Locations::All(span),
1103 ConstraintCategory::TypeAnnotation,
1106 UserType::TypeOf(def_id, user_substs) => {
1107 if let Err(terr) = self.fully_perform_op(
1108 Locations::All(span),
1109 ConstraintCategory::BoringNoLocation,
1110 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1119 "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}",
1123 self.tcx().type_of(def_id),
1132 #[instrument(skip(self, data), level = "debug")]
1133 fn push_region_constraints(
1135 locations: Locations,
1136 category: ConstraintCategory,
1137 data: &QueryRegionConstraints<'tcx>,
1139 debug!("constraints generated: {:#?}", data);
1141 constraint_conversion::ConstraintConversion::new(
1143 self.borrowck_context.universal_regions,
1144 self.region_bound_pairs,
1145 self.implicit_region_bound,
1148 locations.span(self.body),
1150 &mut self.borrowck_context.constraints,
1155 /// Try to relate `sub <: sup`
1160 locations: Locations,
1161 category: ConstraintCategory,
1163 // Use this order of parameters because the sup type is usually the
1164 // "expected" type in diagnostics.
1165 self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
1168 #[instrument(skip(self, category), level = "debug")]
1173 locations: Locations,
1174 category: ConstraintCategory,
1176 self.relate_types(expected, ty::Variance::Invariant, found, locations, category)
1179 #[instrument(skip(self), level = "debug")]
1180 fn relate_type_and_user_type(
1184 user_ty: &UserTypeProjection,
1185 locations: Locations,
1186 category: ConstraintCategory,
1188 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1189 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1191 let tcx = self.infcx.tcx;
1193 for proj in &user_ty.projs {
1194 let projected_ty = curr_projected_ty.projection_ty_core(
1199 let ty = this.field_ty(tcx, field);
1200 self.normalize(ty, locations)
1202 |_, _| unreachable!(),
1204 curr_projected_ty = projected_ty;
1207 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1208 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1211 let ty = curr_projected_ty.ty;
1212 self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1217 fn tcx(&self) -> TyCtxt<'tcx> {
1221 #[instrument(skip(self, body, location), level = "debug")]
1222 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1223 let tcx = self.tcx();
1224 debug!("stmt kind: {:?}", stmt.kind);
1226 StatementKind::Assign(box (ref place, ref rv)) => {
1227 // Assignments to temporaries are not "interesting";
1228 // they are not caused by the user, but rather artifacts
1229 // of lowering. Assignments to other sorts of places *are* interesting
1231 let category = match place.as_local() {
1232 Some(RETURN_PLACE) => {
1233 let defining_ty = &self.borrowck_context.universal_regions.defining_ty;
1234 if defining_ty.is_const() {
1235 if tcx.is_static(defining_ty.def_id()) {
1236 ConstraintCategory::UseAsStatic
1238 ConstraintCategory::UseAsConst
1241 ConstraintCategory::Return(ReturnConstraint::Normal)
1246 body.local_decls[l].local_info,
1247 Some(box LocalInfo::AggregateTemp)
1250 ConstraintCategory::Usage
1252 Some(l) if !body.local_decls[l].is_user_variable() => {
1253 ConstraintCategory::Boring
1255 _ => ConstraintCategory::Assignment,
1258 "assignment category: {:?} {:?}",
1260 place.as_local().map(|l| &body.local_decls[l])
1263 let place_ty = place.ty(body, tcx).ty;
1265 let place_ty = self.normalize(place_ty, location);
1266 debug!("place_ty normalized: {:?}", place_ty);
1267 let rv_ty = rv.ty(body, tcx);
1269 let rv_ty = self.normalize(rv_ty, location);
1270 debug!("normalized rv_ty: {:?}", rv_ty);
1272 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1277 "bad assignment ({:?} = {:?}): {:?}",
1284 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1285 if let Err(terr) = self.relate_type_and_user_type(
1287 ty::Variance::Invariant,
1288 &UserTypeProjection { base: annotation_index, projs: vec![] },
1289 location.to_locations(),
1290 ConstraintCategory::Boring,
1292 let annotation = &self.user_type_annotations[annotation_index];
1296 "bad user type on rvalue ({:?} = {:?}): {:?}",
1304 self.check_rvalue(body, rv, location);
1305 if !self.unsized_feature_enabled() {
1306 let trait_ref = ty::TraitRef {
1307 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1308 substs: tcx.mk_substs_trait(place_ty, &[]),
1310 self.prove_trait_ref(
1312 location.to_locations(),
1313 ConstraintCategory::SizedBound,
1317 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1318 let place_ty = place.ty(body, tcx).ty;
1319 if let Err(terr) = self.relate_type_and_user_type(
1323 Locations::All(stmt.source_info.span),
1324 ConstraintCategory::TypeAnnotation,
1326 let annotation = &self.user_type_annotations[projection.base];
1330 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1338 StatementKind::Intrinsic(box ref kind) => match kind {
1339 NonDivergingIntrinsic::Assume(op) => self.check_operand(op, location),
1340 NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
1341 stmt.source_info.span,
1342 "Unexpected NonDivergingIntrinsic::CopyNonOverlapping, should only appear after lowering_intrinsics",
1345 StatementKind::FakeRead(..)
1346 | StatementKind::StorageLive(..)
1347 | StatementKind::StorageDead(..)
1348 | StatementKind::Retag { .. }
1349 | StatementKind::Coverage(..)
1350 | StatementKind::Nop => {}
1351 StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
1352 bug!("Statement not allowed in this MIR phase")
1357 #[instrument(skip(self, body, term_location), level = "debug")]
1358 fn check_terminator(
1361 term: &Terminator<'tcx>,
1362 term_location: Location,
1364 let tcx = self.tcx();
1365 debug!("terminator kind: {:?}", term.kind);
1367 TerminatorKind::Goto { .. }
1368 | TerminatorKind::Resume
1369 | TerminatorKind::Abort
1370 | TerminatorKind::Return
1371 | TerminatorKind::GeneratorDrop
1372 | TerminatorKind::Unreachable
1373 | TerminatorKind::Drop { .. }
1374 | TerminatorKind::FalseEdge { .. }
1375 | TerminatorKind::FalseUnwind { .. }
1376 | TerminatorKind::InlineAsm { .. } => {
1377 // no checks needed for these
1380 TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1381 let place_ty = place.ty(body, tcx).ty;
1382 let rv_ty = value.ty(body, tcx);
1384 let locations = term_location.to_locations();
1386 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1391 "bad DropAndReplace ({:?} = {:?}): {:?}",
1398 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1399 self.check_operand(discr, term_location);
1401 let discr_ty = discr.ty(body, tcx);
1402 if let Err(terr) = self.sub_types(
1405 term_location.to_locations(),
1406 ConstraintCategory::Assignment,
1411 "bad SwitchInt ({:?} on {:?}): {:?}",
1417 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1418 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1420 // FIXME: check the values
1422 TerminatorKind::Call {
1430 self.check_operand(func, term_location);
1432 self.check_operand(arg, term_location);
1435 let func_ty = func.ty(body, tcx);
1436 debug!("func_ty.kind: {:?}", func_ty.kind());
1438 let sig = match func_ty.kind() {
1439 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1441 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1445 let (sig, map) = tcx.replace_late_bound_regions(sig, |br| {
1446 self.infcx.next_region_var(LateBoundRegion(
1447 term.source_info.span,
1449 LateBoundRegionConversionTime::FnCall,
1453 // IMPORTANT: We have to prove well formed for the function signature before
1454 // we normalize it, as otherwise types like `<&'a &'b () as Trait>::Assoc`
1455 // get normalized away, causing us to ignore the `'b: 'a` bound used by the function.
1457 // Normalization results in a well formed type if the input is well formed, so we
1458 // don't have to check it twice.
1460 // See #91068 for an example.
1461 self.prove_predicates(
1462 sig.inputs_and_output
1464 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1465 term_location.to_locations(),
1466 ConstraintCategory::Boring,
1468 let sig = self.normalize(sig, term_location);
1469 self.check_call_dest(body, term, &sig, *destination, target, term_location);
1471 // The ordinary liveness rules will ensure that all
1472 // regions in the type of the callee are live here. We
1473 // then further constrain the late-bound regions that
1474 // were instantiated at the call site to be live as
1475 // well. The resulting is that all the input (and
1476 // output) types in the signature must be live, since
1477 // all the inputs that fed into it were live.
1478 for &late_bound_region in map.values() {
1480 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1481 self.borrowck_context
1483 .liveness_constraints
1484 .add_element(region_vid, term_location);
1487 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1489 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1490 self.check_operand(cond, term_location);
1492 let cond_ty = cond.ty(body, tcx);
1493 if cond_ty != tcx.types.bool {
1494 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1497 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1498 if len.ty(body, tcx) != tcx.types.usize {
1499 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1501 if index.ty(body, tcx) != tcx.types.usize {
1502 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1506 TerminatorKind::Yield { ref value, .. } => {
1507 self.check_operand(value, term_location);
1509 let value_ty = value.ty(body, tcx);
1510 match body.yield_ty() {
1511 None => span_mirbug!(self, term, "yield in non-generator"),
1513 if let Err(terr) = self.sub_types(
1516 term_location.to_locations(),
1517 ConstraintCategory::Yield,
1522 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1537 term: &Terminator<'tcx>,
1538 sig: &ty::FnSig<'tcx>,
1539 destination: Place<'tcx>,
1540 target: Option<BasicBlock>,
1541 term_location: Location,
1543 let tcx = self.tcx();
1546 let dest_ty = destination.ty(body, tcx).ty;
1547 let dest_ty = self.normalize(dest_ty, term_location);
1548 let category = match destination.as_local() {
1549 Some(RETURN_PLACE) => {
1550 if let BorrowCheckContext {
1554 DefiningTy::Const(def_id, _)
1555 | DefiningTy::InlineConst(def_id, _),
1559 } = self.borrowck_context
1561 if tcx.is_static(*def_id) {
1562 ConstraintCategory::UseAsStatic
1564 ConstraintCategory::UseAsConst
1567 ConstraintCategory::Return(ReturnConstraint::Normal)
1570 Some(l) if !body.local_decls[l].is_user_variable() => {
1571 ConstraintCategory::Boring
1573 _ => ConstraintCategory::Assignment,
1576 let locations = term_location.to_locations();
1578 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1582 "call dest mismatch ({:?} <- {:?}): {:?}",
1589 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1590 // this check is done at `check_local`.
1591 if self.unsized_feature_enabled() {
1592 let span = term.source_info.span;
1593 self.ensure_place_sized(dest_ty, span);
1599 .conservative_is_privately_uninhabited(self.param_env.and(sig.output()))
1601 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1607 fn check_call_inputs(
1610 term: &Terminator<'tcx>,
1611 sig: &ty::FnSig<'tcx>,
1612 args: &[Operand<'tcx>],
1613 term_location: Location,
1614 from_hir_call: bool,
1616 debug!("check_call_inputs({:?}, {:?})", sig, args);
1617 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1618 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1621 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1622 let op_arg_ty = op_arg.ty(body, self.tcx());
1624 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1625 let category = if from_hir_call {
1626 ConstraintCategory::CallArgument(term_location)
1628 ConstraintCategory::Boring
1631 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
1636 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1646 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1647 let is_cleanup = block_data.is_cleanup;
1648 self.last_span = block_data.terminator().source_info.span;
1649 match block_data.terminator().kind {
1650 TerminatorKind::Goto { target } => {
1651 self.assert_iscleanup(body, block_data, target, is_cleanup)
1653 TerminatorKind::SwitchInt { ref targets, .. } => {
1654 for target in targets.all_targets() {
1655 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1658 TerminatorKind::Resume => {
1660 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1663 TerminatorKind::Abort => {
1665 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1668 TerminatorKind::Return => {
1670 span_mirbug!(self, block_data, "return on cleanup block")
1673 TerminatorKind::GeneratorDrop { .. } => {
1675 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1678 TerminatorKind::Yield { resume, drop, .. } => {
1680 span_mirbug!(self, block_data, "yield in cleanup block")
1682 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1683 if let Some(drop) = drop {
1684 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1687 TerminatorKind::Unreachable => {}
1688 TerminatorKind::Drop { target, unwind, .. }
1689 | TerminatorKind::DropAndReplace { target, unwind, .. }
1690 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1691 self.assert_iscleanup(body, block_data, target, is_cleanup);
1692 if let Some(unwind) = unwind {
1694 span_mirbug!(self, block_data, "unwind on cleanup block")
1696 self.assert_iscleanup(body, block_data, unwind, true);
1699 TerminatorKind::Call { ref target, cleanup, .. } => {
1700 if let &Some(target) = target {
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);
1710 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1711 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1712 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1714 TerminatorKind::FalseUnwind { real_target, unwind } => {
1715 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1716 if let Some(unwind) = unwind {
1718 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1720 self.assert_iscleanup(body, block_data, unwind, true);
1723 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
1724 if let Some(target) = destination {
1725 self.assert_iscleanup(body, block_data, target, is_cleanup);
1727 if let Some(cleanup) = cleanup {
1729 span_mirbug!(self, block_data, "cleanup on cleanup block")
1731 self.assert_iscleanup(body, block_data, cleanup, true);
1737 fn assert_iscleanup(
1740 ctxt: &dyn fmt::Debug,
1744 if body[bb].is_cleanup != iscleanuppad {
1745 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1749 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1750 match body.local_kind(local) {
1751 LocalKind::ReturnPointer | LocalKind::Arg => {
1752 // return values of normal functions are required to be
1753 // sized by typeck, but return values of ADT constructors are
1754 // not because we don't include a `Self: Sized` bounds on them.
1756 // Unbound parts of arguments were never required to be Sized
1757 // - maybe we should make that a warning.
1760 LocalKind::Var | LocalKind::Temp => {}
1763 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1764 // and nullary ops are checked in `check_call_dest`.
1765 if !self.unsized_feature_enabled() {
1766 let span = local_decl.source_info.span;
1767 let ty = local_decl.ty;
1768 self.ensure_place_sized(ty, span);
1772 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1773 let tcx = self.tcx();
1775 // Erase the regions from `ty` to get a global type. The
1776 // `Sized` bound in no way depends on precise regions, so this
1777 // shouldn't affect `is_sized`.
1778 let erased_ty = tcx.erase_regions(ty);
1779 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1780 // in current MIR construction, all non-control-flow rvalue
1781 // expressions evaluate through `as_temp` or `into` a return
1782 // slot or local, so to find all unsized rvalues it is enough
1783 // to check all temps, return slots and locals.
1784 if self.reported_errors.replace((ty, span)).is_none() {
1785 // While this is located in `nll::typeck` this error is not
1786 // an NLL error, it's a required check to prevent creation
1787 // of unsized rvalues in a call expression.
1788 self.tcx().sess.emit_err(MoveUnsized { ty, span });
1793 fn aggregate_field_ty(
1795 ak: &AggregateKind<'tcx>,
1798 ) -> Result<Ty<'tcx>, FieldAccessError> {
1799 let tcx = self.tcx();
1802 AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => {
1803 let def = tcx.adt_def(adt_did);
1804 let variant = &def.variant(variant_index);
1805 let adj_field_index = active_field_index.unwrap_or(field_index);
1806 if let Some(field) = variant.fields.get(adj_field_index) {
1807 Ok(self.normalize(field.ty(tcx, substs), location))
1809 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1812 AggregateKind::Closure(_, substs) => {
1813 match substs.as_closure().upvar_tys().nth(field_index) {
1815 None => Err(FieldAccessError::OutOfRange {
1816 field_count: substs.as_closure().upvar_tys().count(),
1820 AggregateKind::Generator(_, substs, _) => {
1821 // It doesn't make sense to look at a field beyond the prefix;
1822 // these require a variant index, and are not initialized in
1823 // aggregate rvalues.
1824 match substs.as_generator().prefix_tys().nth(field_index) {
1826 None => Err(FieldAccessError::OutOfRange {
1827 field_count: substs.as_generator().prefix_tys().count(),
1831 AggregateKind::Array(ty) => Ok(ty),
1832 AggregateKind::Tuple => {
1833 unreachable!("This should have been covered in check_rvalues");
1838 fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1839 debug!(?op, ?location, "check_operand");
1841 if let Operand::Constant(constant) = op {
1842 let maybe_uneval = match constant.literal {
1843 ConstantKind::Val(..) | ConstantKind::Ty(_) => None,
1844 ConstantKind::Unevaluated(uv, _) => Some(uv),
1847 if let Some(uv) = maybe_uneval {
1848 if uv.promoted.is_none() {
1849 let tcx = self.tcx();
1850 let def_id = uv.def.def_id_for_type_of();
1851 if tcx.def_kind(def_id) == DefKind::InlineConst {
1852 let def_id = def_id.expect_local();
1854 self.prove_closure_bounds(tcx, def_id, uv.substs, location);
1855 self.normalize_and_prove_instantiated_predicates(
1858 location.to_locations(),
1866 #[instrument(skip(self, body), level = "debug")]
1867 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1868 let tcx = self.tcx();
1871 Rvalue::Aggregate(ak, ops) => {
1873 self.check_operand(op, location);
1875 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1878 Rvalue::Repeat(operand, len) => {
1879 self.check_operand(operand, location);
1881 // If the length cannot be evaluated we must assume that the length can be larger
1883 // If the length is larger than 1, the repeat expression will need to copy the
1884 // element, so we require the `Copy` trait.
1885 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1887 Operand::Copy(..) | Operand::Constant(..) => {
1888 // These are always okay: direct use of a const, or a value that can evidently be copied.
1890 Operand::Move(place) => {
1891 // Make sure that repeated elements implement `Copy`.
1892 let span = body.source_info(location).span;
1893 let ty = place.ty(body, tcx).ty;
1894 let trait_ref = ty::TraitRef::new(
1895 tcx.require_lang_item(LangItem::Copy, Some(span)),
1896 tcx.mk_substs_trait(ty, &[]),
1899 self.prove_trait_ref(
1901 Locations::Single(location),
1902 ConstraintCategory::CopyBound,
1909 &Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, ty) => {
1910 let trait_ref = ty::TraitRef {
1911 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1912 substs: tcx.mk_substs_trait(ty, &[]),
1915 self.prove_trait_ref(
1917 location.to_locations(),
1918 ConstraintCategory::SizedBound,
1922 Rvalue::ShallowInitBox(operand, ty) => {
1923 self.check_operand(operand, location);
1925 let trait_ref = ty::TraitRef {
1926 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1927 substs: tcx.mk_substs_trait(*ty, &[]),
1930 self.prove_trait_ref(
1932 location.to_locations(),
1933 ConstraintCategory::SizedBound,
1937 Rvalue::Cast(cast_kind, op, ty) => {
1938 self.check_operand(op, location);
1941 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1942 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1944 // The type that we see in the fcx is like
1945 // `foo::<'a, 'b>`, where `foo` is the path to a
1946 // function definition. When we extract the
1947 // signature, it comes from the `fn_sig` query,
1948 // and hence may contain unnormalized results.
1949 let fn_sig = self.normalize(fn_sig, location);
1951 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1953 if let Err(terr) = self.eq_types(
1956 location.to_locations(),
1957 ConstraintCategory::Cast,
1962 "equating {:?} with {:?} yields {:?}",
1970 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
1971 let sig = match op.ty(body, tcx).kind() {
1972 ty::Closure(_, substs) => substs.as_closure().sig(),
1975 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
1977 if let Err(terr) = self.eq_types(
1980 location.to_locations(),
1981 ConstraintCategory::Cast,
1986 "equating {:?} with {:?} yields {:?}",
1994 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
1995 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1997 // The type that we see in the fcx is like
1998 // `foo::<'a, 'b>`, where `foo` is the path to a
1999 // function definition. When we extract the
2000 // signature, it comes from the `fn_sig` query,
2001 // and hence may contain unnormalized results.
2002 let fn_sig = self.normalize(fn_sig, location);
2004 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2006 if let Err(terr) = self.eq_types(
2009 location.to_locations(),
2010 ConstraintCategory::Cast,
2015 "equating {:?} with {:?} yields {:?}",
2023 CastKind::Pointer(PointerCast::Unsize) => {
2025 let trait_ref = ty::TraitRef {
2027 .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2028 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2031 self.prove_trait_ref(
2033 location.to_locations(),
2034 ConstraintCategory::Cast,
2038 CastKind::DynStar => {
2039 // get the constraints from the target type (`dyn* Clone`)
2041 // apply them to prove that the source type `Foo` implements `Clone` etc
2042 let (existential_predicates, region) = match ty.kind() {
2043 Dynamic(predicates, region, ty::DynStar) => (predicates, region),
2044 _ => panic!("Invalid dyn* cast_ty"),
2047 let self_ty = op.ty(body, tcx);
2049 self.prove_predicates(
2050 existential_predicates
2052 .map(|predicate| predicate.with_self_ty(tcx, self_ty)),
2053 location.to_locations(),
2054 ConstraintCategory::Cast,
2057 let outlives_predicate =
2058 tcx.mk_predicate(Binder::dummy(ty::PredicateKind::TypeOutlives(
2059 ty::OutlivesPredicate(self_ty, *region),
2061 self.prove_predicate(
2063 location.to_locations(),
2064 ConstraintCategory::Cast,
2068 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2069 let ty::RawPtr(ty::TypeAndMut {
2071 mutbl: hir::Mutability::Mut,
2072 }) = op.ty(body, tcx).kind() else {
2076 "unexpected base type for cast {:?}",
2081 let ty::RawPtr(ty::TypeAndMut {
2083 mutbl: hir::Mutability::Not,
2084 }) = ty.kind() else {
2088 "unexpected target type for cast {:?}",
2093 if let Err(terr) = self.sub_types(
2096 location.to_locations(),
2097 ConstraintCategory::Cast,
2102 "relating {:?} with {:?} yields {:?}",
2110 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2111 let ty_from = op.ty(body, tcx);
2113 let opt_ty_elem_mut = match ty_from.kind() {
2114 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2115 match array_ty.kind() {
2116 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2123 let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
2127 "ArrayToPointer cast from unexpected type {:?}",
2133 let (ty_to, ty_to_mut) = match ty.kind() {
2134 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2141 "ArrayToPointer cast to unexpected type {:?}",
2148 if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2152 "ArrayToPointer cast from const {:?} to mut {:?}",
2159 if let Err(terr) = self.sub_types(
2162 location.to_locations(),
2163 ConstraintCategory::Cast,
2168 "relating {:?} with {:?} yields {:?}",
2176 CastKind::PointerExposeAddress => {
2177 let ty_from = op.ty(body, tcx);
2178 let cast_ty_from = CastTy::from_ty(ty_from);
2179 let cast_ty_to = CastTy::from_ty(*ty);
2180 match (cast_ty_from, cast_ty_to) {
2181 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => (),
2186 "Invalid PointerExposeAddress cast {:?} -> {:?}",
2194 CastKind::PointerFromExposedAddress => {
2195 let ty_from = op.ty(body, tcx);
2196 let cast_ty_from = CastTy::from_ty(ty_from);
2197 let cast_ty_to = CastTy::from_ty(*ty);
2198 match (cast_ty_from, cast_ty_to) {
2199 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
2204 "Invalid PointerFromExposedAddress cast {:?} -> {:?}",
2211 CastKind::IntToInt => {
2212 let ty_from = op.ty(body, tcx);
2213 let cast_ty_from = CastTy::from_ty(ty_from);
2214 let cast_ty_to = CastTy::from_ty(*ty);
2215 match (cast_ty_from, cast_ty_to) {
2216 (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => (),
2221 "Invalid IntToInt cast {:?} -> {:?}",
2228 CastKind::IntToFloat => {
2229 let ty_from = op.ty(body, tcx);
2230 let cast_ty_from = CastTy::from_ty(ty_from);
2231 let cast_ty_to = CastTy::from_ty(*ty);
2232 match (cast_ty_from, cast_ty_to) {
2233 (Some(CastTy::Int(_)), Some(CastTy::Float)) => (),
2238 "Invalid IntToFloat cast {:?} -> {:?}",
2245 CastKind::FloatToInt => {
2246 let ty_from = op.ty(body, tcx);
2247 let cast_ty_from = CastTy::from_ty(ty_from);
2248 let cast_ty_to = CastTy::from_ty(*ty);
2249 match (cast_ty_from, cast_ty_to) {
2250 (Some(CastTy::Float), Some(CastTy::Int(_))) => (),
2255 "Invalid FloatToInt cast {:?} -> {:?}",
2262 CastKind::FloatToFloat => {
2263 let ty_from = op.ty(body, tcx);
2264 let cast_ty_from = CastTy::from_ty(ty_from);
2265 let cast_ty_to = CastTy::from_ty(*ty);
2266 match (cast_ty_from, cast_ty_to) {
2267 (Some(CastTy::Float), Some(CastTy::Float)) => (),
2272 "Invalid FloatToFloat cast {:?} -> {:?}",
2279 CastKind::FnPtrToPtr => {
2280 let ty_from = op.ty(body, tcx);
2281 let cast_ty_from = CastTy::from_ty(ty_from);
2282 let cast_ty_to = CastTy::from_ty(*ty);
2283 match (cast_ty_from, cast_ty_to) {
2284 (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
2289 "Invalid FnPtrToPtr cast {:?} -> {:?}",
2296 CastKind::PtrToPtr => {
2297 let ty_from = op.ty(body, tcx);
2298 let cast_ty_from = CastTy::from_ty(ty_from);
2299 let cast_ty_to = CastTy::from_ty(*ty);
2300 match (cast_ty_from, cast_ty_to) {
2301 (Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_))) => (),
2306 "Invalid PtrToPtr cast {:?} -> {:?}",
2316 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2317 self.add_reborrow_constraint(&body, location, *region, borrowed_place);
2321 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2324 self.check_operand(left, location);
2325 self.check_operand(right, location);
2327 let ty_left = left.ty(body, tcx);
2328 match ty_left.kind() {
2329 // Types with regions are comparable if they have a common super-type.
2330 ty::RawPtr(_) | ty::FnPtr(_) => {
2331 let ty_right = right.ty(body, tcx);
2332 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2333 kind: TypeVariableOriginKind::MiscVariable,
2334 span: body.source_info(location).span,
2339 location.to_locations(),
2340 ConstraintCategory::Boring,
2342 .unwrap_or_else(|err| {
2343 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2345 if let Err(terr) = self.sub_types(
2348 location.to_locations(),
2349 ConstraintCategory::Boring,
2354 "unexpected comparison types {:?} and {:?} yields {:?}",
2361 // For types with no regions we can just check that the
2362 // both operands have the same type.
2363 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2364 if ty_left == right.ty(body, tcx) => {}
2365 // Other types are compared by trait methods, not by
2366 // `Rvalue::BinaryOp`.
2370 "unexpected comparison types {:?} and {:?}",
2377 Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => {
2378 self.check_operand(operand, location);
2380 Rvalue::CopyForDeref(place) => {
2381 let op = &Operand::Copy(*place);
2382 self.check_operand(op, location);
2385 Rvalue::BinaryOp(_, box (left, right))
2386 | Rvalue::CheckedBinaryOp(_, box (left, right)) => {
2387 self.check_operand(left, location);
2388 self.check_operand(right, location);
2391 Rvalue::AddressOf(..)
2392 | Rvalue::ThreadLocalRef(..)
2394 | Rvalue::Discriminant(..) => {}
2398 /// If this rvalue supports a user-given type annotation, then
2399 /// extract and return it. This represents the final type of the
2400 /// rvalue and will be unified with the inferred type.
2401 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2404 | Rvalue::ThreadLocalRef(_)
2405 | Rvalue::Repeat(..)
2407 | Rvalue::AddressOf(..)
2410 | Rvalue::ShallowInitBox(..)
2411 | Rvalue::BinaryOp(..)
2412 | Rvalue::CheckedBinaryOp(..)
2413 | Rvalue::NullaryOp(..)
2414 | Rvalue::CopyForDeref(..)
2415 | Rvalue::UnaryOp(..)
2416 | Rvalue::Discriminant(..) => None,
2418 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2419 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2420 AggregateKind::Array(_) => None,
2421 AggregateKind::Tuple => None,
2422 AggregateKind::Closure(_, _) => None,
2423 AggregateKind::Generator(_, _, _) => None,
2428 fn check_aggregate_rvalue(
2431 rvalue: &Rvalue<'tcx>,
2432 aggregate_kind: &AggregateKind<'tcx>,
2433 operands: &[Operand<'tcx>],
2436 let tcx = self.tcx();
2438 self.prove_aggregate_predicates(aggregate_kind, location);
2440 if *aggregate_kind == AggregateKind::Tuple {
2441 // tuple rvalue field type is always the type of the op. Nothing to check here.
2445 for (i, operand) in operands.iter().enumerate() {
2446 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2447 Ok(field_ty) => field_ty,
2448 Err(FieldAccessError::OutOfRange { field_count }) => {
2452 "accessed field #{} but variant only has {}",
2459 let operand_ty = operand.ty(body, tcx);
2460 let operand_ty = self.normalize(operand_ty, location);
2462 if let Err(terr) = self.sub_types(
2465 location.to_locations(),
2466 ConstraintCategory::Boring,
2471 "{:?} is not a subtype of {:?}: {:?}",
2480 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2484 /// - `location`: the location `L` where the borrow expression occurs
2485 /// - `borrow_region`: the region `'a` associated with the borrow
2486 /// - `borrowed_place`: the place `P` being borrowed
2487 fn add_reborrow_constraint(
2491 borrow_region: ty::Region<'tcx>,
2492 borrowed_place: &Place<'tcx>,
2494 // These constraints are only meaningful during borrowck:
2495 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2496 self.borrowck_context;
2498 // In Polonius mode, we also push a `loan_issued_at` fact
2499 // linking the loan to the region (in some cases, though,
2500 // there is no loan associated with this borrow expression --
2501 // that occurs when we are borrowing an unsafe place, for
2503 if let Some(all_facts) = all_facts {
2504 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2505 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2506 let region_vid = borrow_region.to_region_vid();
2507 all_facts.loan_issued_at.push((
2510 location_table.mid_index(location),
2515 // If we are reborrowing the referent of another reference, we
2516 // need to add outlives relationships. In a case like `&mut
2517 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2518 // need to ensure that `'b: 'a`.
2521 "add_reborrow_constraint({:?}, {:?}, {:?})",
2522 location, borrow_region, borrowed_place
2525 let mut cursor = borrowed_place.projection.as_ref();
2526 let tcx = self.infcx.tcx;
2527 let field = path_utils::is_upvar_field_projection(
2529 &self.borrowck_context.upvars,
2530 borrowed_place.as_ref(),
2533 let category = if let Some(field) = field {
2534 ConstraintCategory::ClosureUpvar(field)
2536 ConstraintCategory::Boring
2539 while let [proj_base @ .., elem] = cursor {
2542 debug!("add_reborrow_constraint - iteration {:?}", elem);
2545 ProjectionElem::Deref => {
2546 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2548 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2549 match base_ty.kind() {
2550 ty::Ref(ref_region, _, mutbl) => {
2551 constraints.outlives_constraints.push(OutlivesConstraint {
2552 sup: ref_region.to_region_vid(),
2553 sub: borrow_region.to_region_vid(),
2554 locations: location.to_locations(),
2555 span: location.to_locations().span(body),
2557 variance_info: ty::VarianceDiagInfo::default(),
2561 hir::Mutability::Not => {
2562 // Immutable reference. We don't need the base
2563 // to be valid for the entire lifetime of
2567 hir::Mutability::Mut => {
2568 // Mutable reference. We *do* need the base
2569 // to be valid, because after the base becomes
2570 // invalid, someone else can use our mutable deref.
2572 // This is in order to make the following function
2575 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2580 // As otherwise you could clone `&mut T` using the
2581 // following function:
2583 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2584 // let my_clone = unsafe_deref(&'a x);
2593 // deref of raw pointer, guaranteed to be valid
2596 ty::Adt(def, _) if def.is_box() => {
2597 // deref of `Box`, need the base to be valid - propagate
2599 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2602 ProjectionElem::Field(..)
2603 | ProjectionElem::Downcast(..)
2604 | ProjectionElem::OpaqueCast(..)
2605 | ProjectionElem::Index(..)
2606 | ProjectionElem::ConstantIndex { .. }
2607 | ProjectionElem::Subslice { .. } => {
2608 // other field access
2614 fn prove_aggregate_predicates(
2616 aggregate_kind: &AggregateKind<'tcx>,
2619 let tcx = self.tcx();
2622 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2623 aggregate_kind, location
2626 let (def_id, instantiated_predicates) = match *aggregate_kind {
2627 AggregateKind::Adt(adt_did, _, substs, _, _) => {
2628 (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, substs))
2631 // For closures, we have some **extra requirements** we
2633 // have to check. In particular, in their upvars and
2634 // signatures, closures often reference various regions
2635 // from the surrounding function -- we call those the
2636 // closure's free regions. When we borrow-check (and hence
2637 // region-check) closures, we may find that the closure
2638 // requires certain relationships between those free
2639 // regions. However, because those free regions refer to
2640 // portions of the CFG of their caller, the closure is not
2641 // in a position to verify those relationships. In that
2642 // case, the requirements get "propagated" to us, and so
2643 // we have to solve them here where we instantiate the
2646 // Despite the opacity of the previous paragraph, this is
2647 // actually relatively easy to understand in terms of the
2648 // desugaring. A closure gets desugared to a struct, and
2649 // these extra requirements are basically like where
2650 // clauses on the struct.
2651 AggregateKind::Closure(def_id, substs)
2652 | AggregateKind::Generator(def_id, substs, _) => {
2653 (def_id.to_def_id(), self.prove_closure_bounds(tcx, def_id, substs, location))
2656 AggregateKind::Array(_) | AggregateKind::Tuple => {
2657 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2661 self.normalize_and_prove_instantiated_predicates(
2663 instantiated_predicates,
2664 location.to_locations(),
2668 fn prove_closure_bounds(
2672 substs: SubstsRef<'tcx>,
2674 ) -> ty::InstantiatedPredicates<'tcx> {
2675 if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2677 let closure_constraints = QueryRegionConstraints {
2678 outlives: closure_region_requirements.apply_requirements(
2684 // Presently, closures never propagate member
2685 // constraints to their parents -- they are enforced
2686 // locally. This is largely a non-issue as member
2687 // constraints only come from `-> impl Trait` and
2688 // friends which don't appear (thus far...) in
2690 member_constraints: vec![],
2693 let bounds_mapping = closure_constraints
2697 .filter_map(|(idx, constraint)| {
2698 let ty::OutlivesPredicate(k1, r2) =
2699 constraint.0.no_bound_vars().unwrap_or_else(|| {
2700 bug!("query_constraint {:?} contained bound vars", constraint,);
2704 GenericArgKind::Lifetime(r1) => {
2705 // constraint is r1: r2
2706 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2707 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2708 let outlives_requirements =
2709 &closure_region_requirements.outlives_requirements[idx];
2712 (outlives_requirements.category, outlives_requirements.blame_span),
2715 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2723 .closure_bounds_mapping
2724 .insert(location, bounds_mapping);
2725 assert!(existing.is_none(), "Multiple closures at the same location.");
2727 self.push_region_constraints(
2728 location.to_locations(),
2729 ConstraintCategory::ClosureBounds,
2730 &closure_constraints,
2734 // Now equate closure substs to regions inherited from `typeck_root_def_id`. Fixes #98589.
2735 let typeck_root_def_id = tcx.typeck_root_def_id(self.body.source.def_id());
2736 let typeck_root_substs = ty::InternalSubsts::identity_for_item(tcx, typeck_root_def_id);
2738 let parent_substs = match tcx.def_kind(def_id) {
2739 DefKind::Closure => substs.as_closure().parent_substs(),
2740 DefKind::Generator => substs.as_generator().parent_substs(),
2741 DefKind::InlineConst => substs.as_inline_const().parent_substs(),
2742 other => bug!("unexpected item {:?}", other),
2744 let parent_substs = tcx.mk_substs(parent_substs.iter());
2746 assert_eq!(typeck_root_substs.len(), parent_substs.len());
2747 if let Err(_) = self.eq_substs(
2750 location.to_locations(),
2751 ConstraintCategory::BoringNoLocation,
2756 "could not relate closure to parent {:?} != {:?}",
2762 tcx.predicates_of(def_id).instantiate(tcx, substs)
2765 #[instrument(skip(self, body), level = "debug")]
2766 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2767 self.last_span = body.span;
2770 for (local, local_decl) in body.local_decls.iter_enumerated() {
2771 self.check_local(&body, local, local_decl);
2774 for (block, block_data) in body.basic_blocks.iter_enumerated() {
2775 let mut location = Location { block, statement_index: 0 };
2776 for stmt in &block_data.statements {
2777 if !stmt.source_info.span.is_dummy() {
2778 self.last_span = stmt.source_info.span;
2780 self.check_stmt(body, stmt, location);
2781 location.statement_index += 1;
2784 self.check_terminator(&body, block_data.terminator(), location);
2785 self.check_iscleanup(&body, block_data);
2790 trait NormalizeLocation: fmt::Debug + Copy {
2791 fn to_locations(self) -> Locations;
2794 impl NormalizeLocation for Locations {
2795 fn to_locations(self) -> Locations {
2800 impl NormalizeLocation for Location {
2801 fn to_locations(self) -> Locations {
2802 Locations::Single(self)
2806 /// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2807 /// this is not canonicalized - it directly affects the main `InferCtxt`
2808 /// that we use during MIR borrowchecking.
2810 pub(super) struct InstantiateOpaqueType<'tcx> {
2811 pub base_universe: Option<ty::UniverseIndex>,
2812 pub region_constraints: Option<RegionConstraintData<'tcx>>,
2813 pub obligations: Vec<PredicateObligation<'tcx>>,
2816 impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2818 /// We use this type itself to store the information used
2819 /// when reporting errors. Since this is not a query, we don't
2820 /// re-run anything during error reporting - we just use the information
2821 /// we saved to help extract an error from the already-existing region
2822 /// constraints in our `InferCtxt`
2823 type ErrorInfo = InstantiateOpaqueType<'tcx>;
2825 fn fully_perform(mut self, infcx: &InferCtxt<'tcx>) -> Fallible<TypeOpOutput<'tcx, Self>> {
2826 let (mut output, region_constraints) = scrape_region_constraints(infcx, || {
2827 Ok(InferOk { value: (), obligations: self.obligations.clone() })
2829 self.region_constraints = Some(region_constraints);
2830 output.error_info = Some(self);