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::opaque_types::{GenerateMemberConstraints, InferCtxtExt};
40 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
41 use rustc_trait_selection::traits::query::type_op;
42 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
43 use rustc_trait_selection::traits::query::Fallible;
44 use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligations};
46 use rustc_const_eval::transform::{
47 check_consts::ConstCx, promote_consts::is_const_fn_in_array_repeat_expression,
49 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
50 use rustc_mir_dataflow::move_paths::MoveData;
51 use rustc_mir_dataflow::ResultsCursor;
54 borrow_set::BorrowSet,
55 constraints::{OutlivesConstraint, OutlivesConstraintSet},
56 diagnostics::UniverseInfo,
58 location::LocationTable,
59 member_constraints::MemberConstraintSet,
62 region_infer::values::{
63 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
65 region_infer::{ClosureRegionRequirementsExt, TypeTest},
66 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
67 universal_regions::{DefiningTy, UniversalRegions},
71 macro_rules! span_mirbug {
72 ($context:expr, $elem:expr, $($message:tt)*) => ({
73 $crate::type_check::mirbug(
77 "broken MIR in {:?} ({:?}): {}",
78 $context.body.source.def_id(),
80 format_args!($($message)*),
86 macro_rules! span_mirbug_and_err {
87 ($context:expr, $elem:expr, $($message:tt)*) => ({
89 span_mirbug!($context, $elem, $($message)*);
96 mod constraint_conversion;
97 pub mod free_region_relations;
102 /// Type checks the given `mir` in the context of the inference
103 /// context `infcx`. Returns any region constraints that have yet to
104 /// be proven. This result includes liveness constraints that
105 /// ensure that regions appearing in the types of all local variables
106 /// are live at all points where that local variable may later be
109 /// This phase of type-check ought to be infallible -- this is because
110 /// the original, HIR-based type-check succeeded. So if any errors
111 /// occur here, we will get a `bug!` reported.
115 /// - `infcx` -- inference context to use
116 /// - `param_env` -- parameter environment to use for trait solving
117 /// - `body` -- MIR body to type-check
118 /// - `promoted` -- map of promoted constants within `body`
119 /// - `universal_regions` -- the universal regions from `body`s function signature
120 /// - `location_table` -- MIR location map of `body`
121 /// - `borrow_set` -- information about borrows occurring in `body`
122 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
123 /// - `flow_inits` -- results of a maybe-init dataflow analysis
124 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
125 /// - `elements` -- MIR region map
126 pub(crate) fn type_check<'mir, 'tcx>(
127 infcx: &InferCtxt<'_, 'tcx>,
128 param_env: ty::ParamEnv<'tcx>,
130 promoted: &IndexVec<Promoted, Body<'tcx>>,
131 universal_regions: &Rc<UniversalRegions<'tcx>>,
132 location_table: &LocationTable,
133 borrow_set: &BorrowSet<'tcx>,
134 all_facts: &mut Option<AllFacts>,
135 flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
136 move_data: &MoveData<'tcx>,
137 elements: &Rc<RegionValueElements>,
138 upvars: &[Upvar<'tcx>],
139 ) -> MirTypeckResults<'tcx> {
140 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
141 let mut universe_causes = FxHashMap::default();
142 universe_causes.insert(ty::UniverseIndex::from_u32(0), UniverseInfo::other());
143 let mut constraints = MirTypeckRegionConstraints {
144 placeholder_indices: PlaceholderIndices::default(),
145 placeholder_index_to_region: IndexVec::default(),
146 liveness_constraints: LivenessValues::new(elements.clone()),
147 outlives_constraints: OutlivesConstraintSet::default(),
148 member_constraints: MemberConstraintSet::default(),
149 closure_bounds_mapping: Default::default(),
150 type_tests: Vec::default(),
155 universal_region_relations,
157 normalized_inputs_and_output,
158 } = free_region_relations::create(
161 Some(implicit_region_bound),
166 for u in ty::UniverseIndex::ROOT..infcx.universe() {
167 let info = UniverseInfo::other();
168 constraints.universe_causes.insert(u, info);
171 let mut borrowck_context = BorrowCheckContext {
176 constraints: &mut constraints,
180 let opaque_type_values = type_check_internal(
186 implicit_region_bound,
187 &mut borrowck_context,
188 &universal_region_relations,
190 cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
191 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
193 translate_outlives_facts(&mut cx);
194 let opaque_type_values = mem::take(&mut infcx.inner.borrow_mut().opaque_types);
198 .filter_map(|(opaque_type_key, mut decl)| {
199 decl.concrete_ty = infcx.resolve_vars_if_possible(decl.concrete_ty);
201 "finalized opaque type {:?} to {:#?}",
203 decl.concrete_ty.kind()
205 if decl.concrete_ty.has_infer_types_or_consts() {
206 infcx.tcx.sess.delay_span_bug(
208 &format!("could not resolve {:#?}", decl.concrete_ty.kind()),
210 decl.concrete_ty = infcx.tcx.ty_error();
212 let concrete_is_opaque = if let ty::Opaque(def_id, _) = decl.concrete_ty.kind()
214 *def_id == opaque_type_key.def_id
219 if concrete_is_opaque {
220 // We're using an opaque `impl Trait` type without
221 // 'revealing' it. For example, code like this:
223 // type Foo = impl Debug;
224 // fn foo1() -> Foo { ... }
225 // fn foo2() -> Foo { foo1() }
227 // In `foo2`, we're not revealing the type of `Foo` - we're
228 // just treating it as the opaque type.
230 // When this occurs, we do *not* want to try to equate
231 // the concrete type with the underlying defining type
232 // of the opaque type - this will always fail, since
233 // the defining type of an opaque type is always
234 // some other type (e.g. not itself)
235 // Essentially, none of the normal obligations apply here -
236 // we're just passing around some unknown opaque type,
237 // without actually looking at the underlying type it
238 // gets 'revealed' into
240 "eq_opaque_type_and_type: non-defining use of {:?}",
241 opaque_type_key.def_id,
245 Some((opaque_type_key, decl))
252 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
262 universal_region_relations,
267 fn type_check_internal<'a, 'tcx, R>(
268 infcx: &'a InferCtxt<'a, 'tcx>,
269 param_env: ty::ParamEnv<'tcx>,
270 body: &'a Body<'tcx>,
271 promoted: &'a IndexVec<Promoted, Body<'tcx>>,
272 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
273 implicit_region_bound: ty::Region<'tcx>,
274 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
275 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
276 extra: impl FnOnce(TypeChecker<'a, 'tcx>) -> R,
278 let mut checker = TypeChecker::new(
283 implicit_region_bound,
285 universal_region_relations,
287 let errors_reported = {
288 let mut verifier = TypeVerifier::new(&mut checker, body, promoted);
289 verifier.visit_body(&body);
290 verifier.errors_reported
293 if !errors_reported {
294 // if verifier failed, don't do further checks to avoid ICEs
295 checker.typeck_mir(body);
301 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
302 let cx = &mut typeck.borrowck_context;
303 if let Some(facts) = cx.all_facts {
304 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
305 let location_table = cx.location_table;
306 facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
307 |constraint: &OutlivesConstraint<'_>| {
308 if let Some(from_location) = constraint.locations.from_location() {
309 Either::Left(iter::once((
312 location_table.mid_index(from_location),
318 .map(move |location| (constraint.sup, constraint.sub, location)),
326 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
327 // We sometimes see MIR failures (notably predicate failures) due to
328 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
329 // to avoid reporting bugs in those cases.
330 tcx.sess.diagnostic().delay_span_bug(span, msg);
333 enum FieldAccessError {
334 OutOfRange { field_count: usize },
337 /// Verifies that MIR types are sane to not crash further checks.
339 /// The sanitize_XYZ methods here take an MIR object and compute its
340 /// type, calling `span_mirbug` and returning an error type if there
342 struct TypeVerifier<'a, 'b, 'tcx> {
343 cx: &'a mut TypeChecker<'b, 'tcx>,
344 body: &'b Body<'tcx>,
345 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
347 errors_reported: bool,
350 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
351 fn visit_span(&mut self, span: &Span) {
352 if !span.is_dummy() {
353 self.last_span = *span;
357 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
358 self.sanitize_place(place, location, context);
361 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
362 self.super_constant(constant, location);
363 let ty = self.sanitize_type(constant, constant.literal.ty());
365 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
366 let live_region_vid =
367 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
371 .liveness_constraints
372 .add_element(live_region_vid, location);
375 if let Some(annotation_index) = constant.user_ty {
376 if let Err(terr) = self.cx.relate_type_and_user_type(
377 constant.literal.ty(),
378 ty::Variance::Invariant,
379 &UserTypeProjection { base: annotation_index, projs: vec![] },
380 location.to_locations(),
381 ConstraintCategory::Boring,
383 let annotation = &self.cx.user_type_annotations[annotation_index];
387 "bad constant user type {:?} vs {:?}: {:?}",
389 constant.literal.ty(),
394 let tcx = self.tcx();
395 let maybe_uneval = match constant.literal {
396 ConstantKind::Ty(ct) => match ct.val {
397 ty::ConstKind::Unevaluated(uv) => Some(uv),
402 if let Some(uv) = maybe_uneval {
403 if let Some(promoted) = uv.promoted {
404 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
405 promoted: &Body<'tcx>,
408 if let Err(terr) = verifier.cx.eq_types(
411 location.to_locations(),
412 ConstraintCategory::Boring,
417 "bad promoted type ({:?}: {:?}): {:?}",
425 if !self.errors_reported {
426 let promoted_body = &self.promoted[promoted];
427 self.sanitize_promoted(promoted_body, location);
429 let promoted_ty = promoted_body.return_ty();
430 check_err(self, promoted_body, ty, promoted_ty);
433 if let Err(terr) = self.cx.fully_perform_op(
434 location.to_locations(),
435 ConstraintCategory::Boring,
436 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
437 constant.literal.ty(),
439 UserSubsts { substs: uv.substs(self.tcx()), user_self_ty: None },
445 "bad constant type {:?} ({:?})",
451 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
452 let unnormalized_ty = tcx.type_of(static_def_id);
453 let locations = location.to_locations();
454 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
455 let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty;
457 if let Err(terr) = self.cx.eq_types(
461 ConstraintCategory::Boring,
463 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
467 if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() {
468 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
469 self.cx.normalize_and_prove_instantiated_predicates(
471 instantiated_predicates,
472 location.to_locations(),
478 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
479 self.super_rvalue(rvalue, location);
480 let rval_ty = rvalue.ty(self.body, self.tcx());
481 self.sanitize_type(rvalue, rval_ty);
484 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
485 self.super_local_decl(local, local_decl);
486 self.sanitize_type(local_decl, local_decl.ty);
488 if let Some(user_ty) = &local_decl.user_ty {
489 for (user_ty, span) in user_ty.projections_and_spans() {
490 let ty = if !local_decl.is_nonref_binding() {
491 // If we have a binding of the form `let ref x: T = ..`
492 // then remove the outermost reference so we can check the
493 // type annotation for the remaining type.
494 if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
497 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
503 if let Err(terr) = self.cx.relate_type_and_user_type(
505 ty::Variance::Invariant,
507 Locations::All(*span),
508 ConstraintCategory::TypeAnnotation,
513 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
524 fn visit_body(&mut self, body: &Body<'tcx>) {
525 self.sanitize_type(&"return type", body.return_ty());
526 for local_decl in &body.local_decls {
527 self.sanitize_type(local_decl, local_decl.ty);
529 if self.errors_reported {
532 self.super_body(body);
536 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
538 cx: &'a mut TypeChecker<'b, 'tcx>,
539 body: &'b Body<'tcx>,
540 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
542 TypeVerifier { body, promoted, cx, last_span: body.span, errors_reported: false }
545 fn tcx(&self) -> TyCtxt<'tcx> {
549 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
550 if ty.has_escaping_bound_vars() || ty.references_error() {
551 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
557 /// Checks that the types internal to the `place` match up with
558 /// what would be expected.
563 context: PlaceContext,
565 debug!("sanitize_place: {:?}", place);
567 let mut place_ty = PlaceTy::from_ty(self.body.local_decls[place.local].ty);
569 for elem in place.projection.iter() {
570 if place_ty.variant_index.is_none() {
571 if place_ty.ty.references_error() {
572 assert!(self.errors_reported);
573 return PlaceTy::from_ty(self.tcx().ty_error());
576 place_ty = self.sanitize_projection(place_ty, elem, place, location);
579 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
580 let tcx = self.tcx();
581 let trait_ref = ty::TraitRef {
582 def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
583 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
586 // To have a `Copy` operand, the type `T` of the
587 // value must be `Copy`. Note that we prove that `T: Copy`,
588 // rather than using the `is_copy_modulo_regions`
589 // test. This is important because
590 // `is_copy_modulo_regions` ignores the resulting region
591 // obligations and assumes they pass. This can result in
592 // bounds from `Copy` impls being unsoundly ignored (e.g.,
593 // #29149). Note that we decide to use `Copy` before knowing
594 // whether the bounds fully apply: in effect, the rule is
595 // that if a value of some type could implement `Copy`, then
597 self.cx.prove_trait_ref(
599 location.to_locations(),
600 ConstraintCategory::CopyBound,
607 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
608 // Determine the constraints from the promoted MIR by running the type
609 // checker on the promoted MIR, then transfer the constraints back to
610 // the main MIR, changing the locations to the provided location.
612 let parent_body = mem::replace(&mut self.body, promoted_body);
614 // Use new sets of constraints and closure bounds so that we can
615 // modify their locations.
616 let all_facts = &mut None;
617 let mut constraints = Default::default();
618 let mut closure_bounds = Default::default();
619 let mut liveness_constraints =
620 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
621 // Don't try to add borrow_region facts for the promoted MIR
623 let mut swap_constraints = |this: &mut Self| {
624 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
626 &mut this.cx.borrowck_context.constraints.outlives_constraints,
630 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
634 &mut this.cx.borrowck_context.constraints.liveness_constraints,
635 &mut liveness_constraints,
639 swap_constraints(self);
641 self.visit_body(&promoted_body);
643 if !self.errors_reported {
644 // if verifier failed, don't do further checks to avoid ICEs
645 self.cx.typeck_mir(promoted_body);
648 self.body = parent_body;
649 // Merge the outlives constraints back in, at the given location.
650 swap_constraints(self);
652 let locations = location.to_locations();
653 for constraint in constraints.outlives().iter() {
654 let mut constraint = constraint.clone();
655 constraint.locations = locations;
656 if let ConstraintCategory::Return(_)
657 | ConstraintCategory::UseAsConst
658 | ConstraintCategory::UseAsStatic = constraint.category
660 // "Returning" from a promoted is an assignment to a
661 // temporary from the user's point of view.
662 constraint.category = ConstraintCategory::Boring;
664 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
666 for live_region in liveness_constraints.rows() {
670 .liveness_constraints
671 .add_element(live_region, location);
674 if !closure_bounds.is_empty() {
675 let combined_bounds_mapping =
676 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
681 .closure_bounds_mapping
682 .insert(location, combined_bounds_mapping);
683 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
687 fn sanitize_projection(
694 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
695 let tcx = self.tcx();
696 let base_ty = base.ty;
698 ProjectionElem::Deref => {
699 let deref_ty = base_ty.builtin_deref(true);
700 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
701 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
704 ProjectionElem::Index(i) => {
705 let index_ty = Place::from(i).ty(self.body, tcx).ty;
706 if index_ty != tcx.types.usize {
707 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
709 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
710 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
714 ProjectionElem::ConstantIndex { .. } => {
715 // consider verifying in-bounds
716 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
717 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
720 ProjectionElem::Subslice { from, to, from_end } => {
721 PlaceTy::from_ty(match base_ty.kind() {
722 ty::Array(inner, _) => {
723 assert!(!from_end, "array subslices should not use from_end");
724 tcx.mk_array(inner, to - from)
727 assert!(from_end, "slice subslices should use from_end");
730 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
733 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
734 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
735 if index.as_usize() >= adt_def.variants.len() {
736 PlaceTy::from_ty(span_mirbug_and_err!(
739 "cast to variant #{:?} but enum only has {:?}",
741 adt_def.variants.len()
744 PlaceTy { ty: base_ty, variant_index: Some(index) }
747 // We do not need to handle generators here, because this runs
748 // before the generator transform stage.
750 let ty = if let Some(name) = maybe_name {
751 span_mirbug_and_err!(
754 "can't downcast {:?} as {:?}",
759 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
764 ProjectionElem::Field(field, fty) => {
765 let fty = self.sanitize_type(place, fty);
766 match self.field_ty(place, base, field, location) {
768 let ty = self.cx.normalize(ty, location);
769 if let Err(terr) = self.cx.eq_types(
772 location.to_locations(),
773 ConstraintCategory::Boring,
778 "bad field access ({:?}: {:?}): {:?}",
785 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
788 "accessed field #{} but variant only has {}",
793 PlaceTy::from_ty(fty)
798 fn error(&mut self) -> Ty<'tcx> {
799 self.errors_reported = true;
800 self.tcx().ty_error()
805 parent: &dyn fmt::Debug,
806 base_ty: PlaceTy<'tcx>,
809 ) -> Result<Ty<'tcx>, FieldAccessError> {
810 let tcx = self.tcx();
812 let (variant, substs) = match base_ty {
813 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
814 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
815 ty::Generator(def_id, substs, _) => {
816 let mut variants = substs.as_generator().state_tys(def_id, tcx);
817 let mut variant = match variants.nth(variant_index.into()) {
820 "variant_index of generator out of range: {:?}/{:?}",
822 substs.as_generator().state_tys(def_id, tcx).count()
825 return match variant.nth(field.index()) {
827 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
830 _ => bug!("can't have downcast of non-adt non-generator type"),
832 PlaceTy { ty, variant_index: None } => match *ty.kind() {
833 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
834 (&adt_def.variants[VariantIdx::new(0)], substs)
836 ty::Closure(_, substs) => {
840 .tuple_element_ty(field.index())
843 None => Err(FieldAccessError::OutOfRange {
844 field_count: substs.as_closure().upvar_tys().count(),
848 ty::Generator(_, substs, _) => {
849 // Only prefix fields (upvars and current state) are
850 // accessible without a variant index.
851 return match substs.as_generator().prefix_tys().nth(field.index()) {
853 None => Err(FieldAccessError::OutOfRange {
854 field_count: substs.as_generator().prefix_tys().count(),
859 return match tys.get(field.index()) {
860 Some(&ty) => Ok(ty.expect_ty()),
861 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
865 return Ok(span_mirbug_and_err!(
868 "can't project out of {:?}",
875 if let Some(field) = variant.fields.get(field.index()) {
876 Ok(self.cx.normalize(field.ty(tcx, substs), location))
878 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
883 /// The MIR type checker. Visits the MIR and enforces all the
884 /// constraints needed for it to be valid and well-typed. Along the
885 /// way, it accrues region constraints -- these can later be used by
886 /// NLL region checking.
887 struct TypeChecker<'a, 'tcx> {
888 infcx: &'a InferCtxt<'a, 'tcx>,
889 param_env: ty::ParamEnv<'tcx>,
891 body: &'a Body<'tcx>,
892 /// User type annotations are shared between the main MIR and the MIR of
893 /// all of the promoted items.
894 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
895 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
896 implicit_region_bound: ty::Region<'tcx>,
897 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
898 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
899 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
902 struct BorrowCheckContext<'a, 'tcx> {
903 universal_regions: &'a UniversalRegions<'tcx>,
904 location_table: &'a LocationTable,
905 all_facts: &'a mut Option<AllFacts>,
906 borrow_set: &'a BorrowSet<'tcx>,
907 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
908 upvars: &'a [Upvar<'tcx>],
911 crate struct MirTypeckResults<'tcx> {
912 crate constraints: MirTypeckRegionConstraints<'tcx>,
913 crate universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
914 crate opaque_type_values: VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>,
917 /// A collection of region constraints that must be satisfied for the
918 /// program to be considered well-typed.
919 crate struct MirTypeckRegionConstraints<'tcx> {
920 /// Maps from a `ty::Placeholder` to the corresponding
921 /// `PlaceholderIndex` bit that we will use for it.
923 /// To keep everything in sync, do not insert this set
924 /// directly. Instead, use the `placeholder_region` helper.
925 crate placeholder_indices: PlaceholderIndices,
927 /// Each time we add a placeholder to `placeholder_indices`, we
928 /// also create a corresponding "representative" region vid for
929 /// that wraps it. This vector tracks those. This way, when we
930 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
931 /// the same underlying `RegionVid`.
932 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
934 /// In general, the type-checker is not responsible for enforcing
935 /// liveness constraints; this job falls to the region inferencer,
936 /// which performs a liveness analysis. However, in some limited
937 /// cases, the MIR type-checker creates temporary regions that do
938 /// not otherwise appear in the MIR -- in particular, the
939 /// late-bound regions that it instantiates at call-sites -- and
940 /// hence it must report on their liveness constraints.
941 crate liveness_constraints: LivenessValues<RegionVid>,
943 crate outlives_constraints: OutlivesConstraintSet<'tcx>,
945 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
947 crate closure_bounds_mapping:
948 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
950 crate universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
952 crate type_tests: Vec<TypeTest<'tcx>>,
955 impl MirTypeckRegionConstraints<'tcx> {
956 fn placeholder_region(
958 infcx: &InferCtxt<'_, 'tcx>,
959 placeholder: ty::PlaceholderRegion,
960 ) -> ty::Region<'tcx> {
961 let placeholder_index = self.placeholder_indices.insert(placeholder);
962 match self.placeholder_index_to_region.get(placeholder_index) {
965 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
966 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
967 self.placeholder_index_to_region.push(region);
974 /// The `Locations` type summarizes *where* region constraints are
975 /// required to hold. Normally, this is at a particular point which
976 /// created the obligation, but for constraints that the user gave, we
977 /// want the constraint to hold at all points.
978 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
980 /// Indicates that a type constraint should always be true. This
981 /// is particularly important in the new borrowck analysis for
982 /// things like the type of the return slot. Consider this
986 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
988 /// return &y; // error
992 /// Here, we wind up with the signature from the return type being
993 /// something like `&'1 u32` where `'1` is a universal region. But
994 /// the type of the return slot `_0` is something like `&'2 u32`
995 /// where `'2` is an existential region variable. The type checker
996 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
997 /// older NLL analysis, we required this only at the entry point
998 /// to the function. By the nature of the constraints, this wound
999 /// up propagating to all points reachable from start (because
1000 /// `'1` -- as a universal region -- is live everywhere). In the
1001 /// newer analysis, though, this doesn't work: `_0` is considered
1002 /// dead at the start (it has no usable value) and hence this type
1003 /// equality is basically a no-op. Then, later on, when we do `_0
1004 /// = &'3 y`, that region `'3` never winds up related to the
1005 /// universal region `'1` and hence no error occurs. Therefore, we
1006 /// use Locations::All instead, which ensures that the `'1` and
1007 /// `'2` are equal everything. We also use this for other
1008 /// user-given type annotations; e.g., if the user wrote `let mut
1009 /// x: &'static u32 = ...`, we would ensure that all values
1010 /// assigned to `x` are of `'static` lifetime.
1012 /// The span points to the place the constraint arose. For example,
1013 /// it points to the type in a user-given type annotation. If
1014 /// there's no sensible span then it's DUMMY_SP.
1017 /// An outlives constraint that only has to hold at a single location,
1018 /// usually it represents a point where references flow from one spot to
1019 /// another (e.g., `x = y`)
1024 pub fn from_location(&self) -> Option<Location> {
1026 Locations::All(_) => None,
1027 Locations::Single(from_location) => Some(*from_location),
1031 /// Gets a span representing the location.
1032 pub fn span(&self, body: &Body<'_>) -> Span {
1034 Locations::All(span) => *span,
1035 Locations::Single(l) => body.source_info(*l).span,
1040 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1042 infcx: &'a InferCtxt<'a, 'tcx>,
1043 body: &'a Body<'tcx>,
1044 param_env: ty::ParamEnv<'tcx>,
1045 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1046 implicit_region_bound: ty::Region<'tcx>,
1047 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1048 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
1050 let mut checker = Self {
1052 last_span: DUMMY_SP,
1054 user_type_annotations: &body.user_type_annotations,
1057 implicit_region_bound,
1059 reported_errors: Default::default(),
1060 universal_region_relations,
1062 checker.check_user_type_annotations();
1066 fn unsized_feature_enabled(&self) -> bool {
1067 let features = self.tcx().features();
1068 features.unsized_locals || features.unsized_fn_params
1071 /// Equate the inferred type and the annotated type for user type annotations
1072 fn check_user_type_annotations(&mut self) {
1074 "check_user_type_annotations: user_type_annotations={:?}",
1075 self.user_type_annotations
1077 for user_annotation in self.user_type_annotations {
1078 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1079 let inferred_ty = self.normalize(inferred_ty, Locations::All(span));
1080 let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1082 UserType::Ty(mut ty) => {
1083 ty = self.normalize(ty, Locations::All(span));
1085 if let Err(terr) = self.eq_types(
1088 Locations::All(span),
1089 ConstraintCategory::BoringNoLocation,
1094 "bad user type ({:?} = {:?}): {:?}",
1101 self.prove_predicate(
1102 ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into()))
1103 .to_predicate(self.tcx()),
1104 Locations::All(span),
1105 ConstraintCategory::TypeAnnotation,
1108 UserType::TypeOf(def_id, user_substs) => {
1109 if let Err(terr) = self.fully_perform_op(
1110 Locations::All(span),
1111 ConstraintCategory::BoringNoLocation,
1112 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1121 "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}",
1125 self.tcx().type_of(def_id),
1134 #[instrument(skip(self, data), level = "debug")]
1135 fn push_region_constraints(
1137 locations: Locations,
1138 category: ConstraintCategory,
1139 data: &QueryRegionConstraints<'tcx>,
1141 debug!("constraints generated: {:#?}", data);
1143 constraint_conversion::ConstraintConversion::new(
1145 self.borrowck_context.universal_regions,
1146 self.region_bound_pairs,
1147 Some(self.implicit_region_bound),
1151 &mut self.borrowck_context.constraints,
1156 /// Try to relate `sub <: sup`
1161 locations: Locations,
1162 category: ConstraintCategory,
1164 // Use this order of parameters because the sup type is usually the
1165 // "expected" type in diagnostics.
1166 self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
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(
1198 |this, field, &()| {
1199 let ty = this.field_ty(tcx, field);
1200 self.normalize(ty, locations)
1203 curr_projected_ty = projected_ty;
1206 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1207 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1210 let ty = curr_projected_ty.ty;
1211 self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1216 /// Equates a type `anon_ty` that may contain opaque types whose
1217 /// values are to be inferred by the MIR.
1219 /// The type `revealed_ty` contains the same type as `anon_ty`, but with the
1220 /// hidden types for impl traits revealed.
1224 /// Consider a piece of code like
1227 /// type Foo<U> = impl Debug;
1229 /// fn foo<T: Debug>(t: T) -> Box<Foo<T>> {
1230 /// Box::new((t, 22_u32))
1234 /// Here, the function signature would be something like
1235 /// `fn(T) -> Box<impl Debug>`. The MIR return slot would have
1236 /// the type with the opaque type revealed, so `Box<(T, u32)>`.
1238 /// In terms of our function parameters:
1240 /// * `anon_ty` would be `Box<Foo<T>>` where `Foo<T>` is an opaque type
1241 /// scoped to this function (note that it is parameterized by the
1242 /// generics of `foo`). Note that `anon_ty` is not just the opaque type,
1243 /// but the entire return type (which may contain opaque types within it).
1244 /// * `revealed_ty` would be `Box<(T, u32)>`
1245 #[instrument(skip(self), level = "debug")]
1246 fn eq_opaque_type_and_type(
1248 revealed_ty: Ty<'tcx>,
1250 locations: Locations,
1251 category: ConstraintCategory,
1253 // Fast path for the common case.
1254 if !anon_ty.has_opaque_types() {
1255 if let Err(terr) = self.eq_types(anon_ty, revealed_ty, locations, category) {
1259 "eq_opaque_type_and_type: `{:?}=={:?}` failed with `{:?}`",
1268 let param_env = self.param_env;
1269 let body = self.body;
1270 let mir_def_id = body.source.def_id().expect_local();
1272 debug!(?mir_def_id);
1273 self.fully_perform_op(
1278 let mut obligations = ObligationAccumulator::default();
1280 let dummy_body_id = hir::CRATE_HIR_ID;
1282 // Replace the opaque types defined by this function with
1283 // inference variables, creating a map. In our example above,
1284 // this would transform the type `Box<Foo<T>>` (where `Foo` is an opaque type)
1285 // to `Box<?T>`, returning an `opaque_type_map` mapping `{Foo<T> -> ?T}`.
1286 // (Note that the key of the map is both the def-id of `Foo` along with
1287 // any generic parameters.)
1288 let output_ty = obligations.add(infcx.instantiate_opaque_types(
1292 locations.span(body),
1294 debug!(?output_ty, ?revealed_ty);
1296 // Make sure that the inferred types are well-formed. I'm
1297 // not entirely sure this is needed (the HIR type check
1298 // didn't do this) but it seems sensible to prevent opaque
1299 // types hiding ill-formed types.
1300 obligations.obligations.push(traits::Obligation::new(
1301 ObligationCause::dummy(),
1303 ty::Binder::dummy(ty::PredicateKind::WellFormed(revealed_ty.into()))
1304 .to_predicate(infcx.tcx),
1308 .at(&ObligationCause::dummy(), param_env)
1309 .eq(output_ty, revealed_ty)?,
1314 Ok(InferOk { value: (), obligations: obligations.into_vec() })
1316 || "input_output".to_string(),
1320 let universal_region_relations = self.universal_region_relations;
1322 // Finally, if we instantiated the anon types successfully, we
1323 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1324 // prove that `T: Iterator` where `T` is the type we
1325 // instantiated it with).
1326 let opaque_type_map = self.infcx.inner.borrow().opaque_types.clone();
1327 for (opaque_type_key, opaque_decl) in opaque_type_map {
1328 self.fully_perform_op(
1330 ConstraintCategory::OpaqueType,
1333 infcx.constrain_opaque_type(
1336 GenerateMemberConstraints::IfNoStaticBound,
1337 universal_region_relations,
1339 Ok(InferOk { value: (), obligations: vec![] })
1341 || "opaque_type_map".to_string(),
1348 fn tcx(&self) -> TyCtxt<'tcx> {
1352 #[instrument(skip(self, body, location), level = "debug")]
1353 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1354 let tcx = self.tcx();
1356 StatementKind::Assign(box (ref place, ref rv)) => {
1357 // Assignments to temporaries are not "interesting";
1358 // they are not caused by the user, but rather artifacts
1359 // of lowering. Assignments to other sorts of places *are* interesting
1361 let category = match place.as_local() {
1362 Some(RETURN_PLACE) => {
1363 if let BorrowCheckContext {
1365 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1367 } = self.borrowck_context
1369 if tcx.is_static(*def_id) {
1370 ConstraintCategory::UseAsStatic
1372 ConstraintCategory::UseAsConst
1375 ConstraintCategory::Return(ReturnConstraint::Normal)
1380 body.local_decls[l].local_info,
1381 Some(box LocalInfo::AggregateTemp)
1384 ConstraintCategory::Usage
1386 Some(l) if !body.local_decls[l].is_user_variable() => {
1387 ConstraintCategory::Boring
1389 _ => ConstraintCategory::Assignment,
1392 "assignment category: {:?} {:?}",
1394 place.as_local().map(|l| &body.local_decls[l])
1397 let place_ty = place.ty(body, tcx).ty;
1398 let place_ty = self.normalize(place_ty, location);
1399 let rv_ty = rv.ty(body, tcx);
1400 let rv_ty = self.normalize(rv_ty, location);
1402 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1407 "bad assignment ({:?} = {:?}): {:?}",
1414 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1415 if let Err(terr) = self.relate_type_and_user_type(
1417 ty::Variance::Invariant,
1418 &UserTypeProjection { base: annotation_index, projs: vec![] },
1419 location.to_locations(),
1420 ConstraintCategory::Boring,
1422 let annotation = &self.user_type_annotations[annotation_index];
1426 "bad user type on rvalue ({:?} = {:?}): {:?}",
1434 self.check_rvalue(body, rv, location);
1435 if !self.unsized_feature_enabled() {
1436 let trait_ref = ty::TraitRef {
1437 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1438 substs: tcx.mk_substs_trait(place_ty, &[]),
1440 self.prove_trait_ref(
1442 location.to_locations(),
1443 ConstraintCategory::SizedBound,
1447 StatementKind::SetDiscriminant { ref place, variant_index } => {
1448 let place_type = place.ty(body, tcx).ty;
1449 let adt = match place_type.kind() {
1450 ty::Adt(adt, _) if adt.is_enum() => adt,
1453 stmt.source_info.span,
1454 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1460 if variant_index.as_usize() >= adt.variants.len() {
1462 stmt.source_info.span,
1463 "bad set discriminant ({:?} = {:?}): value of of range",
1469 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1470 let place_ty = place.ty(body, tcx).ty;
1471 if let Err(terr) = self.relate_type_and_user_type(
1475 Locations::All(stmt.source_info.span),
1476 ConstraintCategory::TypeAnnotation,
1478 let annotation = &self.user_type_annotations[projection.base];
1482 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1490 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
1493 stmt.source_info.span,
1494 "Unexpected StatementKind::CopyNonOverlapping, should only appear after lowering_intrinsics",
1496 StatementKind::FakeRead(..)
1497 | StatementKind::StorageLive(..)
1498 | StatementKind::StorageDead(..)
1499 | StatementKind::LlvmInlineAsm { .. }
1500 | StatementKind::Retag { .. }
1501 | StatementKind::Coverage(..)
1502 | StatementKind::Nop => {}
1506 #[instrument(skip(self, body, term_location), level = "debug")]
1507 fn check_terminator(
1510 term: &Terminator<'tcx>,
1511 term_location: Location,
1513 let tcx = self.tcx();
1515 TerminatorKind::Goto { .. }
1516 | TerminatorKind::Resume
1517 | TerminatorKind::Abort
1518 | TerminatorKind::Return
1519 | TerminatorKind::GeneratorDrop
1520 | TerminatorKind::Unreachable
1521 | TerminatorKind::Drop { .. }
1522 | TerminatorKind::FalseEdge { .. }
1523 | TerminatorKind::FalseUnwind { .. }
1524 | TerminatorKind::InlineAsm { .. } => {
1525 // no checks needed for these
1528 TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1529 let place_ty = place.ty(body, tcx).ty;
1530 let rv_ty = value.ty(body, tcx);
1532 let locations = term_location.to_locations();
1534 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1539 "bad DropAndReplace ({:?} = {:?}): {:?}",
1546 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1547 let discr_ty = discr.ty(body, tcx);
1548 if let Err(terr) = self.sub_types(
1551 term_location.to_locations(),
1552 ConstraintCategory::Assignment,
1557 "bad SwitchInt ({:?} on {:?}): {:?}",
1563 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1564 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1566 // FIXME: check the values
1568 TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1569 let func_ty = func.ty(body, tcx);
1570 debug!("check_terminator: call, func_ty={:?}", func_ty);
1571 let sig = match func_ty.kind() {
1572 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1574 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1578 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1579 term.source_info.span,
1580 LateBoundRegionConversionTime::FnCall,
1583 let sig = self.normalize(sig, term_location);
1584 self.check_call_dest(body, term, &sig, destination, term_location);
1586 self.prove_predicates(
1587 sig.inputs_and_output
1589 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1590 term_location.to_locations(),
1591 ConstraintCategory::Boring,
1594 // The ordinary liveness rules will ensure that all
1595 // regions in the type of the callee are live here. We
1596 // then further constrain the late-bound regions that
1597 // were instantiated at the call site to be live as
1598 // well. The resulting is that all the input (and
1599 // output) types in the signature must be live, since
1600 // all the inputs that fed into it were live.
1601 for &late_bound_region in map.values() {
1603 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1604 self.borrowck_context
1606 .liveness_constraints
1607 .add_element(region_vid, term_location);
1610 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1612 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1613 let cond_ty = cond.ty(body, tcx);
1614 if cond_ty != tcx.types.bool {
1615 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1618 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1619 if len.ty(body, tcx) != tcx.types.usize {
1620 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1622 if index.ty(body, tcx) != tcx.types.usize {
1623 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1627 TerminatorKind::Yield { ref value, .. } => {
1628 let value_ty = value.ty(body, tcx);
1629 match body.yield_ty() {
1630 None => span_mirbug!(self, term, "yield in non-generator"),
1632 if let Err(terr) = self.sub_types(
1635 term_location.to_locations(),
1636 ConstraintCategory::Yield,
1641 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1656 term: &Terminator<'tcx>,
1657 sig: &ty::FnSig<'tcx>,
1658 destination: &Option<(Place<'tcx>, BasicBlock)>,
1659 term_location: Location,
1661 let tcx = self.tcx();
1662 match *destination {
1663 Some((ref dest, _target_block)) => {
1664 let dest_ty = dest.ty(body, tcx).ty;
1665 let dest_ty = self.normalize(dest_ty, term_location);
1666 let category = match dest.as_local() {
1667 Some(RETURN_PLACE) => {
1668 if let BorrowCheckContext {
1670 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1672 } = self.borrowck_context
1674 if tcx.is_static(*def_id) {
1675 ConstraintCategory::UseAsStatic
1677 ConstraintCategory::UseAsConst
1680 ConstraintCategory::Return(ReturnConstraint::Normal)
1683 Some(l) if !body.local_decls[l].is_user_variable() => {
1684 ConstraintCategory::Boring
1686 _ => ConstraintCategory::Assignment,
1689 let locations = term_location.to_locations();
1691 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1695 "call dest mismatch ({:?} <- {:?}): {:?}",
1702 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1703 // this check is done at `check_local`.
1704 if self.unsized_feature_enabled() {
1705 let span = term.source_info.span;
1706 self.ensure_place_sized(dest_ty, span);
1712 .conservative_is_privately_uninhabited(self.param_env.and(sig.output()))
1714 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1720 fn check_call_inputs(
1723 term: &Terminator<'tcx>,
1724 sig: &ty::FnSig<'tcx>,
1725 args: &[Operand<'tcx>],
1726 term_location: Location,
1727 from_hir_call: bool,
1729 debug!("check_call_inputs({:?}, {:?})", sig, args);
1730 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1731 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1733 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1734 let op_arg_ty = op_arg.ty(body, self.tcx());
1735 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1736 let category = if from_hir_call {
1737 ConstraintCategory::CallArgument
1739 ConstraintCategory::Boring
1742 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1747 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1757 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1758 let is_cleanup = block_data.is_cleanup;
1759 self.last_span = block_data.terminator().source_info.span;
1760 match block_data.terminator().kind {
1761 TerminatorKind::Goto { target } => {
1762 self.assert_iscleanup(body, block_data, target, is_cleanup)
1764 TerminatorKind::SwitchInt { ref targets, .. } => {
1765 for target in targets.all_targets() {
1766 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1769 TerminatorKind::Resume => {
1771 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1774 TerminatorKind::Abort => {
1776 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1779 TerminatorKind::Return => {
1781 span_mirbug!(self, block_data, "return on cleanup block")
1784 TerminatorKind::GeneratorDrop { .. } => {
1786 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1789 TerminatorKind::Yield { resume, drop, .. } => {
1791 span_mirbug!(self, block_data, "yield in cleanup block")
1793 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1794 if let Some(drop) = drop {
1795 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1798 TerminatorKind::Unreachable => {}
1799 TerminatorKind::Drop { target, unwind, .. }
1800 | TerminatorKind::DropAndReplace { target, unwind, .. }
1801 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1802 self.assert_iscleanup(body, block_data, target, is_cleanup);
1803 if let Some(unwind) = unwind {
1805 span_mirbug!(self, block_data, "unwind on cleanup block")
1807 self.assert_iscleanup(body, block_data, unwind, true);
1810 TerminatorKind::Call { ref destination, cleanup, .. } => {
1811 if let &Some((_, target)) = destination {
1812 self.assert_iscleanup(body, block_data, target, is_cleanup);
1814 if let Some(cleanup) = cleanup {
1816 span_mirbug!(self, block_data, "cleanup on cleanup block")
1818 self.assert_iscleanup(body, block_data, cleanup, true);
1821 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1822 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1823 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1825 TerminatorKind::FalseUnwind { real_target, unwind } => {
1826 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1827 if let Some(unwind) = unwind {
1829 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1831 self.assert_iscleanup(body, block_data, unwind, true);
1834 TerminatorKind::InlineAsm { destination, .. } => {
1835 if let Some(target) = destination {
1836 self.assert_iscleanup(body, block_data, target, is_cleanup);
1842 fn assert_iscleanup(
1845 ctxt: &dyn fmt::Debug,
1849 if body[bb].is_cleanup != iscleanuppad {
1850 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1854 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1855 match body.local_kind(local) {
1856 LocalKind::ReturnPointer | LocalKind::Arg => {
1857 // return values of normal functions are required to be
1858 // sized by typeck, but return values of ADT constructors are
1859 // not because we don't include a `Self: Sized` bounds on them.
1861 // Unbound parts of arguments were never required to be Sized
1862 // - maybe we should make that a warning.
1865 LocalKind::Var | LocalKind::Temp => {}
1868 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1869 // and nullary ops are checked in `check_call_dest`.
1870 if !self.unsized_feature_enabled() {
1871 let span = local_decl.source_info.span;
1872 let ty = local_decl.ty;
1873 self.ensure_place_sized(ty, span);
1877 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1878 let tcx = self.tcx();
1880 // Erase the regions from `ty` to get a global type. The
1881 // `Sized` bound in no way depends on precise regions, so this
1882 // shouldn't affect `is_sized`.
1883 let erased_ty = tcx.erase_regions(ty);
1884 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1885 // in current MIR construction, all non-control-flow rvalue
1886 // expressions evaluate through `as_temp` or `into` a return
1887 // slot or local, so to find all unsized rvalues it is enough
1888 // to check all temps, return slots and locals.
1889 if self.reported_errors.replace((ty, span)).is_none() {
1890 let mut diag = struct_span_err!(
1894 "cannot move a value of type {0}: the size of {0} \
1895 cannot be statically determined",
1899 // While this is located in `nll::typeck` this error is not
1900 // an NLL error, it's a required check to prevent creation
1901 // of unsized rvalues in a call expression.
1907 fn aggregate_field_ty(
1909 ak: &AggregateKind<'tcx>,
1912 ) -> Result<Ty<'tcx>, FieldAccessError> {
1913 let tcx = self.tcx();
1916 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1917 let variant = &def.variants[variant_index];
1918 let adj_field_index = active_field_index.unwrap_or(field_index);
1919 if let Some(field) = variant.fields.get(adj_field_index) {
1920 Ok(self.normalize(field.ty(tcx, substs), location))
1922 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1925 AggregateKind::Closure(_, substs) => {
1926 match substs.as_closure().upvar_tys().nth(field_index) {
1928 None => Err(FieldAccessError::OutOfRange {
1929 field_count: substs.as_closure().upvar_tys().count(),
1933 AggregateKind::Generator(_, substs, _) => {
1934 // It doesn't make sense to look at a field beyond the prefix;
1935 // these require a variant index, and are not initialized in
1936 // aggregate rvalues.
1937 match substs.as_generator().prefix_tys().nth(field_index) {
1939 None => Err(FieldAccessError::OutOfRange {
1940 field_count: substs.as_generator().prefix_tys().count(),
1944 AggregateKind::Array(ty) => Ok(ty),
1945 AggregateKind::Tuple => {
1946 unreachable!("This should have been covered in check_rvalues");
1951 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1952 let tcx = self.tcx();
1955 Rvalue::Aggregate(ak, ops) => {
1956 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1959 Rvalue::Repeat(operand, len) => {
1960 // If the length cannot be evaluated we must assume that the length can be larger
1962 // If the length is larger than 1, the repeat expression will need to copy the
1963 // element, so we require the `Copy` trait.
1964 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1966 Operand::Copy(..) | Operand::Constant(..) => {
1967 // These are always okay: direct use of a const, or a value that can evidently be copied.
1969 Operand::Move(place) => {
1970 // Make sure that repeated elements implement `Copy`.
1971 let span = body.source_info(location).span;
1972 let ty = operand.ty(body, tcx);
1973 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1974 let ccx = ConstCx::new_with_param_env(tcx, body, self.param_env);
1976 is_const_fn_in_array_repeat_expression(&ccx, &place, &body);
1978 debug!("check_rvalue: is_const_fn={:?}", is_const_fn);
1980 let def_id = body.source.def_id().expect_local();
1981 let obligation = traits::Obligation::new(
1982 ObligationCause::new(
1984 self.tcx().hir().local_def_id_to_hir_id(def_id),
1985 traits::ObligationCauseCode::RepeatVec(is_const_fn),
1988 ty::Binder::dummy(ty::TraitRef::new(
1989 self.tcx().require_lang_item(
1991 Some(self.last_span),
1993 tcx.mk_substs_trait(ty, &[]),
1996 .to_predicate(self.tcx()),
1998 self.infcx.report_selection_error(
2001 &traits::SelectionError::Unimplemented,
2010 Rvalue::NullaryOp(_, ty) | Rvalue::ShallowInitBox(_, ty) => {
2011 let trait_ref = ty::TraitRef {
2012 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
2013 substs: tcx.mk_substs_trait(ty, &[]),
2016 self.prove_trait_ref(
2018 location.to_locations(),
2019 ConstraintCategory::SizedBound,
2023 Rvalue::Cast(cast_kind, op, ty) => {
2025 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2026 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2028 // The type that we see in the fcx is like
2029 // `foo::<'a, 'b>`, where `foo` is the path to a
2030 // function definition. When we extract the
2031 // signature, it comes from the `fn_sig` query,
2032 // and hence may contain unnormalized results.
2033 let fn_sig = self.normalize(fn_sig, location);
2035 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2037 if let Err(terr) = self.eq_types(
2040 location.to_locations(),
2041 ConstraintCategory::Cast,
2046 "equating {:?} with {:?} yields {:?}",
2054 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2055 let sig = match op.ty(body, tcx).kind() {
2056 ty::Closure(_, substs) => substs.as_closure().sig(),
2059 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
2061 if let Err(terr) = self.eq_types(
2064 location.to_locations(),
2065 ConstraintCategory::Cast,
2070 "equating {:?} with {:?} yields {:?}",
2078 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2079 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2081 // The type that we see in the fcx is like
2082 // `foo::<'a, 'b>`, where `foo` is the path to a
2083 // function definition. When we extract the
2084 // signature, it comes from the `fn_sig` query,
2085 // and hence may contain unnormalized results.
2086 let fn_sig = self.normalize(fn_sig, location);
2088 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2090 if let Err(terr) = self.eq_types(
2093 location.to_locations(),
2094 ConstraintCategory::Cast,
2099 "equating {:?} with {:?} yields {:?}",
2107 CastKind::Pointer(PointerCast::Unsize) => {
2109 let trait_ref = ty::TraitRef {
2111 .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2112 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2115 self.prove_trait_ref(
2117 location.to_locations(),
2118 ConstraintCategory::Cast,
2122 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2123 let ty_from = match op.ty(body, tcx).kind() {
2124 ty::RawPtr(ty::TypeAndMut {
2126 mutbl: hir::Mutability::Mut,
2132 "unexpected base type for cast {:?}",
2138 let ty_to = match ty.kind() {
2139 ty::RawPtr(ty::TypeAndMut {
2141 mutbl: hir::Mutability::Not,
2147 "unexpected target type for cast {:?}",
2153 if let Err(terr) = self.sub_types(
2156 location.to_locations(),
2157 ConstraintCategory::Cast,
2162 "relating {:?} with {:?} yields {:?}",
2170 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2171 let ty_from = op.ty(body, tcx);
2173 let opt_ty_elem_mut = match ty_from.kind() {
2174 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2175 match array_ty.kind() {
2176 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2183 let (ty_elem, ty_mut) = match opt_ty_elem_mut {
2184 Some(ty_elem_mut) => ty_elem_mut,
2189 "ArrayToPointer cast from unexpected type {:?}",
2196 let (ty_to, ty_to_mut) = match ty.kind() {
2197 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2204 "ArrayToPointer cast to unexpected type {:?}",
2211 if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2215 "ArrayToPointer cast from const {:?} to mut {:?}",
2222 if let Err(terr) = self.sub_types(
2225 location.to_locations(),
2226 ConstraintCategory::Cast,
2231 "relating {:?} with {:?} yields {:?}",
2240 let ty_from = op.ty(body, tcx);
2241 let cast_ty_from = CastTy::from_ty(ty_from);
2242 let cast_ty_to = CastTy::from_ty(ty);
2243 match (cast_ty_from, cast_ty_to) {
2245 | (_, None | Some(CastTy::FnPtr))
2246 | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2247 | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => {
2248 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2251 Some(CastTy::Int(_)),
2252 Some(CastTy::Int(_) | CastTy::Float | CastTy::Ptr(_)),
2254 | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float))
2255 | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_)))
2256 | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (),
2262 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2263 self.add_reborrow_constraint(&body, location, region, borrowed_place);
2267 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2270 let ty_left = left.ty(body, tcx);
2271 match ty_left.kind() {
2272 // Types with regions are comparable if they have a common super-type.
2273 ty::RawPtr(_) | ty::FnPtr(_) => {
2274 let ty_right = right.ty(body, tcx);
2275 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2276 kind: TypeVariableOriginKind::MiscVariable,
2277 span: body.source_info(location).span,
2282 location.to_locations(),
2283 ConstraintCategory::Boring,
2285 .unwrap_or_else(|err| {
2286 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2288 if let Err(terr) = self.sub_types(
2291 location.to_locations(),
2292 ConstraintCategory::Boring,
2297 "unexpected comparison types {:?} and {:?} yields {:?}",
2304 // For types with no regions we can just check that the
2305 // both operands have the same type.
2306 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2307 if ty_left == right.ty(body, tcx) => {}
2308 // Other types are compared by trait methods, not by
2309 // `Rvalue::BinaryOp`.
2313 "unexpected comparison types {:?} and {:?}",
2320 Rvalue::AddressOf(..)
2321 | Rvalue::ThreadLocalRef(..)
2324 | Rvalue::BinaryOp(..)
2325 | Rvalue::CheckedBinaryOp(..)
2326 | Rvalue::UnaryOp(..)
2327 | Rvalue::Discriminant(..) => {}
2331 /// If this rvalue supports a user-given type annotation, then
2332 /// extract and return it. This represents the final type of the
2333 /// rvalue and will be unified with the inferred type.
2334 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2337 | Rvalue::ThreadLocalRef(_)
2338 | Rvalue::Repeat(..)
2340 | Rvalue::AddressOf(..)
2343 | Rvalue::ShallowInitBox(..)
2344 | Rvalue::BinaryOp(..)
2345 | Rvalue::CheckedBinaryOp(..)
2346 | Rvalue::NullaryOp(..)
2347 | Rvalue::UnaryOp(..)
2348 | Rvalue::Discriminant(..) => None,
2350 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2351 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2352 AggregateKind::Array(_) => None,
2353 AggregateKind::Tuple => None,
2354 AggregateKind::Closure(_, _) => None,
2355 AggregateKind::Generator(_, _, _) => None,
2360 fn check_aggregate_rvalue(
2363 rvalue: &Rvalue<'tcx>,
2364 aggregate_kind: &AggregateKind<'tcx>,
2365 operands: &[Operand<'tcx>],
2368 let tcx = self.tcx();
2370 self.prove_aggregate_predicates(aggregate_kind, location);
2372 if *aggregate_kind == AggregateKind::Tuple {
2373 // tuple rvalue field type is always the type of the op. Nothing to check here.
2377 for (i, operand) in operands.iter().enumerate() {
2378 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2379 Ok(field_ty) => field_ty,
2380 Err(FieldAccessError::OutOfRange { field_count }) => {
2384 "accessed field #{} but variant only has {}",
2391 let operand_ty = operand.ty(body, tcx);
2392 let operand_ty = self.normalize(operand_ty, location);
2394 if let Err(terr) = self.sub_types(
2397 location.to_locations(),
2398 ConstraintCategory::Boring,
2403 "{:?} is not a subtype of {:?}: {:?}",
2412 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2416 /// - `location`: the location `L` where the borrow expression occurs
2417 /// - `borrow_region`: the region `'a` associated with the borrow
2418 /// - `borrowed_place`: the place `P` being borrowed
2419 fn add_reborrow_constraint(
2423 borrow_region: ty::Region<'tcx>,
2424 borrowed_place: &Place<'tcx>,
2426 // These constraints are only meaningful during borrowck:
2427 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2428 self.borrowck_context;
2430 // In Polonius mode, we also push a `loan_issued_at` fact
2431 // linking the loan to the region (in some cases, though,
2432 // there is no loan associated with this borrow expression --
2433 // that occurs when we are borrowing an unsafe place, for
2435 if let Some(all_facts) = all_facts {
2436 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2437 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2438 let region_vid = borrow_region.to_region_vid();
2439 all_facts.loan_issued_at.push((
2442 location_table.mid_index(location),
2447 // If we are reborrowing the referent of another reference, we
2448 // need to add outlives relationships. In a case like `&mut
2449 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2450 // need to ensure that `'b: 'a`.
2453 "add_reborrow_constraint({:?}, {:?}, {:?})",
2454 location, borrow_region, borrowed_place
2457 let mut cursor = borrowed_place.projection.as_ref();
2458 let tcx = self.infcx.tcx;
2459 let field = path_utils::is_upvar_field_projection(
2461 &self.borrowck_context.upvars,
2462 borrowed_place.as_ref(),
2465 let category = if let Some(field) = field {
2466 let var_hir_id = self.borrowck_context.upvars[field.index()].place.get_root_variable();
2467 // FIXME(project-rfc-2229#8): Use Place for better diagnostics
2468 ConstraintCategory::ClosureUpvar(var_hir_id)
2470 ConstraintCategory::Boring
2473 while let [proj_base @ .., elem] = cursor {
2476 debug!("add_reborrow_constraint - iteration {:?}", elem);
2479 ProjectionElem::Deref => {
2480 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2482 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2483 match base_ty.kind() {
2484 ty::Ref(ref_region, _, mutbl) => {
2485 constraints.outlives_constraints.push(OutlivesConstraint {
2486 sup: ref_region.to_region_vid(),
2487 sub: borrow_region.to_region_vid(),
2488 locations: location.to_locations(),
2490 variance_info: ty::VarianceDiagInfo::default(),
2494 hir::Mutability::Not => {
2495 // Immutable reference. We don't need the base
2496 // to be valid for the entire lifetime of
2500 hir::Mutability::Mut => {
2501 // Mutable reference. We *do* need the base
2502 // to be valid, because after the base becomes
2503 // invalid, someone else can use our mutable deref.
2505 // This is in order to make the following function
2508 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2513 // As otherwise you could clone `&mut T` using the
2514 // following function:
2516 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2517 // let my_clone = unsafe_deref(&'a x);
2526 // deref of raw pointer, guaranteed to be valid
2529 ty::Adt(def, _) if def.is_box() => {
2530 // deref of `Box`, need the base to be valid - propagate
2532 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2535 ProjectionElem::Field(..)
2536 | ProjectionElem::Downcast(..)
2537 | ProjectionElem::Index(..)
2538 | ProjectionElem::ConstantIndex { .. }
2539 | ProjectionElem::Subslice { .. } => {
2540 // other field access
2546 fn prove_aggregate_predicates(
2548 aggregate_kind: &AggregateKind<'tcx>,
2551 let tcx = self.tcx();
2554 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2555 aggregate_kind, location
2558 let (def_id, instantiated_predicates) = match aggregate_kind {
2559 AggregateKind::Adt(def, _, substs, _, _) => {
2560 (def.did, tcx.predicates_of(def.did).instantiate(tcx, substs))
2563 // For closures, we have some **extra requirements** we
2565 // have to check. In particular, in their upvars and
2566 // signatures, closures often reference various regions
2567 // from the surrounding function -- we call those the
2568 // closure's free regions. When we borrow-check (and hence
2569 // region-check) closures, we may find that the closure
2570 // requires certain relationships between those free
2571 // regions. However, because those free regions refer to
2572 // portions of the CFG of their caller, the closure is not
2573 // in a position to verify those relationships. In that
2574 // case, the requirements get "propagated" to us, and so
2575 // we have to solve them here where we instantiate the
2578 // Despite the opacity of the previous parapgrah, this is
2579 // actually relatively easy to understand in terms of the
2580 // desugaring. A closure gets desugared to a struct, and
2581 // these extra requirements are basically like where
2582 // clauses on the struct.
2583 AggregateKind::Closure(def_id, substs)
2584 | AggregateKind::Generator(def_id, substs, _) => {
2585 (*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location))
2588 AggregateKind::Array(_) | AggregateKind::Tuple => {
2589 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2593 self.normalize_and_prove_instantiated_predicates(
2595 instantiated_predicates,
2596 location.to_locations(),
2600 fn prove_closure_bounds(
2604 substs: SubstsRef<'tcx>,
2606 ) -> ty::InstantiatedPredicates<'tcx> {
2607 if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2609 let closure_constraints = QueryRegionConstraints {
2610 outlives: closure_region_requirements.apply_requirements(
2616 // Presently, closures never propagate member
2617 // constraints to their parents -- they are enforced
2618 // locally. This is largely a non-issue as member
2619 // constraints only come from `-> impl Trait` and
2620 // friends which don't appear (thus far...) in
2622 member_constraints: vec![],
2625 let bounds_mapping = closure_constraints
2629 .filter_map(|(idx, constraint)| {
2630 let ty::OutlivesPredicate(k1, r2) =
2631 constraint.no_bound_vars().unwrap_or_else(|| {
2632 bug!("query_constraint {:?} contained bound vars", constraint,);
2636 GenericArgKind::Lifetime(r1) => {
2637 // constraint is r1: r2
2638 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2639 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2640 let outlives_requirements =
2641 &closure_region_requirements.outlives_requirements[idx];
2644 (outlives_requirements.category, outlives_requirements.blame_span),
2647 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2655 .closure_bounds_mapping
2656 .insert(location, bounds_mapping);
2657 assert!(existing.is_none(), "Multiple closures at the same location.");
2659 self.push_region_constraints(
2660 location.to_locations(),
2661 ConstraintCategory::ClosureBounds,
2662 &closure_constraints,
2666 tcx.predicates_of(def_id).instantiate(tcx, substs)
2669 #[instrument(skip(self, body), level = "debug")]
2670 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2671 self.last_span = body.span;
2674 for (local, local_decl) in body.local_decls.iter_enumerated() {
2675 self.check_local(&body, local, local_decl);
2678 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2679 let mut location = Location { block, statement_index: 0 };
2680 for stmt in &block_data.statements {
2681 if !stmt.source_info.span.is_dummy() {
2682 self.last_span = stmt.source_info.span;
2684 self.check_stmt(body, stmt, location);
2685 location.statement_index += 1;
2688 self.check_terminator(&body, block_data.terminator(), location);
2689 self.check_iscleanup(&body, block_data);
2694 trait NormalizeLocation: fmt::Debug + Copy {
2695 fn to_locations(self) -> Locations;
2698 impl NormalizeLocation for Locations {
2699 fn to_locations(self) -> Locations {
2704 impl NormalizeLocation for Location {
2705 fn to_locations(self) -> Locations {
2706 Locations::Single(self)
2710 #[derive(Debug, Default)]
2711 struct ObligationAccumulator<'tcx> {
2712 obligations: PredicateObligations<'tcx>,
2715 impl<'tcx> ObligationAccumulator<'tcx> {
2716 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2717 let InferOk { value, obligations } = value;
2718 self.obligations.extend(obligations);
2722 fn into_vec(self) -> PredicateObligations<'tcx> {