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_errors::struct_span_err;
12 use rustc_hir::def_id::{DefId, LocalDefId};
13 use rustc_hir::lang_items::{CoerceUnsizedTraitLangItem, CopyTraitLangItem, SizedTraitLangItem};
14 use rustc_index::vec::{Idx, IndexVec};
15 use rustc_infer::infer::canonical::QueryRegionConstraints;
16 use rustc_infer::infer::outlives::env::RegionBoundPairs;
17 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
18 use rustc_infer::infer::{
19 InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin,
21 use rustc_middle::mir::tcx::PlaceTy;
22 use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
23 use rustc_middle::mir::AssertKind;
24 use rustc_middle::mir::*;
25 use rustc_middle::ty::adjustment::PointerCast;
26 use rustc_middle::ty::cast::CastTy;
27 use rustc_middle::ty::fold::TypeFoldable;
28 use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef, UserSubsts};
29 use rustc_middle::ty::{
30 self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, RegionVid, ToPolyTraitRef, Ty,
31 TyCtxt, UserType, UserTypeAnnotationIndex,
33 use rustc_span::{Span, DUMMY_SP};
34 use rustc_target::abi::VariantIdx;
35 use rustc_trait_selection::infer::InferCtxtExt as _;
36 use rustc_trait_selection::opaque_types::{GenerateMemberConstraints, InferCtxtExt};
37 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
38 use rustc_trait_selection::traits::query::type_op;
39 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
40 use rustc_trait_selection::traits::query::{Fallible, NoSolution};
41 use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligations};
43 use crate::dataflow::impls::MaybeInitializedPlaces;
44 use crate::dataflow::move_paths::MoveData;
45 use crate::dataflow::ResultsCursor;
46 use crate::transform::{
47 check_consts::ConstCx,
48 promote_consts::should_suggest_const_in_array_repeat_expressions_attribute,
51 use crate::borrow_check::{
52 borrow_set::BorrowSet,
53 constraints::{OutlivesConstraint, OutlivesConstraintSet},
55 location::LocationTable,
56 member_constraints::MemberConstraintSet,
58 region_infer::values::{
59 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
61 region_infer::{ClosureRegionRequirementsExt, TypeTest},
63 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
64 universal_regions::{DefiningTy, UniversalRegions},
67 macro_rules! span_mirbug {
68 ($context:expr, $elem:expr, $($message:tt)*) => ({
69 $crate::borrow_check::type_check::mirbug(
73 "broken MIR in {:?} ({:?}): {}",
76 format_args!($($message)*),
82 macro_rules! span_mirbug_and_err {
83 ($context:expr, $elem:expr, $($message:tt)*) => ({
85 span_mirbug!($context, $elem, $($message)*);
91 mod constraint_conversion;
92 pub mod free_region_relations;
97 /// Type checks the given `mir` in the context of the inference
98 /// context `infcx`. Returns any region constraints that have yet to
99 /// be proven. This result is includes liveness constraints that
100 /// ensure that regions appearing in the types of all local variables
101 /// are live at all points where that local variable may later be
104 /// This phase of type-check ought to be infallible -- this is because
105 /// the original, HIR-based type-check succeeded. So if any errors
106 /// occur here, we will get a `bug!` reported.
110 /// - `infcx` -- inference context to use
111 /// - `param_env` -- parameter environment to use for trait solving
112 /// - `body` -- MIR body to type-check
113 /// - `promoted` -- map of promoted constants within `body`
114 /// - `mir_def_id` -- `LocalDefId` from which the MIR is derived
115 /// - `universal_regions` -- the universal regions from `body`s function signature
116 /// - `location_table` -- MIR location map of `body`
117 /// - `borrow_set` -- information about borrows occurring in `body`
118 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
119 /// - `flow_inits` -- results of a maybe-init dataflow analysis
120 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
121 /// - `elements` -- MIR region map
122 pub(crate) fn type_check<'mir, 'tcx>(
123 infcx: &InferCtxt<'_, 'tcx>,
124 param_env: ty::ParamEnv<'tcx>,
126 promoted: &IndexVec<Promoted, Body<'tcx>>,
127 mir_def_id: LocalDefId,
128 universal_regions: &Rc<UniversalRegions<'tcx>>,
129 location_table: &LocationTable,
130 borrow_set: &BorrowSet<'tcx>,
131 all_facts: &mut Option<AllFacts>,
132 flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
133 move_data: &MoveData<'tcx>,
134 elements: &Rc<RegionValueElements>,
135 ) -> MirTypeckResults<'tcx> {
136 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
137 let mut constraints = MirTypeckRegionConstraints {
138 placeholder_indices: PlaceholderIndices::default(),
139 placeholder_index_to_region: IndexVec::default(),
140 liveness_constraints: LivenessValues::new(elements.clone()),
141 outlives_constraints: OutlivesConstraintSet::default(),
142 member_constraints: MemberConstraintSet::default(),
143 closure_bounds_mapping: Default::default(),
144 type_tests: Vec::default(),
148 universal_region_relations,
150 normalized_inputs_and_output,
151 } = free_region_relations::create(
154 Some(implicit_region_bound),
159 let mut borrowck_context = BorrowCheckContext {
164 constraints: &mut constraints,
167 let opaque_type_values = type_check_internal(
174 implicit_region_bound,
175 &mut borrowck_context,
176 &universal_region_relations,
178 cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
179 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
181 translate_outlives_facts(&mut cx);
182 cx.opaque_type_values
186 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
189 fn type_check_internal<'a, 'tcx, R>(
190 infcx: &'a InferCtxt<'a, 'tcx>,
191 mir_def_id: LocalDefId,
192 param_env: ty::ParamEnv<'tcx>,
193 body: &'a Body<'tcx>,
194 promoted: &'a IndexVec<Promoted, Body<'tcx>>,
195 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
196 implicit_region_bound: ty::Region<'tcx>,
197 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
198 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
199 extra: impl FnOnce(TypeChecker<'a, 'tcx>) -> R,
201 let mut checker = TypeChecker::new(
207 implicit_region_bound,
209 universal_region_relations,
211 let errors_reported = {
212 let mut verifier = TypeVerifier::new(&mut checker, body, promoted);
213 verifier.visit_body(&body);
214 verifier.errors_reported
217 if !errors_reported {
218 // if verifier failed, don't do further checks to avoid ICEs
219 checker.typeck_mir(body);
225 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
226 let cx = &mut typeck.borrowck_context;
227 if let Some(facts) = cx.all_facts {
228 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
229 let location_table = cx.location_table;
230 facts.outlives.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
231 |constraint: &OutlivesConstraint| {
232 if let Some(from_location) = constraint.locations.from_location() {
233 Either::Left(iter::once((
236 location_table.mid_index(from_location),
242 .map(move |location| (constraint.sup, constraint.sub, location)),
250 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
251 // We sometimes see MIR failures (notably predicate failures) due to
252 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
253 // to avoid reporting bugs in those cases.
254 tcx.sess.diagnostic().delay_span_bug(span, msg);
257 enum FieldAccessError {
258 OutOfRange { field_count: usize },
261 /// Verifies that MIR types are sane to not crash further checks.
263 /// The sanitize_XYZ methods here take an MIR object and compute its
264 /// type, calling `span_mirbug` and returning an error type if there
266 struct TypeVerifier<'a, 'b, 'tcx> {
267 cx: &'a mut TypeChecker<'b, 'tcx>,
268 body: &'b Body<'tcx>,
269 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
271 mir_def_id: LocalDefId,
272 errors_reported: bool,
275 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
276 fn visit_span(&mut self, span: &Span) {
277 if !span.is_dummy() {
278 self.last_span = *span;
282 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
283 self.sanitize_place(place, location, context);
286 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
287 self.super_constant(constant, location);
288 let ty = self.sanitize_type(constant, constant.literal.ty);
290 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
291 let live_region_vid =
292 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
296 .liveness_constraints
297 .add_element(live_region_vid, location);
300 if let Some(annotation_index) = constant.user_ty {
301 if let Err(terr) = self.cx.relate_type_and_user_type(
303 ty::Variance::Invariant,
304 &UserTypeProjection { base: annotation_index, projs: vec![] },
305 location.to_locations(),
306 ConstraintCategory::Boring,
308 let annotation = &self.cx.user_type_annotations[annotation_index];
312 "bad constant user type {:?} vs {:?}: {:?}",
319 let tcx = self.tcx();
320 if let ty::ConstKind::Unevaluated(def_id, substs, promoted) = constant.literal.val {
321 if let Some(promoted) = promoted {
322 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
323 promoted: &Body<'tcx>,
326 if let Err(terr) = verifier.cx.eq_types(
329 location.to_locations(),
330 ConstraintCategory::Boring,
335 "bad promoted type ({:?}: {:?}): {:?}",
343 if !self.errors_reported {
344 let promoted_body = &self.promoted[promoted];
345 self.sanitize_promoted(promoted_body, location);
347 let promoted_ty = promoted_body.return_ty();
348 check_err(self, promoted_body, ty, promoted_ty);
351 if let Err(terr) = self.cx.fully_perform_op(
352 location.to_locations(),
353 ConstraintCategory::Boring,
354 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
357 UserSubsts { substs, user_self_ty: None },
363 "bad constant type {:?} ({:?})",
369 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
370 let unnormalized_ty = tcx.type_of(static_def_id);
371 let locations = location.to_locations();
372 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
373 let literal_ty = constant.literal.ty.builtin_deref(true).unwrap().ty;
375 if let Err(terr) = self.cx.eq_types(
379 ConstraintCategory::Boring,
381 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
385 if let ty::FnDef(def_id, substs) = constant.literal.ty.kind {
386 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
387 self.cx.normalize_and_prove_instantiated_predicates(
388 instantiated_predicates,
389 location.to_locations(),
395 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
396 self.super_rvalue(rvalue, location);
397 let rval_ty = rvalue.ty(self.body, self.tcx());
398 self.sanitize_type(rvalue, rval_ty);
401 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
402 self.super_local_decl(local, local_decl);
403 self.sanitize_type(local_decl, local_decl.ty);
405 if let Some(user_ty) = &local_decl.user_ty {
406 for (user_ty, span) in user_ty.projections_and_spans() {
407 let ty = if !local_decl.is_nonref_binding() {
408 // If we have a binding of the form `let ref x: T = ..`
409 // then remove the outermost reference so we can check the
410 // type annotation for the remaining type.
411 if let ty::Ref(_, rty, _) = local_decl.ty.kind {
414 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
420 if let Err(terr) = self.cx.relate_type_and_user_type(
422 ty::Variance::Invariant,
424 Locations::All(*span),
425 ConstraintCategory::TypeAnnotation,
430 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
441 fn visit_body(&mut self, body: &Body<'tcx>) {
442 self.sanitize_type(&"return type", body.return_ty());
443 for local_decl in &body.local_decls {
444 self.sanitize_type(local_decl, local_decl.ty);
446 if self.errors_reported {
449 self.super_body(body);
453 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
455 cx: &'a mut TypeChecker<'b, 'tcx>,
456 body: &'b Body<'tcx>,
457 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
462 mir_def_id: cx.mir_def_id,
464 last_span: body.span,
465 errors_reported: false,
469 fn tcx(&self) -> TyCtxt<'tcx> {
473 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
474 if ty.has_escaping_bound_vars() || ty.references_error() {
475 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
481 /// Checks that the types internal to the `place` match up with
482 /// what would be expected.
487 context: PlaceContext,
489 debug!("sanitize_place: {:?}", place);
491 let mut place_ty = PlaceTy::from_ty(self.body.local_decls[place.local].ty);
493 for elem in place.projection.iter() {
494 if place_ty.variant_index.is_none() {
495 if place_ty.ty.references_error() {
496 assert!(self.errors_reported);
497 return PlaceTy::from_ty(self.tcx().types.err);
500 place_ty = self.sanitize_projection(place_ty, elem, place, location)
503 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
504 let tcx = self.tcx();
505 let trait_ref = ty::TraitRef {
506 def_id: tcx.require_lang_item(CopyTraitLangItem, Some(self.last_span)),
507 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
510 // To have a `Copy` operand, the type `T` of the
511 // value must be `Copy`. Note that we prove that `T: Copy`,
512 // rather than using the `is_copy_modulo_regions`
513 // test. This is important because
514 // `is_copy_modulo_regions` ignores the resulting region
515 // obligations and assumes they pass. This can result in
516 // bounds from `Copy` impls being unsoundly ignored (e.g.,
517 // #29149). Note that we decide to use `Copy` before knowing
518 // whether the bounds fully apply: in effect, the rule is
519 // that if a value of some type could implement `Copy`, then
521 self.cx.prove_trait_ref(
523 location.to_locations(),
524 ConstraintCategory::CopyBound,
531 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
532 // Determine the constraints from the promoted MIR by running the type
533 // checker on the promoted MIR, then transfer the constraints back to
534 // the main MIR, changing the locations to the provided location.
536 let parent_body = mem::replace(&mut self.body, promoted_body);
538 // Use new sets of constraints and closure bounds so that we can
539 // modify their locations.
540 let all_facts = &mut None;
541 let mut constraints = Default::default();
542 let mut closure_bounds = Default::default();
543 let mut liveness_constraints =
544 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
545 // Don't try to add borrow_region facts for the promoted MIR
547 let mut swap_constraints = |this: &mut Self| {
548 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
550 &mut this.cx.borrowck_context.constraints.outlives_constraints,
554 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
558 &mut this.cx.borrowck_context.constraints.liveness_constraints,
559 &mut liveness_constraints,
563 swap_constraints(self);
565 self.visit_body(&promoted_body);
567 if !self.errors_reported {
568 // if verifier failed, don't do further checks to avoid ICEs
569 self.cx.typeck_mir(promoted_body);
572 self.body = parent_body;
573 // Merge the outlives constraints back in, at the given location.
574 swap_constraints(self);
576 let locations = location.to_locations();
577 for constraint in constraints.outlives().iter() {
578 let mut constraint = *constraint;
579 constraint.locations = locations;
580 if let ConstraintCategory::Return
581 | ConstraintCategory::UseAsConst
582 | ConstraintCategory::UseAsStatic = constraint.category
584 // "Returning" from a promoted is an assignment to a
585 // temporary from the user's point of view.
586 constraint.category = ConstraintCategory::Boring;
588 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
590 for live_region in liveness_constraints.rows() {
594 .liveness_constraints
595 .add_element(live_region, location);
598 if !closure_bounds.is_empty() {
599 let combined_bounds_mapping =
600 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
605 .closure_bounds_mapping
606 .insert(location, combined_bounds_mapping);
607 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
611 fn sanitize_projection(
614 pi: &PlaceElem<'tcx>,
618 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
619 let tcx = self.tcx();
620 let base_ty = base.ty;
622 ProjectionElem::Deref => {
623 let deref_ty = base_ty.builtin_deref(true);
624 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
625 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
628 ProjectionElem::Index(i) => {
629 let index_ty = Place::from(i).ty(self.body, tcx).ty;
630 if index_ty != tcx.types.usize {
631 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
633 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
634 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
638 ProjectionElem::ConstantIndex { .. } => {
639 // consider verifying in-bounds
640 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
641 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
644 ProjectionElem::Subslice { from, to, from_end } => {
645 PlaceTy::from_ty(match base_ty.kind {
646 ty::Array(inner, _) => {
647 assert!(!from_end, "array subslices should not use from_end");
648 tcx.mk_array(inner, (to - from) as u64)
651 assert!(from_end, "slice subslices should use from_end");
654 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
657 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind {
658 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
659 if index.as_usize() >= adt_def.variants.len() {
660 PlaceTy::from_ty(span_mirbug_and_err!(
663 "cast to variant #{:?} but enum only has {:?}",
665 adt_def.variants.len()
668 PlaceTy { ty: base_ty, variant_index: Some(index) }
671 // We do not need to handle generators here, because this runs
672 // before the generator transform stage.
674 let ty = if let Some(name) = maybe_name {
675 span_mirbug_and_err!(
678 "can't downcast {:?} as {:?}",
683 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
688 ProjectionElem::Field(field, fty) => {
689 let fty = self.sanitize_type(place, fty);
690 match self.field_ty(place, base, field, location) {
692 let ty = self.cx.normalize(ty, location);
693 if let Err(terr) = self.cx.eq_types(
696 location.to_locations(),
697 ConstraintCategory::Boring,
702 "bad field access ({:?}: {:?}): {:?}",
709 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
712 "accessed field #{} but variant only has {}",
717 PlaceTy::from_ty(fty)
722 fn error(&mut self) -> Ty<'tcx> {
723 self.errors_reported = true;
729 parent: &dyn fmt::Debug,
730 base_ty: PlaceTy<'tcx>,
733 ) -> Result<Ty<'tcx>, FieldAccessError> {
734 let tcx = self.tcx();
736 let (variant, substs) = match base_ty {
737 PlaceTy { ty, variant_index: Some(variant_index) } => match ty.kind {
738 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
739 ty::Generator(def_id, substs, _) => {
740 let mut variants = substs.as_generator().state_tys(def_id, tcx);
741 let mut variant = match variants.nth(variant_index.into()) {
744 "variant_index of generator out of range: {:?}/{:?}",
746 substs.as_generator().state_tys(def_id, tcx).count()
749 return match variant.nth(field.index()) {
751 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
754 _ => bug!("can't have downcast of non-adt non-generator type"),
756 PlaceTy { ty, variant_index: None } => match ty.kind {
757 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
758 (&adt_def.variants[VariantIdx::new(0)], substs)
760 ty::Closure(_, substs) => {
761 return match substs.as_closure().upvar_tys().nth(field.index()) {
763 None => Err(FieldAccessError::OutOfRange {
764 field_count: substs.as_closure().upvar_tys().count(),
768 ty::Generator(_, substs, _) => {
769 // Only prefix fields (upvars and current state) are
770 // accessible without a variant index.
771 return match substs.as_generator().prefix_tys().nth(field.index()) {
773 None => Err(FieldAccessError::OutOfRange {
774 field_count: substs.as_generator().prefix_tys().count(),
779 return match tys.get(field.index()) {
780 Some(&ty) => Ok(ty.expect_ty()),
781 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
785 return Ok(span_mirbug_and_err!(
788 "can't project out of {:?}",
795 if let Some(field) = variant.fields.get(field.index()) {
796 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
798 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
803 /// The MIR type checker. Visits the MIR and enforces all the
804 /// constraints needed for it to be valid and well-typed. Along the
805 /// way, it accrues region constraints -- these can later be used by
806 /// NLL region checking.
807 struct TypeChecker<'a, 'tcx> {
808 infcx: &'a InferCtxt<'a, 'tcx>,
809 param_env: ty::ParamEnv<'tcx>,
811 body: &'a Body<'tcx>,
812 /// User type annotations are shared between the main MIR and the MIR of
813 /// all of the promoted items.
814 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
815 mir_def_id: LocalDefId,
816 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
817 implicit_region_bound: ty::Region<'tcx>,
818 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
819 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
820 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
821 opaque_type_values: FxHashMap<DefId, ty::ResolvedOpaqueTy<'tcx>>,
824 struct BorrowCheckContext<'a, 'tcx> {
825 universal_regions: &'a UniversalRegions<'tcx>,
826 location_table: &'a LocationTable,
827 all_facts: &'a mut Option<AllFacts>,
828 borrow_set: &'a BorrowSet<'tcx>,
829 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
832 crate struct MirTypeckResults<'tcx> {
833 crate constraints: MirTypeckRegionConstraints<'tcx>,
834 pub(in crate::borrow_check) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
835 crate opaque_type_values: FxHashMap<DefId, ty::ResolvedOpaqueTy<'tcx>>,
838 /// A collection of region constraints that must be satisfied for the
839 /// program to be considered well-typed.
840 crate struct MirTypeckRegionConstraints<'tcx> {
841 /// Maps from a `ty::Placeholder` to the corresponding
842 /// `PlaceholderIndex` bit that we will use for it.
844 /// To keep everything in sync, do not insert this set
845 /// directly. Instead, use the `placeholder_region` helper.
846 crate placeholder_indices: PlaceholderIndices,
848 /// Each time we add a placeholder to `placeholder_indices`, we
849 /// also create a corresponding "representative" region vid for
850 /// that wraps it. This vector tracks those. This way, when we
851 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
852 /// the same underlying `RegionVid`.
853 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
855 /// In general, the type-checker is not responsible for enforcing
856 /// liveness constraints; this job falls to the region inferencer,
857 /// which performs a liveness analysis. However, in some limited
858 /// cases, the MIR type-checker creates temporary regions that do
859 /// not otherwise appear in the MIR -- in particular, the
860 /// late-bound regions that it instantiates at call-sites -- and
861 /// hence it must report on their liveness constraints.
862 crate liveness_constraints: LivenessValues<RegionVid>,
864 crate outlives_constraints: OutlivesConstraintSet,
866 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
868 crate closure_bounds_mapping:
869 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
871 crate type_tests: Vec<TypeTest<'tcx>>,
874 impl MirTypeckRegionConstraints<'tcx> {
875 fn placeholder_region(
877 infcx: &InferCtxt<'_, 'tcx>,
878 placeholder: ty::PlaceholderRegion,
879 ) -> ty::Region<'tcx> {
880 let placeholder_index = self.placeholder_indices.insert(placeholder);
881 match self.placeholder_index_to_region.get(placeholder_index) {
884 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
885 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
886 self.placeholder_index_to_region.push(region);
893 /// The `Locations` type summarizes *where* region constraints are
894 /// required to hold. Normally, this is at a particular point which
895 /// created the obligation, but for constraints that the user gave, we
896 /// want the constraint to hold at all points.
897 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
899 /// Indicates that a type constraint should always be true. This
900 /// is particularly important in the new borrowck analysis for
901 /// things like the type of the return slot. Consider this
905 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
907 /// return &y; // error
911 /// Here, we wind up with the signature from the return type being
912 /// something like `&'1 u32` where `'1` is a universal region. But
913 /// the type of the return slot `_0` is something like `&'2 u32`
914 /// where `'2` is an existential region variable. The type checker
915 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
916 /// older NLL analysis, we required this only at the entry point
917 /// to the function. By the nature of the constraints, this wound
918 /// up propagating to all points reachable from start (because
919 /// `'1` -- as a universal region -- is live everywhere). In the
920 /// newer analysis, though, this doesn't work: `_0` is considered
921 /// dead at the start (it has no usable value) and hence this type
922 /// equality is basically a no-op. Then, later on, when we do `_0
923 /// = &'3 y`, that region `'3` never winds up related to the
924 /// universal region `'1` and hence no error occurs. Therefore, we
925 /// use Locations::All instead, which ensures that the `'1` and
926 /// `'2` are equal everything. We also use this for other
927 /// user-given type annotations; e.g., if the user wrote `let mut
928 /// x: &'static u32 = ...`, we would ensure that all values
929 /// assigned to `x` are of `'static` lifetime.
931 /// The span points to the place the constraint arose. For example,
932 /// it points to the type in a user-given type annotation. If
933 /// there's no sensible span then it's DUMMY_SP.
936 /// An outlives constraint that only has to hold at a single location,
937 /// usually it represents a point where references flow from one spot to
938 /// another (e.g., `x = y`)
943 pub fn from_location(&self) -> Option<Location> {
945 Locations::All(_) => None,
946 Locations::Single(from_location) => Some(*from_location),
950 /// Gets a span representing the location.
951 pub fn span(&self, body: &Body<'_>) -> Span {
953 Locations::All(span) => *span,
954 Locations::Single(l) => body.source_info(*l).span,
959 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
961 infcx: &'a InferCtxt<'a, 'tcx>,
962 body: &'a Body<'tcx>,
963 mir_def_id: LocalDefId,
964 param_env: ty::ParamEnv<'tcx>,
965 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
966 implicit_region_bound: ty::Region<'tcx>,
967 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
968 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
970 let mut checker = Self {
975 user_type_annotations: &body.user_type_annotations,
978 implicit_region_bound,
980 reported_errors: Default::default(),
981 universal_region_relations,
982 opaque_type_values: FxHashMap::default(),
984 checker.check_user_type_annotations();
988 /// Equate the inferred type and the annotated type for user type annotations
989 fn check_user_type_annotations(&mut self) {
991 "check_user_type_annotations: user_type_annotations={:?}",
992 self.user_type_annotations
994 for user_annotation in self.user_type_annotations {
995 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
996 let (annotation, _) =
997 self.infcx.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
999 UserType::Ty(mut ty) => {
1000 ty = self.normalize(ty, Locations::All(span));
1002 if let Err(terr) = self.eq_types(
1005 Locations::All(span),
1006 ConstraintCategory::BoringNoLocation,
1011 "bad user type ({:?} = {:?}): {:?}",
1018 self.prove_predicate(
1019 ty::PredicateKind::WellFormed(inferred_ty),
1020 Locations::All(span),
1021 ConstraintCategory::TypeAnnotation,
1024 UserType::TypeOf(def_id, user_substs) => {
1025 if let Err(terr) = self.fully_perform_op(
1026 Locations::All(span),
1027 ConstraintCategory::BoringNoLocation,
1028 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1037 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1049 /// Given some operation `op` that manipulates types, proves
1050 /// predicates, or otherwise uses the inference context, executes
1051 /// `op` and then executes all the further obligations that `op`
1052 /// returns. This will yield a set of outlives constraints amongst
1053 /// regions which are extracted and stored as having occurred at
1056 /// **Any `rustc_infer::infer` operations that might generate region
1057 /// constraints should occur within this method so that those
1058 /// constraints can be properly localized!**
1059 fn fully_perform_op<R>(
1061 locations: Locations,
1062 category: ConstraintCategory,
1063 op: impl type_op::TypeOp<'tcx, Output = R>,
1065 let (r, opt_data) = op.fully_perform(self.infcx)?;
1067 if let Some(data) = &opt_data {
1068 self.push_region_constraints(locations, category, data);
1074 fn push_region_constraints(
1076 locations: Locations,
1077 category: ConstraintCategory,
1078 data: &QueryRegionConstraints<'tcx>,
1080 debug!("push_region_constraints: constraints generated at {:?} are {:#?}", locations, data);
1082 constraint_conversion::ConstraintConversion::new(
1084 self.borrowck_context.universal_regions,
1085 self.region_bound_pairs,
1086 Some(self.implicit_region_bound),
1090 &mut self.borrowck_context.constraints,
1095 /// Convenient wrapper around `relate_tys::relate_types` -- see
1096 /// that fn for docs.
1102 locations: Locations,
1103 category: ConstraintCategory,
1105 relate_tys::relate_types(
1112 Some(self.borrowck_context),
1120 locations: Locations,
1121 category: ConstraintCategory,
1123 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1126 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1127 /// variables in `sub` with their inferred definitions and try
1128 /// again. This is used for opaque types in places (e.g., `let x:
1129 /// impl Foo = ..`).
1130 fn sub_types_or_anon(
1134 locations: Locations,
1135 category: ConstraintCategory,
1137 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1138 if let ty::Opaque(..) = sup.kind {
1139 // When you have `let x: impl Foo = ...` in a closure,
1140 // the resulting inferend values are stored with the
1141 // def-id of the base function.
1142 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id.to_def_id());
1143 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1155 locations: Locations,
1156 category: ConstraintCategory,
1158 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1161 fn relate_type_and_user_type(
1165 user_ty: &UserTypeProjection,
1166 locations: Locations,
1167 category: ConstraintCategory,
1170 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1171 a, v, user_ty, locations,
1174 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1175 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1177 let tcx = self.infcx.tcx;
1179 for proj in &user_ty.projs {
1180 let projected_ty = curr_projected_ty.projection_ty_core(
1184 |this, field, &()| {
1185 let ty = this.field_ty(tcx, field);
1186 self.normalize(ty, locations)
1189 curr_projected_ty = projected_ty;
1192 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1193 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1196 let ty = curr_projected_ty.ty;
1197 self.relate_types(a, v, ty, locations, category)?;
1202 fn eq_opaque_type_and_type(
1204 revealed_ty: Ty<'tcx>,
1206 anon_owner_def_id: DefId,
1207 locations: Locations,
1208 category: ConstraintCategory,
1211 "eq_opaque_type_and_type( \
1214 revealed_ty, anon_ty
1217 // Fast path for the common case.
1218 if !anon_ty.has_opaque_types() {
1219 if let Err(terr) = self.eq_types(anon_ty, revealed_ty, locations, category) {
1223 "eq_opaque_type_and_type: `{:?}=={:?}` failed with `{:?}`",
1232 let infcx = self.infcx;
1233 let tcx = infcx.tcx;
1234 let param_env = self.param_env;
1235 let body = self.body;
1236 let concrete_opaque_types =
1237 &tcx.typeck_tables_of(anon_owner_def_id.expect_local()).concrete_opaque_types;
1238 let mut opaque_type_values = Vec::new();
1240 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1241 let opaque_type_map = self.fully_perform_op(
1246 let mut obligations = ObligationAccumulator::default();
1248 let dummy_body_id = ObligationCause::dummy().body_id;
1249 let (output_ty, opaque_type_map) =
1250 obligations.add(infcx.instantiate_opaque_types(
1255 locations.span(body),
1258 "eq_opaque_type_and_type: \
1259 instantiated output_ty={:?} \
1260 opaque_type_map={:#?} \
1262 output_ty, opaque_type_map, revealed_ty
1264 // Make sure that the inferred types are well-formed. I'm
1265 // not entirely sure this is needed (the HIR type check
1266 // didn't do this) but it seems sensible to prevent opaque
1267 // types hiding ill-formed types.
1268 obligations.obligations.push(traits::Obligation::new(
1269 ObligationCause::dummy(),
1271 ty::PredicateKind::WellFormed(revealed_ty),
1275 .at(&ObligationCause::dummy(), param_env)
1276 .eq(output_ty, revealed_ty)?,
1279 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1280 let resolved_ty = infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty);
1281 let concrete_is_opaque = if let ty::Opaque(def_id, _) = resolved_ty.kind {
1282 def_id == opaque_def_id
1286 let opaque_defn_ty = match concrete_opaque_types.get(&opaque_def_id) {
1288 if !concrete_is_opaque {
1289 tcx.sess.delay_span_bug(
1292 "Non-defining use of {:?} with revealed type",
1299 Some(opaque_defn_ty) => opaque_defn_ty,
1301 debug!("opaque_defn_ty = {:?}", opaque_defn_ty);
1302 let subst_opaque_defn_ty =
1303 opaque_defn_ty.concrete_type.subst(tcx, opaque_decl.substs);
1304 let renumbered_opaque_defn_ty =
1305 renumber::renumber_regions(infcx, &subst_opaque_defn_ty);
1308 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1309 opaque_decl.concrete_ty, resolved_ty, renumbered_opaque_defn_ty,
1312 if !concrete_is_opaque {
1313 // Equate concrete_ty (an inference variable) with
1314 // the renumbered type from typeck.
1317 .at(&ObligationCause::dummy(), param_env)
1318 .eq(opaque_decl.concrete_ty, renumbered_opaque_defn_ty)?,
1320 opaque_type_values.push((
1322 ty::ResolvedOpaqueTy {
1323 concrete_type: renumbered_opaque_defn_ty,
1324 substs: opaque_decl.substs,
1328 // We're using an opaque `impl Trait` type without
1329 // 'revealing' it. For example, code like this:
1331 // type Foo = impl Debug;
1332 // fn foo1() -> Foo { ... }
1333 // fn foo2() -> Foo { foo1() }
1335 // In `foo2`, we're not revealing the type of `Foo` - we're
1336 // just treating it as the opaque type.
1338 // When this occurs, we do *not* want to try to equate
1339 // the concrete type with the underlying defining type
1340 // of the opaque type - this will always fail, since
1341 // the defining type of an opaque type is always
1342 // some other type (e.g. not itself)
1343 // Essentially, none of the normal obligations apply here -
1344 // we're just passing around some unknown opaque type,
1345 // without actually looking at the underlying type it
1346 // gets 'revealed' into
1348 "eq_opaque_type_and_type: non-defining use of {:?}",
1354 debug!("eq_opaque_type_and_type: equated");
1357 value: Some(opaque_type_map),
1358 obligations: obligations.into_vec(),
1361 || "input_output".to_string(),
1365 self.opaque_type_values.extend(opaque_type_values);
1367 let universal_region_relations = self.universal_region_relations;
1369 // Finally, if we instantiated the anon types successfully, we
1370 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1371 // prove that `T: Iterator` where `T` is the type we
1372 // instantiated it with).
1373 if let Some(opaque_type_map) = opaque_type_map {
1374 for (opaque_def_id, opaque_decl) in opaque_type_map {
1375 self.fully_perform_op(
1377 ConstraintCategory::OpaqueType,
1380 infcx.constrain_opaque_type(
1383 GenerateMemberConstraints::IfNoStaticBound,
1384 universal_region_relations,
1386 Ok(InferOk { value: (), obligations: vec![] })
1388 || "opaque_type_map".to_string(),
1396 fn tcx(&self) -> TyCtxt<'tcx> {
1400 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1401 debug!("check_stmt: {:?}", stmt);
1402 let tcx = self.tcx();
1404 StatementKind::Assign(box (ref place, ref rv)) => {
1405 // Assignments to temporaries are not "interesting";
1406 // they are not caused by the user, but rather artifacts
1407 // of lowering. Assignments to other sorts of places *are* interesting
1409 let category = match place.as_local() {
1410 Some(RETURN_PLACE) => {
1411 if let BorrowCheckContext {
1413 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1415 } = self.borrowck_context
1417 if tcx.is_static(*def_id) {
1418 ConstraintCategory::UseAsStatic
1420 ConstraintCategory::UseAsConst
1423 ConstraintCategory::Return
1426 Some(l) if !body.local_decls[l].is_user_variable() => {
1427 ConstraintCategory::Boring
1429 _ => ConstraintCategory::Assignment,
1432 let place_ty = place.ty(body, tcx).ty;
1433 let place_ty = self.normalize(place_ty, location);
1434 let rv_ty = rv.ty(body, tcx);
1435 let rv_ty = self.normalize(rv_ty, location);
1437 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1442 "bad assignment ({:?} = {:?}): {:?}",
1449 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1450 if let Err(terr) = self.relate_type_and_user_type(
1452 ty::Variance::Invariant,
1453 &UserTypeProjection { base: annotation_index, projs: vec![] },
1454 location.to_locations(),
1455 ConstraintCategory::Boring,
1457 let annotation = &self.user_type_annotations[annotation_index];
1461 "bad user type on rvalue ({:?} = {:?}): {:?}",
1469 self.check_rvalue(body, rv, location);
1470 if !self.tcx().features().unsized_locals {
1471 let trait_ref = ty::TraitRef {
1472 def_id: tcx.require_lang_item(SizedTraitLangItem, Some(self.last_span)),
1473 substs: tcx.mk_substs_trait(place_ty, &[]),
1475 self.prove_trait_ref(
1477 location.to_locations(),
1478 ConstraintCategory::SizedBound,
1482 StatementKind::SetDiscriminant { ref place, variant_index } => {
1483 let place_type = place.ty(body, tcx).ty;
1484 let adt = match place_type.kind {
1485 ty::Adt(adt, _) if adt.is_enum() => adt,
1488 stmt.source_info.span,
1489 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1495 if variant_index.as_usize() >= adt.variants.len() {
1497 stmt.source_info.span,
1498 "bad set discriminant ({:?} = {:?}): value of of range",
1504 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1505 let place_ty = place.ty(body, tcx).ty;
1506 if let Err(terr) = self.relate_type_and_user_type(
1510 Locations::All(stmt.source_info.span),
1511 ConstraintCategory::TypeAnnotation,
1513 let annotation = &self.user_type_annotations[projection.base];
1517 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1525 StatementKind::FakeRead(..)
1526 | StatementKind::StorageLive(..)
1527 | StatementKind::StorageDead(..)
1528 | StatementKind::LlvmInlineAsm { .. }
1529 | StatementKind::Retag { .. }
1530 | StatementKind::Nop => {}
1534 fn check_terminator(
1537 term: &Terminator<'tcx>,
1538 term_location: Location,
1540 debug!("check_terminator: {:?}", term);
1541 let tcx = self.tcx();
1543 TerminatorKind::Goto { .. }
1544 | TerminatorKind::Resume
1545 | TerminatorKind::Abort
1546 | TerminatorKind::Return
1547 | TerminatorKind::GeneratorDrop
1548 | TerminatorKind::Unreachable
1549 | TerminatorKind::Drop { .. }
1550 | TerminatorKind::FalseEdges { .. }
1551 | TerminatorKind::FalseUnwind { .. }
1552 | TerminatorKind::InlineAsm { .. } => {
1553 // no checks needed for these
1556 TerminatorKind::DropAndReplace { ref location, ref value, target: _, unwind: _ } => {
1557 let place_ty = location.ty(body, tcx).ty;
1558 let rv_ty = value.ty(body, tcx);
1560 let locations = term_location.to_locations();
1562 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1567 "bad DropAndReplace ({:?} = {:?}): {:?}",
1574 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1575 let discr_ty = discr.ty(body, tcx);
1576 if let Err(terr) = self.sub_types(
1579 term_location.to_locations(),
1580 ConstraintCategory::Assignment,
1585 "bad SwitchInt ({:?} on {:?}): {:?}",
1591 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1592 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1594 // FIXME: check the values
1596 TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1597 let func_ty = func.ty(body, tcx);
1598 debug!("check_terminator: call, func_ty={:?}", func_ty);
1599 let sig = match func_ty.kind {
1600 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1602 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1606 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1607 term.source_info.span,
1608 LateBoundRegionConversionTime::FnCall,
1611 let sig = self.normalize(sig, term_location);
1612 self.check_call_dest(body, term, &sig, destination, term_location);
1614 self.prove_predicates(
1615 sig.inputs_and_output.iter().map(|ty| ty::PredicateKind::WellFormed(ty)),
1616 term_location.to_locations(),
1617 ConstraintCategory::Boring,
1620 // The ordinary liveness rules will ensure that all
1621 // regions in the type of the callee are live here. We
1622 // then further constrain the late-bound regions that
1623 // were instantiated at the call site to be live as
1624 // well. The resulting is that all the input (and
1625 // output) types in the signature must be live, since
1626 // all the inputs that fed into it were live.
1627 for &late_bound_region in map.values() {
1629 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1630 self.borrowck_context
1632 .liveness_constraints
1633 .add_element(region_vid, term_location);
1636 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1638 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1639 let cond_ty = cond.ty(body, tcx);
1640 if cond_ty != tcx.types.bool {
1641 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1644 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1645 if len.ty(body, tcx) != tcx.types.usize {
1646 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1648 if index.ty(body, tcx) != tcx.types.usize {
1649 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1653 TerminatorKind::Yield { ref value, .. } => {
1654 let value_ty = value.ty(body, tcx);
1655 match body.yield_ty {
1656 None => span_mirbug!(self, term, "yield in non-generator"),
1658 if let Err(terr) = self.sub_types(
1661 term_location.to_locations(),
1662 ConstraintCategory::Yield,
1667 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1682 term: &Terminator<'tcx>,
1683 sig: &ty::FnSig<'tcx>,
1684 destination: &Option<(Place<'tcx>, BasicBlock)>,
1685 term_location: Location,
1687 let tcx = self.tcx();
1688 match *destination {
1689 Some((ref dest, _target_block)) => {
1690 let dest_ty = dest.ty(body, tcx).ty;
1691 let dest_ty = self.normalize(dest_ty, term_location);
1692 let category = match dest.as_local() {
1693 Some(RETURN_PLACE) => {
1694 if let BorrowCheckContext {
1696 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1698 } = self.borrowck_context
1700 if tcx.is_static(*def_id) {
1701 ConstraintCategory::UseAsStatic
1703 ConstraintCategory::UseAsConst
1706 ConstraintCategory::Return
1709 Some(l) if !body.local_decls[l].is_user_variable() => {
1710 ConstraintCategory::Boring
1712 _ => ConstraintCategory::Assignment,
1715 let locations = term_location.to_locations();
1718 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1723 "call dest mismatch ({:?} <- {:?}): {:?}",
1730 // When `#![feature(unsized_locals)]` is not enabled,
1731 // this check is done at `check_local`.
1732 if self.tcx().features().unsized_locals {
1733 let span = term.source_info.span;
1734 self.ensure_place_sized(dest_ty, span);
1738 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1739 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1745 fn check_call_inputs(
1748 term: &Terminator<'tcx>,
1749 sig: &ty::FnSig<'tcx>,
1750 args: &[Operand<'tcx>],
1751 term_location: Location,
1752 from_hir_call: bool,
1754 debug!("check_call_inputs({:?}, {:?})", sig, args);
1755 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1756 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1758 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1759 let op_arg_ty = op_arg.ty(body, self.tcx());
1760 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1761 let category = if from_hir_call {
1762 ConstraintCategory::CallArgument
1764 ConstraintCategory::Boring
1767 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1772 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1782 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1783 let is_cleanup = block_data.is_cleanup;
1784 self.last_span = block_data.terminator().source_info.span;
1785 match block_data.terminator().kind {
1786 TerminatorKind::Goto { target } => {
1787 self.assert_iscleanup(body, block_data, target, is_cleanup)
1789 TerminatorKind::SwitchInt { ref targets, .. } => {
1790 for target in targets {
1791 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1794 TerminatorKind::Resume => {
1796 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1799 TerminatorKind::Abort => {
1801 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1804 TerminatorKind::Return => {
1806 span_mirbug!(self, block_data, "return on cleanup block")
1809 TerminatorKind::GeneratorDrop { .. } => {
1811 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1814 TerminatorKind::Yield { resume, drop, .. } => {
1816 span_mirbug!(self, block_data, "yield in cleanup block")
1818 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1819 if let Some(drop) = drop {
1820 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1823 TerminatorKind::Unreachable => {}
1824 TerminatorKind::Drop { target, unwind, .. }
1825 | TerminatorKind::DropAndReplace { target, unwind, .. }
1826 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1827 self.assert_iscleanup(body, block_data, target, is_cleanup);
1828 if let Some(unwind) = unwind {
1830 span_mirbug!(self, block_data, "unwind on cleanup block")
1832 self.assert_iscleanup(body, block_data, unwind, true);
1835 TerminatorKind::Call { ref destination, cleanup, .. } => {
1836 if let &Some((_, target)) = destination {
1837 self.assert_iscleanup(body, block_data, target, is_cleanup);
1839 if let Some(cleanup) = cleanup {
1841 span_mirbug!(self, block_data, "cleanup on cleanup block")
1843 self.assert_iscleanup(body, block_data, cleanup, true);
1846 TerminatorKind::FalseEdges { real_target, imaginary_target } => {
1847 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1848 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1850 TerminatorKind::FalseUnwind { real_target, unwind } => {
1851 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1852 if let Some(unwind) = unwind {
1854 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1856 self.assert_iscleanup(body, block_data, unwind, true);
1859 TerminatorKind::InlineAsm { ref destination, .. } => {
1860 if let &Some(target) = destination {
1861 self.assert_iscleanup(body, block_data, target, is_cleanup);
1867 fn assert_iscleanup(
1870 ctxt: &dyn fmt::Debug,
1874 if body[bb].is_cleanup != iscleanuppad {
1875 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1879 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1880 match body.local_kind(local) {
1881 LocalKind::ReturnPointer | LocalKind::Arg => {
1882 // return values of normal functions are required to be
1883 // sized by typeck, but return values of ADT constructors are
1884 // not because we don't include a `Self: Sized` bounds on them.
1886 // Unbound parts of arguments were never required to be Sized
1887 // - maybe we should make that a warning.
1890 LocalKind::Var | LocalKind::Temp => {}
1893 // When `#![feature(unsized_locals)]` is enabled, only function calls
1894 // and nullary ops are checked in `check_call_dest`.
1895 if !self.tcx().features().unsized_locals {
1896 let span = local_decl.source_info.span;
1897 let ty = local_decl.ty;
1898 self.ensure_place_sized(ty, span);
1902 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1903 let tcx = self.tcx();
1905 // Erase the regions from `ty` to get a global type. The
1906 // `Sized` bound in no way depends on precise regions, so this
1907 // shouldn't affect `is_sized`.
1908 let erased_ty = tcx.erase_regions(&ty);
1909 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1910 // in current MIR construction, all non-control-flow rvalue
1911 // expressions evaluate through `as_temp` or `into` a return
1912 // slot or local, so to find all unsized rvalues it is enough
1913 // to check all temps, return slots and locals.
1914 if self.reported_errors.replace((ty, span)).is_none() {
1915 let mut diag = struct_span_err!(
1919 "cannot move a value of type {0}: the size of {0} \
1920 cannot be statically determined",
1924 // While this is located in `nll::typeck` this error is not
1925 // an NLL error, it's a required check to prevent creation
1926 // of unsized rvalues in certain cases:
1927 // * operand of a box expression
1928 // * callee in a call expression
1934 fn aggregate_field_ty(
1936 ak: &AggregateKind<'tcx>,
1939 ) -> Result<Ty<'tcx>, FieldAccessError> {
1940 let tcx = self.tcx();
1943 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1944 let variant = &def.variants[variant_index];
1945 let adj_field_index = active_field_index.unwrap_or(field_index);
1946 if let Some(field) = variant.fields.get(adj_field_index) {
1947 Ok(self.normalize(field.ty(tcx, substs), location))
1949 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1952 AggregateKind::Closure(_, substs) => {
1953 match substs.as_closure().upvar_tys().nth(field_index) {
1955 None => Err(FieldAccessError::OutOfRange {
1956 field_count: substs.as_closure().upvar_tys().count(),
1960 AggregateKind::Generator(_, substs, _) => {
1961 // It doesn't make sense to look at a field beyond the prefix;
1962 // these require a variant index, and are not initialized in
1963 // aggregate rvalues.
1964 match substs.as_generator().prefix_tys().nth(field_index) {
1966 None => Err(FieldAccessError::OutOfRange {
1967 field_count: substs.as_generator().prefix_tys().count(),
1971 AggregateKind::Array(ty) => Ok(ty),
1972 AggregateKind::Tuple => {
1973 unreachable!("This should have been covered in check_rvalues");
1978 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1979 let tcx = self.tcx();
1982 Rvalue::Aggregate(ak, ops) => {
1983 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1986 Rvalue::Repeat(operand, len) => {
1987 // If the length cannot be evaluated we must assume that the length can be larger
1989 // If the length is larger than 1, the repeat expression will need to copy the
1990 // element, so we require the `Copy` trait.
1991 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1992 if let Operand::Move(_) = operand {
1993 // While this is located in `nll::typeck` this error is not an NLL error, it's
1994 // a required check to make sure that repeated elements implement `Copy`.
1995 let span = body.source_info(location).span;
1996 let ty = operand.ty(body, tcx);
1997 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1998 let ccx = ConstCx::new_with_param_env(
2004 // To determine if `const_in_array_repeat_expressions` feature gate should
2005 // be mentioned, need to check if the rvalue is promotable.
2006 let should_suggest =
2007 should_suggest_const_in_array_repeat_expressions_attribute(
2010 debug!("check_rvalue: should_suggest={:?}", should_suggest);
2012 self.infcx.report_selection_error(
2013 &traits::Obligation::new(
2014 ObligationCause::new(
2016 self.tcx().hir().local_def_id_to_hir_id(self.mir_def_id),
2017 traits::ObligationCauseCode::RepeatVec(should_suggest),
2020 ty::PredicateKind::Trait(
2021 ty::Binder::bind(ty::TraitPredicate {
2022 trait_ref: ty::TraitRef::new(
2023 self.tcx().require_lang_item(
2025 Some(self.last_span),
2027 tcx.mk_substs_trait(ty, &[]),
2030 hir::Constness::NotConst,
2033 &traits::SelectionError::Unimplemented,
2042 Rvalue::NullaryOp(_, ty) => {
2043 // Even with unsized locals cannot box an unsized value.
2044 if self.tcx().features().unsized_locals {
2045 let span = body.source_info(location).span;
2046 self.ensure_place_sized(ty, span);
2049 let trait_ref = ty::TraitRef {
2050 def_id: tcx.require_lang_item(SizedTraitLangItem, Some(self.last_span)),
2051 substs: tcx.mk_substs_trait(ty, &[]),
2054 self.prove_trait_ref(
2056 location.to_locations(),
2057 ConstraintCategory::SizedBound,
2061 Rvalue::Cast(cast_kind, op, ty) => {
2063 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2064 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2066 // The type that we see in the fcx is like
2067 // `foo::<'a, 'b>`, where `foo` is the path to a
2068 // function definition. When we extract the
2069 // signature, it comes from the `fn_sig` query,
2070 // and hence may contain unnormalized results.
2071 let fn_sig = self.normalize(fn_sig, location);
2073 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2075 if let Err(terr) = self.eq_types(
2078 location.to_locations(),
2079 ConstraintCategory::Cast,
2084 "equating {:?} with {:?} yields {:?}",
2092 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2093 let sig = match op.ty(body, tcx).kind {
2094 ty::Closure(_, substs) => substs.as_closure().sig(),
2097 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
2099 if let Err(terr) = self.eq_types(
2102 location.to_locations(),
2103 ConstraintCategory::Cast,
2108 "equating {:?} with {:?} yields {:?}",
2116 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2117 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2119 // The type that we see in the fcx is like
2120 // `foo::<'a, 'b>`, where `foo` is the path to a
2121 // function definition. When we extract the
2122 // signature, it comes from the `fn_sig` query,
2123 // and hence may contain unnormalized results.
2124 let fn_sig = self.normalize(fn_sig, location);
2126 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2128 if let Err(terr) = self.eq_types(
2131 location.to_locations(),
2132 ConstraintCategory::Cast,
2137 "equating {:?} with {:?} yields {:?}",
2145 CastKind::Pointer(PointerCast::Unsize) => {
2147 let trait_ref = ty::TraitRef {
2148 def_id: tcx.require_lang_item(
2149 CoerceUnsizedTraitLangItem,
2150 Some(self.last_span),
2152 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2155 self.prove_trait_ref(
2157 location.to_locations(),
2158 ConstraintCategory::Cast,
2162 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2163 let ty_from = match op.ty(body, tcx).kind {
2164 ty::RawPtr(ty::TypeAndMut {
2166 mutbl: hir::Mutability::Mut,
2172 "unexpected base type for cast {:?}",
2178 let ty_to = match ty.kind {
2179 ty::RawPtr(ty::TypeAndMut {
2181 mutbl: hir::Mutability::Not,
2187 "unexpected target type for cast {:?}",
2193 if let Err(terr) = self.sub_types(
2196 location.to_locations(),
2197 ConstraintCategory::Cast,
2202 "relating {:?} with {:?} yields {:?}",
2210 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2211 let ty_from = op.ty(body, tcx);
2213 let opt_ty_elem = match ty_from.kind {
2214 ty::RawPtr(ty::TypeAndMut {
2215 mutbl: hir::Mutability::Not,
2217 }) => match array_ty.kind {
2218 ty::Array(ty_elem, _) => Some(ty_elem),
2224 let ty_elem = match opt_ty_elem {
2225 Some(ty_elem) => ty_elem,
2230 "ArrayToPointer cast from unexpected type {:?}",
2237 let ty_to = match ty.kind {
2238 ty::RawPtr(ty::TypeAndMut {
2239 mutbl: hir::Mutability::Not,
2246 "ArrayToPointer cast to unexpected type {:?}",
2253 if let Err(terr) = self.sub_types(
2256 location.to_locations(),
2257 ConstraintCategory::Cast,
2262 "relating {:?} with {:?} yields {:?}",
2271 let ty_from = op.ty(body, tcx);
2272 let cast_ty_from = CastTy::from_ty(ty_from);
2273 let cast_ty_to = CastTy::from_ty(ty);
2274 match (cast_ty_from, cast_ty_to) {
2276 | (_, None | Some(CastTy::FnPtr))
2277 | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2278 | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => {
2279 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2282 Some(CastTy::Int(_)),
2283 Some(CastTy::Int(_) | CastTy::Float | CastTy::Ptr(_)),
2285 | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float))
2286 | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_)))
2287 | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (),
2293 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2294 self.add_reborrow_constraint(&body, location, region, borrowed_place);
2298 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2302 let ty_left = left.ty(body, tcx);
2303 match ty_left.kind {
2304 // Types with regions are comparable if they have a common super-type.
2305 ty::RawPtr(_) | ty::FnPtr(_) => {
2306 let ty_right = right.ty(body, tcx);
2307 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2308 kind: TypeVariableOriginKind::MiscVariable,
2309 span: body.source_info(location).span,
2313 ty::Variance::Contravariant,
2315 location.to_locations(),
2316 ConstraintCategory::Boring,
2318 .unwrap_or_else(|err| {
2319 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2321 if let Err(terr) = self.relate_types(
2323 ty::Variance::Contravariant,
2325 location.to_locations(),
2326 ConstraintCategory::Boring,
2331 "unexpected comparison types {:?} and {:?} yields {:?}",
2338 // For types with no regions we can just check that the
2339 // both operands have the same type.
2340 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2341 if ty_left == right.ty(body, tcx) => {}
2342 // Other types are compared by trait methods, not by
2343 // `Rvalue::BinaryOp`.
2347 "unexpected comparison types {:?} and {:?}",
2354 Rvalue::AddressOf(..)
2357 | Rvalue::BinaryOp(..)
2358 | Rvalue::CheckedBinaryOp(..)
2359 | Rvalue::UnaryOp(..)
2360 | Rvalue::Discriminant(..) => {}
2364 /// If this rvalue supports a user-given type annotation, then
2365 /// extract and return it. This represents the final type of the
2366 /// rvalue and will be unified with the inferred type.
2367 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2370 | Rvalue::Repeat(..)
2372 | Rvalue::AddressOf(..)
2375 | Rvalue::BinaryOp(..)
2376 | Rvalue::CheckedBinaryOp(..)
2377 | Rvalue::NullaryOp(..)
2378 | Rvalue::UnaryOp(..)
2379 | Rvalue::Discriminant(..) => None,
2381 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2382 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2383 AggregateKind::Array(_) => None,
2384 AggregateKind::Tuple => None,
2385 AggregateKind::Closure(_, _) => None,
2386 AggregateKind::Generator(_, _, _) => None,
2391 fn check_aggregate_rvalue(
2394 rvalue: &Rvalue<'tcx>,
2395 aggregate_kind: &AggregateKind<'tcx>,
2396 operands: &[Operand<'tcx>],
2399 let tcx = self.tcx();
2401 self.prove_aggregate_predicates(aggregate_kind, location);
2403 if *aggregate_kind == AggregateKind::Tuple {
2404 // tuple rvalue field type is always the type of the op. Nothing to check here.
2408 for (i, operand) in operands.iter().enumerate() {
2409 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2410 Ok(field_ty) => field_ty,
2411 Err(FieldAccessError::OutOfRange { field_count }) => {
2415 "accessed field #{} but variant only has {}",
2422 let operand_ty = operand.ty(body, tcx);
2423 let operand_ty = self.normalize(operand_ty, location);
2425 if let Err(terr) = self.sub_types(
2428 location.to_locations(),
2429 ConstraintCategory::Boring,
2434 "{:?} is not a subtype of {:?}: {:?}",
2443 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2447 /// - `location`: the location `L` where the borrow expression occurs
2448 /// - `borrow_region`: the region `'a` associated with the borrow
2449 /// - `borrowed_place`: the place `P` being borrowed
2450 fn add_reborrow_constraint(
2454 borrow_region: ty::Region<'tcx>,
2455 borrowed_place: &Place<'tcx>,
2457 // These constraints are only meaningful during borrowck:
2458 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2459 self.borrowck_context;
2461 // In Polonius mode, we also push a `borrow_region` fact
2462 // linking the loan to the region (in some cases, though,
2463 // there is no loan associated with this borrow expression --
2464 // that occurs when we are borrowing an unsafe place, for
2466 if let Some(all_facts) = all_facts {
2467 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2468 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2469 let region_vid = borrow_region.to_region_vid();
2470 all_facts.borrow_region.push((
2473 location_table.mid_index(location),
2478 // If we are reborrowing the referent of another reference, we
2479 // need to add outlives relationships. In a case like `&mut
2480 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2481 // need to ensure that `'b: 'a`.
2484 "add_reborrow_constraint({:?}, {:?}, {:?})",
2485 location, borrow_region, borrowed_place
2488 let mut cursor = borrowed_place.projection.as_ref();
2489 while let [proj_base @ .., elem] = cursor {
2492 debug!("add_reborrow_constraint - iteration {:?}", elem);
2495 ProjectionElem::Deref => {
2496 let tcx = self.infcx.tcx;
2497 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2499 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2500 match base_ty.kind {
2501 ty::Ref(ref_region, _, mutbl) => {
2502 constraints.outlives_constraints.push(OutlivesConstraint {
2503 sup: ref_region.to_region_vid(),
2504 sub: borrow_region.to_region_vid(),
2505 locations: location.to_locations(),
2506 category: ConstraintCategory::Boring,
2510 hir::Mutability::Not => {
2511 // Immutable reference. We don't need the base
2512 // to be valid for the entire lifetime of
2516 hir::Mutability::Mut => {
2517 // Mutable reference. We *do* need the base
2518 // to be valid, because after the base becomes
2519 // invalid, someone else can use our mutable deref.
2521 // This is in order to make the following function
2524 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2529 // As otherwise you could clone `&mut T` using the
2530 // following function:
2532 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2533 // let my_clone = unsafe_deref(&'a x);
2542 // deref of raw pointer, guaranteed to be valid
2545 ty::Adt(def, _) if def.is_box() => {
2546 // deref of `Box`, need the base to be valid - propagate
2548 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2551 ProjectionElem::Field(..)
2552 | ProjectionElem::Downcast(..)
2553 | ProjectionElem::Index(..)
2554 | ProjectionElem::ConstantIndex { .. }
2555 | ProjectionElem::Subslice { .. } => {
2556 // other field access
2562 fn prove_aggregate_predicates(
2564 aggregate_kind: &AggregateKind<'tcx>,
2567 let tcx = self.tcx();
2570 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2571 aggregate_kind, location
2574 let instantiated_predicates = match aggregate_kind {
2575 AggregateKind::Adt(def, _, substs, _, _) => {
2576 tcx.predicates_of(def.did).instantiate(tcx, substs)
2579 // For closures, we have some **extra requirements** we
2581 // have to check. In particular, in their upvars and
2582 // signatures, closures often reference various regions
2583 // from the surrounding function -- we call those the
2584 // closure's free regions. When we borrow-check (and hence
2585 // region-check) closures, we may find that the closure
2586 // requires certain relationships between those free
2587 // regions. However, because those free regions refer to
2588 // portions of the CFG of their caller, the closure is not
2589 // in a position to verify those relationships. In that
2590 // case, the requirements get "propagated" to us, and so
2591 // we have to solve them here where we instantiate the
2594 // Despite the opacity of the previous parapgrah, this is
2595 // actually relatively easy to understand in terms of the
2596 // desugaring. A closure gets desugared to a struct, and
2597 // these extra requirements are basically like where
2598 // clauses on the struct.
2599 AggregateKind::Closure(def_id, substs)
2600 | AggregateKind::Generator(def_id, substs, _) => {
2601 self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location)
2604 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2607 self.normalize_and_prove_instantiated_predicates(
2608 instantiated_predicates,
2609 location.to_locations(),
2613 fn prove_closure_bounds(
2617 substs: SubstsRef<'tcx>,
2619 ) -> ty::InstantiatedPredicates<'tcx> {
2620 if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2622 let closure_constraints = QueryRegionConstraints {
2623 outlives: closure_region_requirements.apply_requirements(
2629 // Presently, closures never propagate member
2630 // constraints to their parents -- they are enforced
2631 // locally. This is largely a non-issue as member
2632 // constraints only come from `-> impl Trait` and
2633 // friends which don't appear (thus far...) in
2635 member_constraints: vec![],
2638 let bounds_mapping = closure_constraints
2642 .filter_map(|(idx, constraint)| {
2643 let ty::OutlivesPredicate(k1, r2) =
2644 constraint.no_bound_vars().unwrap_or_else(|| {
2645 bug!("query_constraint {:?} contained bound vars", constraint,);
2649 GenericArgKind::Lifetime(r1) => {
2650 // constraint is r1: r2
2651 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2652 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2653 let outlives_requirements =
2654 &closure_region_requirements.outlives_requirements[idx];
2657 (outlives_requirements.category, outlives_requirements.blame_span),
2660 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2668 .closure_bounds_mapping
2669 .insert(location, bounds_mapping);
2670 assert!(existing.is_none(), "Multiple closures at the same location.");
2672 self.push_region_constraints(
2673 location.to_locations(),
2674 ConstraintCategory::ClosureBounds,
2675 &closure_constraints,
2679 tcx.predicates_of(def_id).instantiate(tcx, substs)
2684 trait_ref: ty::TraitRef<'tcx>,
2685 locations: Locations,
2686 category: ConstraintCategory,
2688 self.prove_predicates(
2689 Some(ty::PredicateKind::Trait(
2690 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2691 hir::Constness::NotConst,
2698 fn normalize_and_prove_instantiated_predicates(
2700 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2701 locations: Locations,
2703 for predicate in instantiated_predicates.predicates {
2704 let predicate = self.normalize(predicate, locations);
2705 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2709 fn prove_predicates(
2711 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2712 locations: Locations,
2713 category: ConstraintCategory,
2715 for predicate in predicates {
2716 debug!("prove_predicates(predicate={:?}, locations={:?})", predicate, locations,);
2718 self.prove_predicate(predicate, locations, category);
2724 predicate: ty::Predicate<'tcx>,
2725 locations: Locations,
2726 category: ConstraintCategory,
2728 debug!("prove_predicate(predicate={:?}, location={:?})", predicate, locations,);
2730 let param_env = self.param_env;
2731 self.fully_perform_op(
2734 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2736 .unwrap_or_else(|NoSolution| {
2737 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2741 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2742 self.last_span = body.span;
2743 debug!("run_on_mir: {:?}", body.span);
2745 for (local, local_decl) in body.local_decls.iter_enumerated() {
2746 self.check_local(&body, local, local_decl);
2749 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2750 let mut location = Location { block, statement_index: 0 };
2751 for stmt in &block_data.statements {
2752 if !stmt.source_info.span.is_dummy() {
2753 self.last_span = stmt.source_info.span;
2755 self.check_stmt(body, stmt, location);
2756 location.statement_index += 1;
2759 self.check_terminator(&body, block_data.terminator(), location);
2760 self.check_iscleanup(&body, block_data);
2764 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2766 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2768 debug!("normalize(value={:?}, location={:?})", value, location);
2769 let param_env = self.param_env;
2770 self.fully_perform_op(
2771 location.to_locations(),
2772 ConstraintCategory::Boring,
2773 param_env.and(type_op::normalize::Normalize::new(value)),
2775 .unwrap_or_else(|NoSolution| {
2776 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2782 trait NormalizeLocation: fmt::Debug + Copy {
2783 fn to_locations(self) -> Locations;
2786 impl NormalizeLocation for Locations {
2787 fn to_locations(self) -> Locations {
2792 impl NormalizeLocation for Location {
2793 fn to_locations(self) -> Locations {
2794 Locations::Single(self)
2798 #[derive(Debug, Default)]
2799 struct ObligationAccumulator<'tcx> {
2800 obligations: PredicateObligations<'tcx>,
2803 impl<'tcx> ObligationAccumulator<'tcx> {
2804 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2805 let InferOk { value, obligations } = value;
2806 self.obligations.extend(obligations);
2810 fn into_vec(self) -> PredicateObligations<'tcx> {