1 //! This pass type-checks the MIR to ensure it is not broken.
4 use std::{fmt, iter, mem};
8 use rustc_data_structures::frozen::Frozen;
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_data_structures::vec_map::VecMap;
11 use rustc_errors::struct_span_err;
13 use rustc_hir::def_id::LocalDefId;
14 use rustc_hir::lang_items::LangItem;
15 use rustc_index::vec::{Idx, IndexVec};
16 use rustc_infer::infer::canonical::QueryRegionConstraints;
17 use rustc_infer::infer::opaque_types::OpaqueTypeDecl;
18 use rustc_infer::infer::outlives::env::RegionBoundPairs;
19 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
20 use rustc_infer::infer::{
21 InferCtxt, InferOk, LateBoundRegionConversionTime, NllRegionVariableOrigin,
23 use rustc_middle::mir::tcx::PlaceTy;
24 use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
25 use rustc_middle::mir::AssertKind;
26 use rustc_middle::mir::*;
27 use rustc_middle::ty::adjustment::PointerCast;
28 use rustc_middle::ty::cast::CastTy;
29 use rustc_middle::ty::fold::TypeFoldable;
30 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef, UserSubsts};
31 use rustc_middle::ty::{
32 self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, OpaqueTypeKey, RegionVid,
33 ToPredicate, Ty, TyCtxt, UserType, UserTypeAnnotationIndex, WithConstness,
35 use rustc_span::def_id::CRATE_DEF_ID;
36 use rustc_span::{Span, DUMMY_SP};
37 use rustc_target::abi::VariantIdx;
38 use rustc_trait_selection::infer::InferCtxtExt as _;
39 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
40 use rustc_trait_selection::traits::query::type_op;
41 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
42 use rustc_trait_selection::traits::query::Fallible;
43 use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligations};
45 use rustc_const_eval::transform::{
46 check_consts::ConstCx, promote_consts::is_const_fn_in_array_repeat_expression,
48 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
49 use rustc_mir_dataflow::move_paths::MoveData;
50 use rustc_mir_dataflow::ResultsCursor;
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;
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>],
138 ) -> MirTypeckResults<'tcx> {
139 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
140 let mut universe_causes = FxHashMap::default();
141 universe_causes.insert(ty::UniverseIndex::from_u32(0), UniverseInfo::other());
142 let mut constraints = MirTypeckRegionConstraints {
143 placeholder_indices: PlaceholderIndices::default(),
144 placeholder_index_to_region: IndexVec::default(),
145 liveness_constraints: LivenessValues::new(elements.clone()),
146 outlives_constraints: OutlivesConstraintSet::default(),
147 member_constraints: MemberConstraintSet::default(),
148 closure_bounds_mapping: Default::default(),
149 type_tests: Vec::default(),
154 universal_region_relations,
156 normalized_inputs_and_output,
157 } = free_region_relations::create(
160 Some(implicit_region_bound),
165 for u in ty::UniverseIndex::ROOT..infcx.universe() {
166 let info = UniverseInfo::other();
167 constraints.universe_causes.insert(u, info);
170 let mut borrowck_context = BorrowCheckContext {
175 constraints: &mut constraints,
179 let opaque_type_values = type_check_internal(
185 implicit_region_bound,
186 &mut borrowck_context,
188 cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
189 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
191 translate_outlives_facts(&mut cx);
192 let opaque_type_values = mem::take(&mut infcx.inner.borrow_mut().opaque_types);
196 .filter_map(|(opaque_type_key, mut decl)| {
197 decl.concrete_ty = infcx.resolve_vars_if_possible(decl.concrete_ty);
199 "finalized opaque type {:?} to {:#?}",
201 decl.concrete_ty.kind()
203 if decl.concrete_ty.has_infer_types_or_consts() {
204 infcx.tcx.sess.delay_span_bug(
206 &format!("could not resolve {:#?}", decl.concrete_ty.kind()),
208 decl.concrete_ty = infcx.tcx.ty_error();
210 let concrete_is_opaque = if let ty::Opaque(def_id, _) = decl.concrete_ty.kind()
212 *def_id == opaque_type_key.def_id
217 if concrete_is_opaque {
218 // We're using an opaque `impl Trait` type without
219 // 'revealing' it. For example, code like this:
221 // type Foo = impl Debug;
222 // fn foo1() -> Foo { ... }
223 // fn foo2() -> Foo { foo1() }
225 // In `foo2`, we're not revealing the type of `Foo` - we're
226 // just treating it as the opaque type.
228 // When this occurs, we do *not* want to try to equate
229 // the concrete type with the underlying defining type
230 // of the opaque type - this will always fail, since
231 // the defining type of an opaque type is always
232 // some other type (e.g. not itself)
233 // Essentially, none of the normal obligations apply here -
234 // we're just passing around some unknown opaque type,
235 // without actually looking at the underlying type it
236 // gets 'revealed' into
238 "eq_opaque_type_and_type: non-defining use of {:?}",
239 opaque_type_key.def_id,
243 Some((opaque_type_key, decl))
250 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
254 skip(infcx, body, promoted, region_bound_pairs, borrowck_context, extra),
257 fn type_check_internal<'a, 'tcx, R>(
258 infcx: &'a InferCtxt<'a, 'tcx>,
259 param_env: ty::ParamEnv<'tcx>,
260 body: &'a Body<'tcx>,
261 promoted: &'a IndexVec<Promoted, Body<'tcx>>,
262 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
263 implicit_region_bound: ty::Region<'tcx>,
264 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
265 extra: impl FnOnce(TypeChecker<'a, 'tcx>) -> R,
267 let mut checker = TypeChecker::new(
272 implicit_region_bound,
275 let errors_reported = {
276 let mut verifier = TypeVerifier::new(&mut checker, body, promoted);
277 verifier.visit_body(&body);
278 verifier.errors_reported
281 if !errors_reported {
282 // if verifier failed, don't do further checks to avoid ICEs
283 checker.typeck_mir(body);
289 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
290 let cx = &mut typeck.borrowck_context;
291 if let Some(facts) = cx.all_facts {
292 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
293 let location_table = cx.location_table;
294 facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
295 |constraint: &OutlivesConstraint<'_>| {
296 if let Some(from_location) = constraint.locations.from_location() {
297 Either::Left(iter::once((
300 location_table.mid_index(from_location),
306 .map(move |location| (constraint.sup, constraint.sub, location)),
314 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
315 // We sometimes see MIR failures (notably predicate failures) due to
316 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
317 // to avoid reporting bugs in those cases.
318 tcx.sess.diagnostic().delay_span_bug(span, msg);
321 enum FieldAccessError {
322 OutOfRange { field_count: usize },
325 /// Verifies that MIR types are sane to not crash further checks.
327 /// The sanitize_XYZ methods here take an MIR object and compute its
328 /// type, calling `span_mirbug` and returning an error type if there
330 struct TypeVerifier<'a, 'b, 'tcx> {
331 cx: &'a mut TypeChecker<'b, 'tcx>,
332 body: &'b Body<'tcx>,
333 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
335 errors_reported: bool,
338 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
339 fn visit_span(&mut self, span: &Span) {
340 if !span.is_dummy() {
341 self.last_span = *span;
345 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
346 self.sanitize_place(place, location, context);
349 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
350 self.super_constant(constant, location);
351 let ty = self.sanitize_type(constant, constant.literal.ty());
353 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
354 let live_region_vid =
355 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
359 .liveness_constraints
360 .add_element(live_region_vid, location);
363 if let Some(annotation_index) = constant.user_ty {
364 if let Err(terr) = self.cx.relate_type_and_user_type(
365 constant.literal.ty(),
366 ty::Variance::Invariant,
367 &UserTypeProjection { base: annotation_index, projs: vec![] },
368 location.to_locations(),
369 ConstraintCategory::Boring,
371 let annotation = &self.cx.user_type_annotations[annotation_index];
375 "bad constant user type {:?} vs {:?}: {:?}",
377 constant.literal.ty(),
382 let tcx = self.tcx();
383 let maybe_uneval = match constant.literal {
384 ConstantKind::Ty(ct) => match ct.val {
385 ty::ConstKind::Unevaluated(uv) => Some(uv),
390 if let Some(uv) = maybe_uneval {
391 if let Some(promoted) = uv.promoted {
392 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
393 promoted: &Body<'tcx>,
396 if let Err(terr) = verifier.cx.eq_types(
399 location.to_locations(),
400 ConstraintCategory::Boring,
405 "bad promoted type ({:?}: {:?}): {:?}",
413 if !self.errors_reported {
414 let promoted_body = &self.promoted[promoted];
415 self.sanitize_promoted(promoted_body, location);
417 let promoted_ty = promoted_body.return_ty();
418 check_err(self, promoted_body, ty, promoted_ty);
421 if let Err(terr) = self.cx.fully_perform_op(
422 location.to_locations(),
423 ConstraintCategory::Boring,
424 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
425 constant.literal.ty(),
427 UserSubsts { substs: uv.substs(self.tcx()), user_self_ty: None },
433 "bad constant type {:?} ({:?})",
439 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
440 let unnormalized_ty = tcx.type_of(static_def_id);
441 let locations = location.to_locations();
442 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
443 let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty;
445 if let Err(terr) = self.cx.eq_types(
449 ConstraintCategory::Boring,
451 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
455 if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() {
456 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
457 self.cx.normalize_and_prove_instantiated_predicates(
459 instantiated_predicates,
460 location.to_locations(),
466 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
467 self.super_rvalue(rvalue, location);
468 let rval_ty = rvalue.ty(self.body, self.tcx());
469 self.sanitize_type(rvalue, rval_ty);
472 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
473 self.super_local_decl(local, local_decl);
474 self.sanitize_type(local_decl, local_decl.ty);
476 if let Some(user_ty) = &local_decl.user_ty {
477 for (user_ty, span) in user_ty.projections_and_spans() {
478 let ty = if !local_decl.is_nonref_binding() {
479 // If we have a binding of the form `let ref x: T = ..`
480 // then remove the outermost reference so we can check the
481 // type annotation for the remaining type.
482 if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
485 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
491 if let Err(terr) = self.cx.relate_type_and_user_type(
493 ty::Variance::Invariant,
495 Locations::All(*span),
496 ConstraintCategory::TypeAnnotation,
501 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
512 fn visit_body(&mut self, body: &Body<'tcx>) {
513 self.sanitize_type(&"return type", body.return_ty());
514 for local_decl in &body.local_decls {
515 self.sanitize_type(local_decl, local_decl.ty);
517 if self.errors_reported {
520 self.super_body(body);
524 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
526 cx: &'a mut TypeChecker<'b, 'tcx>,
527 body: &'b Body<'tcx>,
528 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
530 TypeVerifier { body, promoted, cx, last_span: body.span, errors_reported: false }
533 fn tcx(&self) -> TyCtxt<'tcx> {
537 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
538 if ty.has_escaping_bound_vars() || ty.references_error() {
539 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
545 /// Checks that the types internal to the `place` match up with
546 /// what would be expected.
551 context: PlaceContext,
553 debug!("sanitize_place: {:?}", place);
555 let mut place_ty = PlaceTy::from_ty(self.body.local_decls[place.local].ty);
557 for elem in place.projection.iter() {
558 if place_ty.variant_index.is_none() {
559 if place_ty.ty.references_error() {
560 assert!(self.errors_reported);
561 return PlaceTy::from_ty(self.tcx().ty_error());
564 place_ty = self.sanitize_projection(place_ty, elem, place, location);
567 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
568 let tcx = self.tcx();
569 let trait_ref = ty::TraitRef {
570 def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
571 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
574 // To have a `Copy` operand, the type `T` of the
575 // value must be `Copy`. Note that we prove that `T: Copy`,
576 // rather than using the `is_copy_modulo_regions`
577 // test. This is important because
578 // `is_copy_modulo_regions` ignores the resulting region
579 // obligations and assumes they pass. This can result in
580 // bounds from `Copy` impls being unsoundly ignored (e.g.,
581 // #29149). Note that we decide to use `Copy` before knowing
582 // whether the bounds fully apply: in effect, the rule is
583 // that if a value of some type could implement `Copy`, then
585 self.cx.prove_trait_ref(
587 location.to_locations(),
588 ConstraintCategory::CopyBound,
595 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
596 // Determine the constraints from the promoted MIR by running the type
597 // checker on the promoted MIR, then transfer the constraints back to
598 // the main MIR, changing the locations to the provided location.
600 let parent_body = mem::replace(&mut self.body, promoted_body);
602 // Use new sets of constraints and closure bounds so that we can
603 // modify their locations.
604 let all_facts = &mut None;
605 let mut constraints = Default::default();
606 let mut closure_bounds = Default::default();
607 let mut liveness_constraints =
608 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
609 // Don't try to add borrow_region facts for the promoted MIR
611 let mut swap_constraints = |this: &mut Self| {
612 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
614 &mut this.cx.borrowck_context.constraints.outlives_constraints,
618 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
622 &mut this.cx.borrowck_context.constraints.liveness_constraints,
623 &mut liveness_constraints,
627 swap_constraints(self);
629 self.visit_body(&promoted_body);
631 if !self.errors_reported {
632 // if verifier failed, don't do further checks to avoid ICEs
633 self.cx.typeck_mir(promoted_body);
636 self.body = parent_body;
637 // Merge the outlives constraints back in, at the given location.
638 swap_constraints(self);
640 let locations = location.to_locations();
641 for constraint in constraints.outlives().iter() {
642 let mut constraint = constraint.clone();
643 constraint.locations = locations;
644 if let ConstraintCategory::Return(_)
645 | ConstraintCategory::UseAsConst
646 | ConstraintCategory::UseAsStatic = constraint.category
648 // "Returning" from a promoted is an assignment to a
649 // temporary from the user's point of view.
650 constraint.category = ConstraintCategory::Boring;
652 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
654 for region in liveness_constraints.rows() {
655 // If the region is live at at least one location in the promoted MIR,
656 // then add a liveness constraint to the main MIR for this region
657 // at the location provided as an argument to this method
658 if liveness_constraints.get_elements(region).next().is_some() {
662 .liveness_constraints
663 .add_element(region, location);
667 if !closure_bounds.is_empty() {
668 let combined_bounds_mapping =
669 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
674 .closure_bounds_mapping
675 .insert(location, combined_bounds_mapping);
676 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
680 fn sanitize_projection(
687 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
688 let tcx = self.tcx();
689 let base_ty = base.ty;
691 ProjectionElem::Deref => {
692 let deref_ty = base_ty.builtin_deref(true);
693 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
694 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
697 ProjectionElem::Index(i) => {
698 let index_ty = Place::from(i).ty(self.body, tcx).ty;
699 if index_ty != tcx.types.usize {
700 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
702 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
703 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
707 ProjectionElem::ConstantIndex { .. } => {
708 // consider verifying in-bounds
709 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
710 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
713 ProjectionElem::Subslice { from, to, from_end } => {
714 PlaceTy::from_ty(match base_ty.kind() {
715 ty::Array(inner, _) => {
716 assert!(!from_end, "array subslices should not use from_end");
717 tcx.mk_array(inner, to - from)
720 assert!(from_end, "slice subslices should use from_end");
723 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
726 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
727 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
728 if index.as_usize() >= adt_def.variants.len() {
729 PlaceTy::from_ty(span_mirbug_and_err!(
732 "cast to variant #{:?} but enum only has {:?}",
734 adt_def.variants.len()
737 PlaceTy { ty: base_ty, variant_index: Some(index) }
740 // We do not need to handle generators here, because this runs
741 // before the generator transform stage.
743 let ty = if let Some(name) = maybe_name {
744 span_mirbug_and_err!(
747 "can't downcast {:?} as {:?}",
752 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
757 ProjectionElem::Field(field, fty) => {
758 let fty = self.sanitize_type(place, fty);
759 match self.field_ty(place, base, field, location) {
761 let ty = self.cx.normalize(ty, location);
762 if let Err(terr) = self.cx.eq_types(
765 location.to_locations(),
766 ConstraintCategory::Boring,
771 "bad field access ({:?}: {:?}): {:?}",
778 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
781 "accessed field #{} but variant only has {}",
786 PlaceTy::from_ty(fty)
791 fn error(&mut self) -> Ty<'tcx> {
792 self.errors_reported = true;
793 self.tcx().ty_error()
798 parent: &dyn fmt::Debug,
799 base_ty: PlaceTy<'tcx>,
802 ) -> Result<Ty<'tcx>, FieldAccessError> {
803 let tcx = self.tcx();
805 let (variant, substs) = match base_ty {
806 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
807 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
808 ty::Generator(def_id, substs, _) => {
809 let mut variants = substs.as_generator().state_tys(def_id, tcx);
810 let mut variant = match variants.nth(variant_index.into()) {
813 "variant_index of generator out of range: {:?}/{:?}",
815 substs.as_generator().state_tys(def_id, tcx).count()
818 return match variant.nth(field.index()) {
820 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
823 _ => bug!("can't have downcast of non-adt non-generator type"),
825 PlaceTy { ty, variant_index: None } => match *ty.kind() {
826 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
827 (&adt_def.variants[VariantIdx::new(0)], substs)
829 ty::Closure(_, substs) => {
833 .tuple_element_ty(field.index())
836 None => Err(FieldAccessError::OutOfRange {
837 field_count: substs.as_closure().upvar_tys().count(),
841 ty::Generator(_, substs, _) => {
842 // Only prefix fields (upvars and current state) are
843 // accessible without a variant index.
844 return match substs.as_generator().prefix_tys().nth(field.index()) {
846 None => Err(FieldAccessError::OutOfRange {
847 field_count: substs.as_generator().prefix_tys().count(),
852 return match tys.get(field.index()) {
853 Some(&ty) => Ok(ty.expect_ty()),
854 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
858 return Ok(span_mirbug_and_err!(
861 "can't project out of {:?}",
868 if let Some(field) = variant.fields.get(field.index()) {
869 Ok(self.cx.normalize(field.ty(tcx, substs), location))
871 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
876 /// The MIR type checker. Visits the MIR and enforces all the
877 /// constraints needed for it to be valid and well-typed. Along the
878 /// way, it accrues region constraints -- these can later be used by
879 /// NLL region checking.
880 struct TypeChecker<'a, 'tcx> {
881 infcx: &'a InferCtxt<'a, 'tcx>,
882 param_env: ty::ParamEnv<'tcx>,
884 body: &'a Body<'tcx>,
885 /// User type annotations are shared between the main MIR and the MIR of
886 /// all of the promoted items.
887 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
888 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
889 implicit_region_bound: ty::Region<'tcx>,
890 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
891 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
894 struct BorrowCheckContext<'a, 'tcx> {
895 universal_regions: &'a UniversalRegions<'tcx>,
896 location_table: &'a LocationTable,
897 all_facts: &'a mut Option<AllFacts>,
898 borrow_set: &'a BorrowSet<'tcx>,
899 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
900 upvars: &'a [Upvar<'tcx>],
903 crate struct MirTypeckResults<'tcx> {
904 crate constraints: MirTypeckRegionConstraints<'tcx>,
905 crate universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
906 crate opaque_type_values: VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>,
909 /// A collection of region constraints that must be satisfied for the
910 /// program to be considered well-typed.
911 crate struct MirTypeckRegionConstraints<'tcx> {
912 /// Maps from a `ty::Placeholder` to the corresponding
913 /// `PlaceholderIndex` bit that we will use for it.
915 /// To keep everything in sync, do not insert this set
916 /// directly. Instead, use the `placeholder_region` helper.
917 crate placeholder_indices: PlaceholderIndices,
919 /// Each time we add a placeholder to `placeholder_indices`, we
920 /// also create a corresponding "representative" region vid for
921 /// that wraps it. This vector tracks those. This way, when we
922 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
923 /// the same underlying `RegionVid`.
924 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
926 /// In general, the type-checker is not responsible for enforcing
927 /// liveness constraints; this job falls to the region inferencer,
928 /// which performs a liveness analysis. However, in some limited
929 /// cases, the MIR type-checker creates temporary regions that do
930 /// not otherwise appear in the MIR -- in particular, the
931 /// late-bound regions that it instantiates at call-sites -- and
932 /// hence it must report on their liveness constraints.
933 crate liveness_constraints: LivenessValues<RegionVid>,
935 crate outlives_constraints: OutlivesConstraintSet<'tcx>,
937 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
939 crate closure_bounds_mapping:
940 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
942 crate universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
944 crate type_tests: Vec<TypeTest<'tcx>>,
947 impl MirTypeckRegionConstraints<'tcx> {
948 fn placeholder_region(
950 infcx: &InferCtxt<'_, 'tcx>,
951 placeholder: ty::PlaceholderRegion,
952 ) -> ty::Region<'tcx> {
953 let placeholder_index = self.placeholder_indices.insert(placeholder);
954 match self.placeholder_index_to_region.get(placeholder_index) {
957 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
958 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
959 self.placeholder_index_to_region.push(region);
966 /// The `Locations` type summarizes *where* region constraints are
967 /// required to hold. Normally, this is at a particular point which
968 /// created the obligation, but for constraints that the user gave, we
969 /// want the constraint to hold at all points.
970 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
972 /// Indicates that a type constraint should always be true. This
973 /// is particularly important in the new borrowck analysis for
974 /// things like the type of the return slot. Consider this
978 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
980 /// return &y; // error
984 /// Here, we wind up with the signature from the return type being
985 /// something like `&'1 u32` where `'1` is a universal region. But
986 /// the type of the return slot `_0` is something like `&'2 u32`
987 /// where `'2` is an existential region variable. The type checker
988 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
989 /// older NLL analysis, we required this only at the entry point
990 /// to the function. By the nature of the constraints, this wound
991 /// up propagating to all points reachable from start (because
992 /// `'1` -- as a universal region -- is live everywhere). In the
993 /// newer analysis, though, this doesn't work: `_0` is considered
994 /// dead at the start (it has no usable value) and hence this type
995 /// equality is basically a no-op. Then, later on, when we do `_0
996 /// = &'3 y`, that region `'3` never winds up related to the
997 /// universal region `'1` and hence no error occurs. Therefore, we
998 /// use Locations::All instead, which ensures that the `'1` and
999 /// `'2` are equal everything. We also use this for other
1000 /// user-given type annotations; e.g., if the user wrote `let mut
1001 /// x: &'static u32 = ...`, we would ensure that all values
1002 /// assigned to `x` are of `'static` lifetime.
1004 /// The span points to the place the constraint arose. For example,
1005 /// it points to the type in a user-given type annotation. If
1006 /// there's no sensible span then it's DUMMY_SP.
1009 /// An outlives constraint that only has to hold at a single location,
1010 /// usually it represents a point where references flow from one spot to
1011 /// another (e.g., `x = y`)
1016 pub fn from_location(&self) -> Option<Location> {
1018 Locations::All(_) => None,
1019 Locations::Single(from_location) => Some(*from_location),
1023 /// Gets a span representing the location.
1024 pub fn span(&self, body: &Body<'_>) -> Span {
1026 Locations::All(span) => *span,
1027 Locations::Single(l) => body.source_info(*l).span,
1032 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1034 infcx: &'a InferCtxt<'a, 'tcx>,
1035 body: &'a Body<'tcx>,
1036 param_env: ty::ParamEnv<'tcx>,
1037 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1038 implicit_region_bound: ty::Region<'tcx>,
1039 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1041 let mut checker = Self {
1043 last_span: DUMMY_SP,
1045 user_type_annotations: &body.user_type_annotations,
1048 implicit_region_bound,
1050 reported_errors: Default::default(),
1052 checker.check_user_type_annotations();
1056 fn unsized_feature_enabled(&self) -> bool {
1057 let features = self.tcx().features();
1058 features.unsized_locals || features.unsized_fn_params
1061 /// Equate the inferred type and the annotated type for user type annotations
1062 fn check_user_type_annotations(&mut self) {
1064 "check_user_type_annotations: user_type_annotations={:?}",
1065 self.user_type_annotations
1067 for user_annotation in self.user_type_annotations {
1068 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1069 let inferred_ty = self.normalize(inferred_ty, Locations::All(span));
1070 let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1072 UserType::Ty(mut ty) => {
1073 ty = self.normalize(ty, Locations::All(span));
1075 if let Err(terr) = self.eq_types(
1078 Locations::All(span),
1079 ConstraintCategory::BoringNoLocation,
1084 "bad user type ({:?} = {:?}): {:?}",
1091 self.prove_predicate(
1092 ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into()))
1093 .to_predicate(self.tcx()),
1094 Locations::All(span),
1095 ConstraintCategory::TypeAnnotation,
1098 UserType::TypeOf(def_id, user_substs) => {
1099 if let Err(terr) = self.fully_perform_op(
1100 Locations::All(span),
1101 ConstraintCategory::BoringNoLocation,
1102 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1111 "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}",
1115 self.tcx().type_of(def_id),
1124 #[instrument(skip(self, data), level = "debug")]
1125 fn push_region_constraints(
1127 locations: Locations,
1128 category: ConstraintCategory,
1129 data: &QueryRegionConstraints<'tcx>,
1131 debug!("constraints generated: {:#?}", data);
1133 constraint_conversion::ConstraintConversion::new(
1135 self.borrowck_context.universal_regions,
1136 self.region_bound_pairs,
1137 Some(self.implicit_region_bound),
1141 &mut self.borrowck_context.constraints,
1146 /// Try to relate `sub <: sup`
1151 locations: Locations,
1152 category: ConstraintCategory,
1154 // Use this order of parameters because the sup type is usually the
1155 // "expected" type in diagnostics.
1156 self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
1163 locations: Locations,
1164 category: ConstraintCategory,
1166 self.relate_types(expected, ty::Variance::Invariant, found, locations, category)
1169 #[instrument(skip(self), level = "debug")]
1170 fn relate_type_and_user_type(
1174 user_ty: &UserTypeProjection,
1175 locations: Locations,
1176 category: ConstraintCategory,
1178 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1179 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1181 let tcx = self.infcx.tcx;
1183 for proj in &user_ty.projs {
1184 let projected_ty = curr_projected_ty.projection_ty_core(
1188 |this, field, &()| {
1189 let ty = this.field_ty(tcx, field);
1190 self.normalize(ty, locations)
1193 curr_projected_ty = projected_ty;
1196 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1197 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1200 let ty = curr_projected_ty.ty;
1201 self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1206 /// Equates a type `anon_ty` that may contain opaque types whose
1207 /// values are to be inferred by the MIR.
1209 /// The type `revealed_ty` contains the same type as `anon_ty`, but with the
1210 /// hidden types for impl traits revealed.
1214 /// Consider a piece of code like
1217 /// type Foo<U> = impl Debug;
1219 /// fn foo<T: Debug>(t: T) -> Box<Foo<T>> {
1220 /// Box::new((t, 22_u32))
1224 /// Here, the function signature would be something like
1225 /// `fn(T) -> Box<impl Debug>`. The MIR return slot would have
1226 /// the type with the opaque type revealed, so `Box<(T, u32)>`.
1228 /// In terms of our function parameters:
1230 /// * `anon_ty` would be `Box<Foo<T>>` where `Foo<T>` is an opaque type
1231 /// scoped to this function (note that it is parameterized by the
1232 /// generics of `foo`). Note that `anon_ty` is not just the opaque type,
1233 /// but the entire return type (which may contain opaque types within it).
1234 /// * `revealed_ty` would be `Box<(T, u32)>`
1235 #[instrument(skip(self), level = "debug")]
1236 fn eq_opaque_type_and_type(
1238 revealed_ty: Ty<'tcx>,
1240 locations: Locations,
1241 category: ConstraintCategory,
1243 // Fast path for the common case.
1244 if !anon_ty.has_opaque_types() {
1245 if let Err(terr) = self.eq_types(anon_ty, revealed_ty, locations, category) {
1249 "eq_opaque_type_and_type: `{:?}=={:?}` failed with `{:?}`",
1258 let param_env = self.param_env;
1259 let body = self.body;
1260 let mir_def_id = body.source.def_id().expect_local();
1262 debug!(?mir_def_id);
1263 self.fully_perform_op(
1268 let mut obligations = ObligationAccumulator::default();
1270 let dummy_body_id = hir::CRATE_HIR_ID;
1272 // Replace the opaque types defined by this function with
1273 // inference variables, creating a map. In our example above,
1274 // this would transform the type `Box<Foo<T>>` (where `Foo` is an opaque type)
1275 // to `Box<?T>`, returning an `opaque_type_map` mapping `{Foo<T> -> ?T}`.
1276 // (Note that the key of the map is both the def-id of `Foo` along with
1277 // any generic parameters.)
1278 let output_ty = obligations.add(infcx.instantiate_opaque_types(
1282 locations.span(body),
1284 debug!(?output_ty, ?revealed_ty);
1286 // Make sure that the inferred types are well-formed. I'm
1287 // not entirely sure this is needed (the HIR type check
1288 // didn't do this) but it seems sensible to prevent opaque
1289 // types hiding ill-formed types.
1290 obligations.obligations.push(traits::Obligation::new(
1291 ObligationCause::dummy(),
1293 ty::Binder::dummy(ty::PredicateKind::WellFormed(revealed_ty.into()))
1294 .to_predicate(infcx.tcx),
1298 .at(&ObligationCause::dummy(), param_env)
1299 .eq(output_ty, revealed_ty)?,
1304 Ok(InferOk { value: (), obligations: obligations.into_vec() })
1306 || "input_output".to_string(),
1310 // Finally, if we instantiated the anon types successfully, we
1311 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1312 // prove that `T: Iterator` where `T` is the type we
1313 // instantiated it with).
1314 let opaque_type_map = self.infcx.inner.borrow().opaque_types.clone();
1315 for (opaque_type_key, opaque_decl) in opaque_type_map {
1316 self.fully_perform_op(
1318 ConstraintCategory::OpaqueType,
1321 infcx.constrain_opaque_type(opaque_type_key, &opaque_decl);
1322 Ok(InferOk { value: (), obligations: vec![] })
1324 || "opaque_type_map".to_string(),
1331 fn tcx(&self) -> TyCtxt<'tcx> {
1335 #[instrument(skip(self, body, location), level = "debug")]
1336 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1337 let tcx = self.tcx();
1339 StatementKind::Assign(box (ref place, ref rv)) => {
1340 // Assignments to temporaries are not "interesting";
1341 // they are not caused by the user, but rather artifacts
1342 // of lowering. Assignments to other sorts of places *are* interesting
1344 let category = match place.as_local() {
1345 Some(RETURN_PLACE) => {
1346 if let BorrowCheckContext {
1348 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1350 } = self.borrowck_context
1352 if tcx.is_static(*def_id) {
1353 ConstraintCategory::UseAsStatic
1355 ConstraintCategory::UseAsConst
1358 ConstraintCategory::Return(ReturnConstraint::Normal)
1363 body.local_decls[l].local_info,
1364 Some(box LocalInfo::AggregateTemp)
1367 ConstraintCategory::Usage
1369 Some(l) if !body.local_decls[l].is_user_variable() => {
1370 ConstraintCategory::Boring
1372 _ => ConstraintCategory::Assignment,
1375 "assignment category: {:?} {:?}",
1377 place.as_local().map(|l| &body.local_decls[l])
1380 let place_ty = place.ty(body, tcx).ty;
1381 let place_ty = self.normalize(place_ty, location);
1382 let rv_ty = rv.ty(body, tcx);
1383 let rv_ty = self.normalize(rv_ty, location);
1385 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1390 "bad assignment ({:?} = {:?}): {:?}",
1397 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1398 if let Err(terr) = self.relate_type_and_user_type(
1400 ty::Variance::Invariant,
1401 &UserTypeProjection { base: annotation_index, projs: vec![] },
1402 location.to_locations(),
1403 ConstraintCategory::Boring,
1405 let annotation = &self.user_type_annotations[annotation_index];
1409 "bad user type on rvalue ({:?} = {:?}): {:?}",
1417 self.check_rvalue(body, rv, location);
1418 if !self.unsized_feature_enabled() {
1419 let trait_ref = ty::TraitRef {
1420 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1421 substs: tcx.mk_substs_trait(place_ty, &[]),
1423 self.prove_trait_ref(
1425 location.to_locations(),
1426 ConstraintCategory::SizedBound,
1430 StatementKind::SetDiscriminant { ref place, variant_index } => {
1431 let place_type = place.ty(body, tcx).ty;
1432 let adt = match place_type.kind() {
1433 ty::Adt(adt, _) if adt.is_enum() => adt,
1436 stmt.source_info.span,
1437 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1443 if variant_index.as_usize() >= adt.variants.len() {
1445 stmt.source_info.span,
1446 "bad set discriminant ({:?} = {:?}): value of of range",
1452 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1453 let place_ty = place.ty(body, tcx).ty;
1454 if let Err(terr) = self.relate_type_and_user_type(
1458 Locations::All(stmt.source_info.span),
1459 ConstraintCategory::TypeAnnotation,
1461 let annotation = &self.user_type_annotations[projection.base];
1465 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1473 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
1476 stmt.source_info.span,
1477 "Unexpected StatementKind::CopyNonOverlapping, should only appear after lowering_intrinsics",
1479 StatementKind::FakeRead(..)
1480 | StatementKind::StorageLive(..)
1481 | StatementKind::StorageDead(..)
1482 | StatementKind::LlvmInlineAsm { .. }
1483 | StatementKind::Retag { .. }
1484 | StatementKind::Coverage(..)
1485 | StatementKind::Nop => {}
1489 #[instrument(skip(self, body, term_location), level = "debug")]
1490 fn check_terminator(
1493 term: &Terminator<'tcx>,
1494 term_location: Location,
1496 let tcx = self.tcx();
1498 TerminatorKind::Goto { .. }
1499 | TerminatorKind::Resume
1500 | TerminatorKind::Abort
1501 | TerminatorKind::Return
1502 | TerminatorKind::GeneratorDrop
1503 | TerminatorKind::Unreachable
1504 | TerminatorKind::Drop { .. }
1505 | TerminatorKind::FalseEdge { .. }
1506 | TerminatorKind::FalseUnwind { .. }
1507 | TerminatorKind::InlineAsm { .. } => {
1508 // no checks needed for these
1511 TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1512 let place_ty = place.ty(body, tcx).ty;
1513 let rv_ty = value.ty(body, tcx);
1515 let locations = term_location.to_locations();
1517 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1522 "bad DropAndReplace ({:?} = {:?}): {:?}",
1529 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1530 let discr_ty = discr.ty(body, tcx);
1531 if let Err(terr) = self.sub_types(
1534 term_location.to_locations(),
1535 ConstraintCategory::Assignment,
1540 "bad SwitchInt ({:?} on {:?}): {:?}",
1546 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1547 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1549 // FIXME: check the values
1551 TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1552 let func_ty = func.ty(body, tcx);
1553 debug!("check_terminator: call, func_ty={:?}", func_ty);
1554 let sig = match func_ty.kind() {
1555 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1557 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1561 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1562 term.source_info.span,
1563 LateBoundRegionConversionTime::FnCall,
1566 let sig = self.normalize(sig, term_location);
1567 self.check_call_dest(body, term, &sig, destination, term_location);
1569 self.prove_predicates(
1570 sig.inputs_and_output
1572 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1573 term_location.to_locations(),
1574 ConstraintCategory::Boring,
1577 // The ordinary liveness rules will ensure that all
1578 // regions in the type of the callee are live here. We
1579 // then further constrain the late-bound regions that
1580 // were instantiated at the call site to be live as
1581 // well. The resulting is that all the input (and
1582 // output) types in the signature must be live, since
1583 // all the inputs that fed into it were live.
1584 for &late_bound_region in map.values() {
1586 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1587 self.borrowck_context
1589 .liveness_constraints
1590 .add_element(region_vid, term_location);
1593 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1595 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1596 let cond_ty = cond.ty(body, tcx);
1597 if cond_ty != tcx.types.bool {
1598 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1601 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1602 if len.ty(body, tcx) != tcx.types.usize {
1603 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1605 if index.ty(body, tcx) != tcx.types.usize {
1606 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1610 TerminatorKind::Yield { ref value, .. } => {
1611 let value_ty = value.ty(body, tcx);
1612 match body.yield_ty() {
1613 None => span_mirbug!(self, term, "yield in non-generator"),
1615 if let Err(terr) = self.sub_types(
1618 term_location.to_locations(),
1619 ConstraintCategory::Yield,
1624 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1639 term: &Terminator<'tcx>,
1640 sig: &ty::FnSig<'tcx>,
1641 destination: &Option<(Place<'tcx>, BasicBlock)>,
1642 term_location: Location,
1644 let tcx = self.tcx();
1645 match *destination {
1646 Some((ref dest, _target_block)) => {
1647 let dest_ty = dest.ty(body, tcx).ty;
1648 let dest_ty = self.normalize(dest_ty, term_location);
1649 let category = match dest.as_local() {
1650 Some(RETURN_PLACE) => {
1651 if let BorrowCheckContext {
1653 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1655 } = self.borrowck_context
1657 if tcx.is_static(*def_id) {
1658 ConstraintCategory::UseAsStatic
1660 ConstraintCategory::UseAsConst
1663 ConstraintCategory::Return(ReturnConstraint::Normal)
1666 Some(l) if !body.local_decls[l].is_user_variable() => {
1667 ConstraintCategory::Boring
1669 _ => ConstraintCategory::Assignment,
1672 let locations = term_location.to_locations();
1674 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1678 "call dest mismatch ({:?} <- {:?}): {:?}",
1685 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1686 // this check is done at `check_local`.
1687 if self.unsized_feature_enabled() {
1688 let span = term.source_info.span;
1689 self.ensure_place_sized(dest_ty, span);
1695 .conservative_is_privately_uninhabited(self.param_env.and(sig.output()))
1697 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1703 fn check_call_inputs(
1706 term: &Terminator<'tcx>,
1707 sig: &ty::FnSig<'tcx>,
1708 args: &[Operand<'tcx>],
1709 term_location: Location,
1710 from_hir_call: bool,
1712 debug!("check_call_inputs({:?}, {:?})", sig, args);
1713 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1714 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1716 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1717 let op_arg_ty = op_arg.ty(body, self.tcx());
1718 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1719 let category = if from_hir_call {
1720 ConstraintCategory::CallArgument
1722 ConstraintCategory::Boring
1725 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1730 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1740 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1741 let is_cleanup = block_data.is_cleanup;
1742 self.last_span = block_data.terminator().source_info.span;
1743 match block_data.terminator().kind {
1744 TerminatorKind::Goto { target } => {
1745 self.assert_iscleanup(body, block_data, target, is_cleanup)
1747 TerminatorKind::SwitchInt { ref targets, .. } => {
1748 for target in targets.all_targets() {
1749 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1752 TerminatorKind::Resume => {
1754 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1757 TerminatorKind::Abort => {
1759 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1762 TerminatorKind::Return => {
1764 span_mirbug!(self, block_data, "return on cleanup block")
1767 TerminatorKind::GeneratorDrop { .. } => {
1769 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1772 TerminatorKind::Yield { resume, drop, .. } => {
1774 span_mirbug!(self, block_data, "yield in cleanup block")
1776 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1777 if let Some(drop) = drop {
1778 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1781 TerminatorKind::Unreachable => {}
1782 TerminatorKind::Drop { target, unwind, .. }
1783 | TerminatorKind::DropAndReplace { target, unwind, .. }
1784 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1785 self.assert_iscleanup(body, block_data, target, is_cleanup);
1786 if let Some(unwind) = unwind {
1788 span_mirbug!(self, block_data, "unwind on cleanup block")
1790 self.assert_iscleanup(body, block_data, unwind, true);
1793 TerminatorKind::Call { ref destination, cleanup, .. } => {
1794 if let &Some((_, target)) = destination {
1795 self.assert_iscleanup(body, block_data, target, is_cleanup);
1797 if let Some(cleanup) = cleanup {
1799 span_mirbug!(self, block_data, "cleanup on cleanup block")
1801 self.assert_iscleanup(body, block_data, cleanup, true);
1804 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1805 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1806 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1808 TerminatorKind::FalseUnwind { real_target, unwind } => {
1809 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1810 if let Some(unwind) = unwind {
1812 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1814 self.assert_iscleanup(body, block_data, unwind, true);
1817 TerminatorKind::InlineAsm { destination, .. } => {
1818 if let Some(target) = destination {
1819 self.assert_iscleanup(body, block_data, target, is_cleanup);
1825 fn assert_iscleanup(
1828 ctxt: &dyn fmt::Debug,
1832 if body[bb].is_cleanup != iscleanuppad {
1833 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1837 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1838 match body.local_kind(local) {
1839 LocalKind::ReturnPointer | LocalKind::Arg => {
1840 // return values of normal functions are required to be
1841 // sized by typeck, but return values of ADT constructors are
1842 // not because we don't include a `Self: Sized` bounds on them.
1844 // Unbound parts of arguments were never required to be Sized
1845 // - maybe we should make that a warning.
1848 LocalKind::Var | LocalKind::Temp => {}
1851 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1852 // and nullary ops are checked in `check_call_dest`.
1853 if !self.unsized_feature_enabled() {
1854 let span = local_decl.source_info.span;
1855 let ty = local_decl.ty;
1856 self.ensure_place_sized(ty, span);
1860 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1861 let tcx = self.tcx();
1863 // Erase the regions from `ty` to get a global type. The
1864 // `Sized` bound in no way depends on precise regions, so this
1865 // shouldn't affect `is_sized`.
1866 let erased_ty = tcx.erase_regions(ty);
1867 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1868 // in current MIR construction, all non-control-flow rvalue
1869 // expressions evaluate through `as_temp` or `into` a return
1870 // slot or local, so to find all unsized rvalues it is enough
1871 // to check all temps, return slots and locals.
1872 if self.reported_errors.replace((ty, span)).is_none() {
1873 let mut diag = struct_span_err!(
1877 "cannot move a value of type {0}: the size of {0} \
1878 cannot be statically determined",
1882 // While this is located in `nll::typeck` this error is not
1883 // an NLL error, it's a required check to prevent creation
1884 // of unsized rvalues in a call expression.
1890 fn aggregate_field_ty(
1892 ak: &AggregateKind<'tcx>,
1895 ) -> Result<Ty<'tcx>, FieldAccessError> {
1896 let tcx = self.tcx();
1899 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1900 let variant = &def.variants[variant_index];
1901 let adj_field_index = active_field_index.unwrap_or(field_index);
1902 if let Some(field) = variant.fields.get(adj_field_index) {
1903 Ok(self.normalize(field.ty(tcx, substs), location))
1905 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1908 AggregateKind::Closure(_, substs) => {
1909 match substs.as_closure().upvar_tys().nth(field_index) {
1911 None => Err(FieldAccessError::OutOfRange {
1912 field_count: substs.as_closure().upvar_tys().count(),
1916 AggregateKind::Generator(_, substs, _) => {
1917 // It doesn't make sense to look at a field beyond the prefix;
1918 // these require a variant index, and are not initialized in
1919 // aggregate rvalues.
1920 match substs.as_generator().prefix_tys().nth(field_index) {
1922 None => Err(FieldAccessError::OutOfRange {
1923 field_count: substs.as_generator().prefix_tys().count(),
1927 AggregateKind::Array(ty) => Ok(ty),
1928 AggregateKind::Tuple => {
1929 unreachable!("This should have been covered in check_rvalues");
1934 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1935 let tcx = self.tcx();
1938 Rvalue::Aggregate(ak, ops) => {
1939 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1942 Rvalue::Repeat(operand, len) => {
1943 // If the length cannot be evaluated we must assume that the length can be larger
1945 // If the length is larger than 1, the repeat expression will need to copy the
1946 // element, so we require the `Copy` trait.
1947 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1949 Operand::Copy(..) | Operand::Constant(..) => {
1950 // These are always okay: direct use of a const, or a value that can evidently be copied.
1952 Operand::Move(place) => {
1953 // Make sure that repeated elements implement `Copy`.
1954 let span = body.source_info(location).span;
1955 let ty = operand.ty(body, tcx);
1956 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1957 let ccx = ConstCx::new_with_param_env(tcx, body, self.param_env);
1959 is_const_fn_in_array_repeat_expression(&ccx, &place, &body);
1961 debug!("check_rvalue: is_const_fn={:?}", is_const_fn);
1963 let def_id = body.source.def_id().expect_local();
1964 let obligation = traits::Obligation::new(
1965 ObligationCause::new(
1967 self.tcx().hir().local_def_id_to_hir_id(def_id),
1968 traits::ObligationCauseCode::RepeatVec(is_const_fn),
1971 ty::Binder::dummy(ty::TraitRef::new(
1972 self.tcx().require_lang_item(
1974 Some(self.last_span),
1976 tcx.mk_substs_trait(ty, &[]),
1979 .to_predicate(self.tcx()),
1981 self.infcx.report_selection_error(
1984 &traits::SelectionError::Unimplemented,
1993 Rvalue::NullaryOp(_, ty) | Rvalue::ShallowInitBox(_, ty) => {
1994 let trait_ref = ty::TraitRef {
1995 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1996 substs: tcx.mk_substs_trait(ty, &[]),
1999 self.prove_trait_ref(
2001 location.to_locations(),
2002 ConstraintCategory::SizedBound,
2006 Rvalue::Cast(cast_kind, op, ty) => {
2008 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2009 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2011 // The type that we see in the fcx is like
2012 // `foo::<'a, 'b>`, where `foo` is the path to a
2013 // function definition. When we extract the
2014 // signature, it comes from the `fn_sig` query,
2015 // and hence may contain unnormalized results.
2016 let fn_sig = self.normalize(fn_sig, location);
2018 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2020 if let Err(terr) = self.eq_types(
2023 location.to_locations(),
2024 ConstraintCategory::Cast,
2029 "equating {:?} with {:?} yields {:?}",
2037 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2038 let sig = match op.ty(body, tcx).kind() {
2039 ty::Closure(_, substs) => substs.as_closure().sig(),
2042 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
2044 if let Err(terr) = self.eq_types(
2047 location.to_locations(),
2048 ConstraintCategory::Cast,
2053 "equating {:?} with {:?} yields {:?}",
2061 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2062 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2064 // The type that we see in the fcx is like
2065 // `foo::<'a, 'b>`, where `foo` is the path to a
2066 // function definition. When we extract the
2067 // signature, it comes from the `fn_sig` query,
2068 // and hence may contain unnormalized results.
2069 let fn_sig = self.normalize(fn_sig, location);
2071 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2073 if let Err(terr) = self.eq_types(
2076 location.to_locations(),
2077 ConstraintCategory::Cast,
2082 "equating {:?} with {:?} yields {:?}",
2090 CastKind::Pointer(PointerCast::Unsize) => {
2092 let trait_ref = ty::TraitRef {
2094 .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2095 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2098 self.prove_trait_ref(
2100 location.to_locations(),
2101 ConstraintCategory::Cast,
2105 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2106 let ty_from = match op.ty(body, tcx).kind() {
2107 ty::RawPtr(ty::TypeAndMut {
2109 mutbl: hir::Mutability::Mut,
2115 "unexpected base type for cast {:?}",
2121 let ty_to = match ty.kind() {
2122 ty::RawPtr(ty::TypeAndMut {
2124 mutbl: hir::Mutability::Not,
2130 "unexpected target type for cast {:?}",
2136 if let Err(terr) = self.sub_types(
2139 location.to_locations(),
2140 ConstraintCategory::Cast,
2145 "relating {:?} with {:?} yields {:?}",
2153 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2154 let ty_from = op.ty(body, tcx);
2156 let opt_ty_elem_mut = match ty_from.kind() {
2157 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2158 match array_ty.kind() {
2159 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2166 let (ty_elem, ty_mut) = match opt_ty_elem_mut {
2167 Some(ty_elem_mut) => ty_elem_mut,
2172 "ArrayToPointer cast from unexpected type {:?}",
2179 let (ty_to, ty_to_mut) = match ty.kind() {
2180 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2187 "ArrayToPointer cast to unexpected type {:?}",
2194 if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2198 "ArrayToPointer cast from const {:?} to mut {:?}",
2205 if let Err(terr) = self.sub_types(
2208 location.to_locations(),
2209 ConstraintCategory::Cast,
2214 "relating {:?} with {:?} yields {:?}",
2223 let ty_from = op.ty(body, tcx);
2224 let cast_ty_from = CastTy::from_ty(ty_from);
2225 let cast_ty_to = CastTy::from_ty(ty);
2226 match (cast_ty_from, cast_ty_to) {
2228 | (_, None | Some(CastTy::FnPtr))
2229 | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2230 | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => {
2231 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2234 Some(CastTy::Int(_)),
2235 Some(CastTy::Int(_) | CastTy::Float | CastTy::Ptr(_)),
2237 | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float))
2238 | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_)))
2239 | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (),
2245 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2246 self.add_reborrow_constraint(&body, location, region, borrowed_place);
2250 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2253 let ty_left = left.ty(body, tcx);
2254 match ty_left.kind() {
2255 // Types with regions are comparable if they have a common super-type.
2256 ty::RawPtr(_) | ty::FnPtr(_) => {
2257 let ty_right = right.ty(body, tcx);
2258 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2259 kind: TypeVariableOriginKind::MiscVariable,
2260 span: body.source_info(location).span,
2265 location.to_locations(),
2266 ConstraintCategory::Boring,
2268 .unwrap_or_else(|err| {
2269 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2271 if let Err(terr) = self.sub_types(
2274 location.to_locations(),
2275 ConstraintCategory::Boring,
2280 "unexpected comparison types {:?} and {:?} yields {:?}",
2287 // For types with no regions we can just check that the
2288 // both operands have the same type.
2289 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2290 if ty_left == right.ty(body, tcx) => {}
2291 // Other types are compared by trait methods, not by
2292 // `Rvalue::BinaryOp`.
2296 "unexpected comparison types {:?} and {:?}",
2303 Rvalue::AddressOf(..)
2304 | Rvalue::ThreadLocalRef(..)
2307 | Rvalue::BinaryOp(..)
2308 | Rvalue::CheckedBinaryOp(..)
2309 | Rvalue::UnaryOp(..)
2310 | Rvalue::Discriminant(..) => {}
2314 /// If this rvalue supports a user-given type annotation, then
2315 /// extract and return it. This represents the final type of the
2316 /// rvalue and will be unified with the inferred type.
2317 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2320 | Rvalue::ThreadLocalRef(_)
2321 | Rvalue::Repeat(..)
2323 | Rvalue::AddressOf(..)
2326 | Rvalue::ShallowInitBox(..)
2327 | Rvalue::BinaryOp(..)
2328 | Rvalue::CheckedBinaryOp(..)
2329 | Rvalue::NullaryOp(..)
2330 | Rvalue::UnaryOp(..)
2331 | Rvalue::Discriminant(..) => None,
2333 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2334 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2335 AggregateKind::Array(_) => None,
2336 AggregateKind::Tuple => None,
2337 AggregateKind::Closure(_, _) => None,
2338 AggregateKind::Generator(_, _, _) => None,
2343 fn check_aggregate_rvalue(
2346 rvalue: &Rvalue<'tcx>,
2347 aggregate_kind: &AggregateKind<'tcx>,
2348 operands: &[Operand<'tcx>],
2351 let tcx = self.tcx();
2353 self.prove_aggregate_predicates(aggregate_kind, location);
2355 if *aggregate_kind == AggregateKind::Tuple {
2356 // tuple rvalue field type is always the type of the op. Nothing to check here.
2360 for (i, operand) in operands.iter().enumerate() {
2361 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2362 Ok(field_ty) => field_ty,
2363 Err(FieldAccessError::OutOfRange { field_count }) => {
2367 "accessed field #{} but variant only has {}",
2374 let operand_ty = operand.ty(body, tcx);
2375 let operand_ty = self.normalize(operand_ty, location);
2377 if let Err(terr) = self.sub_types(
2380 location.to_locations(),
2381 ConstraintCategory::Boring,
2386 "{:?} is not a subtype of {:?}: {:?}",
2395 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2399 /// - `location`: the location `L` where the borrow expression occurs
2400 /// - `borrow_region`: the region `'a` associated with the borrow
2401 /// - `borrowed_place`: the place `P` being borrowed
2402 fn add_reborrow_constraint(
2406 borrow_region: ty::Region<'tcx>,
2407 borrowed_place: &Place<'tcx>,
2409 // These constraints are only meaningful during borrowck:
2410 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2411 self.borrowck_context;
2413 // In Polonius mode, we also push a `loan_issued_at` fact
2414 // linking the loan to the region (in some cases, though,
2415 // there is no loan associated with this borrow expression --
2416 // that occurs when we are borrowing an unsafe place, for
2418 if let Some(all_facts) = all_facts {
2419 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2420 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2421 let region_vid = borrow_region.to_region_vid();
2422 all_facts.loan_issued_at.push((
2425 location_table.mid_index(location),
2430 // If we are reborrowing the referent of another reference, we
2431 // need to add outlives relationships. In a case like `&mut
2432 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2433 // need to ensure that `'b: 'a`.
2436 "add_reborrow_constraint({:?}, {:?}, {:?})",
2437 location, borrow_region, borrowed_place
2440 let mut cursor = borrowed_place.projection.as_ref();
2441 let tcx = self.infcx.tcx;
2442 let field = path_utils::is_upvar_field_projection(
2444 &self.borrowck_context.upvars,
2445 borrowed_place.as_ref(),
2448 let category = if let Some(field) = field {
2449 let var_hir_id = self.borrowck_context.upvars[field.index()].place.get_root_variable();
2450 // FIXME(project-rfc-2229#8): Use Place for better diagnostics
2451 ConstraintCategory::ClosureUpvar(var_hir_id)
2453 ConstraintCategory::Boring
2456 while let [proj_base @ .., elem] = cursor {
2459 debug!("add_reborrow_constraint - iteration {:?}", elem);
2462 ProjectionElem::Deref => {
2463 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2465 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2466 match base_ty.kind() {
2467 ty::Ref(ref_region, _, mutbl) => {
2468 constraints.outlives_constraints.push(OutlivesConstraint {
2469 sup: ref_region.to_region_vid(),
2470 sub: borrow_region.to_region_vid(),
2471 locations: location.to_locations(),
2473 variance_info: ty::VarianceDiagInfo::default(),
2477 hir::Mutability::Not => {
2478 // Immutable reference. We don't need the base
2479 // to be valid for the entire lifetime of
2483 hir::Mutability::Mut => {
2484 // Mutable reference. We *do* need the base
2485 // to be valid, because after the base becomes
2486 // invalid, someone else can use our mutable deref.
2488 // This is in order to make the following function
2491 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2496 // As otherwise you could clone `&mut T` using the
2497 // following function:
2499 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2500 // let my_clone = unsafe_deref(&'a x);
2509 // deref of raw pointer, guaranteed to be valid
2512 ty::Adt(def, _) if def.is_box() => {
2513 // deref of `Box`, need the base to be valid - propagate
2515 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2518 ProjectionElem::Field(..)
2519 | ProjectionElem::Downcast(..)
2520 | ProjectionElem::Index(..)
2521 | ProjectionElem::ConstantIndex { .. }
2522 | ProjectionElem::Subslice { .. } => {
2523 // other field access
2529 fn prove_aggregate_predicates(
2531 aggregate_kind: &AggregateKind<'tcx>,
2534 let tcx = self.tcx();
2537 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2538 aggregate_kind, location
2541 let (def_id, instantiated_predicates) = match aggregate_kind {
2542 AggregateKind::Adt(def, _, substs, _, _) => {
2543 (def.did, tcx.predicates_of(def.did).instantiate(tcx, substs))
2546 // For closures, we have some **extra requirements** we
2548 // have to check. In particular, in their upvars and
2549 // signatures, closures often reference various regions
2550 // from the surrounding function -- we call those the
2551 // closure's free regions. When we borrow-check (and hence
2552 // region-check) closures, we may find that the closure
2553 // requires certain relationships between those free
2554 // regions. However, because those free regions refer to
2555 // portions of the CFG of their caller, the closure is not
2556 // in a position to verify those relationships. In that
2557 // case, the requirements get "propagated" to us, and so
2558 // we have to solve them here where we instantiate the
2561 // Despite the opacity of the previous parapgrah, this is
2562 // actually relatively easy to understand in terms of the
2563 // desugaring. A closure gets desugared to a struct, and
2564 // these extra requirements are basically like where
2565 // clauses on the struct.
2566 AggregateKind::Closure(def_id, substs)
2567 | AggregateKind::Generator(def_id, substs, _) => {
2568 (*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location))
2571 AggregateKind::Array(_) | AggregateKind::Tuple => {
2572 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2576 self.normalize_and_prove_instantiated_predicates(
2578 instantiated_predicates,
2579 location.to_locations(),
2583 fn prove_closure_bounds(
2587 substs: SubstsRef<'tcx>,
2589 ) -> ty::InstantiatedPredicates<'tcx> {
2590 if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2592 let closure_constraints = QueryRegionConstraints {
2593 outlives: closure_region_requirements.apply_requirements(
2599 // Presently, closures never propagate member
2600 // constraints to their parents -- they are enforced
2601 // locally. This is largely a non-issue as member
2602 // constraints only come from `-> impl Trait` and
2603 // friends which don't appear (thus far...) in
2605 member_constraints: vec![],
2608 let bounds_mapping = closure_constraints
2612 .filter_map(|(idx, constraint)| {
2613 let ty::OutlivesPredicate(k1, r2) =
2614 constraint.no_bound_vars().unwrap_or_else(|| {
2615 bug!("query_constraint {:?} contained bound vars", constraint,);
2619 GenericArgKind::Lifetime(r1) => {
2620 // constraint is r1: r2
2621 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2622 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2623 let outlives_requirements =
2624 &closure_region_requirements.outlives_requirements[idx];
2627 (outlives_requirements.category, outlives_requirements.blame_span),
2630 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2638 .closure_bounds_mapping
2639 .insert(location, bounds_mapping);
2640 assert!(existing.is_none(), "Multiple closures at the same location.");
2642 self.push_region_constraints(
2643 location.to_locations(),
2644 ConstraintCategory::ClosureBounds,
2645 &closure_constraints,
2649 tcx.predicates_of(def_id).instantiate(tcx, substs)
2652 #[instrument(skip(self, body), level = "debug")]
2653 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2654 self.last_span = body.span;
2657 for (local, local_decl) in body.local_decls.iter_enumerated() {
2658 self.check_local(&body, local, local_decl);
2661 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2662 let mut location = Location { block, statement_index: 0 };
2663 for stmt in &block_data.statements {
2664 if !stmt.source_info.span.is_dummy() {
2665 self.last_span = stmt.source_info.span;
2667 self.check_stmt(body, stmt, location);
2668 location.statement_index += 1;
2671 self.check_terminator(&body, block_data.terminator(), location);
2672 self.check_iscleanup(&body, block_data);
2677 trait NormalizeLocation: fmt::Debug + Copy {
2678 fn to_locations(self) -> Locations;
2681 impl NormalizeLocation for Locations {
2682 fn to_locations(self) -> Locations {
2687 impl NormalizeLocation for Location {
2688 fn to_locations(self) -> Locations {
2689 Locations::Single(self)
2693 #[derive(Debug, Default)]
2694 struct ObligationAccumulator<'tcx> {
2695 obligations: PredicateObligations<'tcx>,
2698 impl<'tcx> ObligationAccumulator<'tcx> {
2699 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2700 let InferOk { value, obligations } = value;
2701 self.obligations.extend(obligations);
2705 fn into_vec(self) -> PredicateObligations<'tcx> {