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::LangItem;
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, ToPredicate, Ty,
31 TyCtxt, UserType, UserTypeAnnotationIndex, WithConstness,
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,
59 region_infer::values::{
60 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
62 region_infer::{ClosureRegionRequirementsExt, TypeTest},
64 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
65 universal_regions::{DefiningTy, UniversalRegions},
69 macro_rules! span_mirbug {
70 ($context:expr, $elem:expr, $($message:tt)*) => ({
71 $crate::borrow_check::type_check::mirbug(
75 "broken MIR in {:?} ({:?}): {}",
76 $context.body.source.def_id(),
78 format_args!($($message)*),
84 macro_rules! span_mirbug_and_err {
85 ($context:expr, $elem:expr, $($message:tt)*) => ({
87 span_mirbug!($context, $elem, $($message)*);
93 mod constraint_conversion;
94 pub mod free_region_relations;
99 /// Type checks the given `mir` in the context of the inference
100 /// context `infcx`. Returns any region constraints that have yet to
101 /// be proven. This result is includes liveness constraints that
102 /// ensure that regions appearing in the types of all local variables
103 /// are live at all points where that local variable may later be
106 /// This phase of type-check ought to be infallible -- this is because
107 /// the original, HIR-based type-check succeeded. So if any errors
108 /// occur here, we will get a `bug!` reported.
112 /// - `infcx` -- inference context to use
113 /// - `param_env` -- parameter environment to use for trait solving
114 /// - `body` -- MIR body to type-check
115 /// - `promoted` -- map of promoted constants within `body`
116 /// - `universal_regions` -- the universal regions from `body`s function signature
117 /// - `location_table` -- MIR location map of `body`
118 /// - `borrow_set` -- information about borrows occurring in `body`
119 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
120 /// - `flow_inits` -- results of a maybe-init dataflow analysis
121 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
122 /// - `elements` -- MIR region map
123 pub(crate) fn type_check<'mir, 'tcx>(
124 infcx: &InferCtxt<'_, 'tcx>,
125 param_env: ty::ParamEnv<'tcx>,
127 promoted: &IndexVec<Promoted, Body<'tcx>>,
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>,
136 ) -> MirTypeckResults<'tcx> {
137 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
138 let mut constraints = MirTypeckRegionConstraints {
139 placeholder_indices: PlaceholderIndices::default(),
140 placeholder_index_to_region: IndexVec::default(),
141 liveness_constraints: LivenessValues::new(elements.clone()),
142 outlives_constraints: OutlivesConstraintSet::default(),
143 member_constraints: MemberConstraintSet::default(),
144 closure_bounds_mapping: Default::default(),
145 type_tests: Vec::default(),
149 universal_region_relations,
151 normalized_inputs_and_output,
152 } = free_region_relations::create(
155 Some(implicit_region_bound),
160 let mut borrowck_context = BorrowCheckContext {
165 constraints: &mut constraints,
169 let opaque_type_values = type_check_internal(
175 implicit_region_bound,
176 &mut borrowck_context,
177 &universal_region_relations,
179 cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
180 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
182 translate_outlives_facts(&mut cx);
183 cx.opaque_type_values
187 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
190 fn type_check_internal<'a, 'tcx, R>(
191 infcx: &'a InferCtxt<'a, 'tcx>,
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(
206 implicit_region_bound,
208 universal_region_relations,
210 let errors_reported = {
211 let mut verifier = TypeVerifier::new(&mut checker, body, promoted);
212 verifier.visit_body(&body);
213 verifier.errors_reported
216 if !errors_reported {
217 // if verifier failed, don't do further checks to avoid ICEs
218 checker.typeck_mir(body);
224 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
225 let cx = &mut typeck.borrowck_context;
226 if let Some(facts) = cx.all_facts {
227 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
228 let location_table = cx.location_table;
229 facts.outlives.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
230 |constraint: &OutlivesConstraint| {
231 if let Some(from_location) = constraint.locations.from_location() {
232 Either::Left(iter::once((
235 location_table.mid_index(from_location),
241 .map(move |location| (constraint.sup, constraint.sub, location)),
249 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
250 // We sometimes see MIR failures (notably predicate failures) due to
251 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
252 // to avoid reporting bugs in those cases.
253 tcx.sess.diagnostic().delay_span_bug(span, msg);
256 enum FieldAccessError {
257 OutOfRange { field_count: usize },
260 /// Verifies that MIR types are sane to not crash further checks.
262 /// The sanitize_XYZ methods here take an MIR object and compute its
263 /// type, calling `span_mirbug` and returning an error type if there
265 struct TypeVerifier<'a, 'b, 'tcx> {
266 cx: &'a mut TypeChecker<'b, 'tcx>,
267 body: &'b Body<'tcx>,
268 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
270 errors_reported: bool,
273 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
274 fn visit_span(&mut self, span: &Span) {
275 if !span.is_dummy() {
276 self.last_span = *span;
280 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
281 self.sanitize_place(place, location, context);
284 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
285 self.super_constant(constant, location);
286 let ty = self.sanitize_type(constant, constant.literal.ty);
288 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
289 let live_region_vid =
290 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
294 .liveness_constraints
295 .add_element(live_region_vid, location);
298 if let Some(annotation_index) = constant.user_ty {
299 if let Err(terr) = self.cx.relate_type_and_user_type(
301 ty::Variance::Invariant,
302 &UserTypeProjection { base: annotation_index, projs: vec![] },
303 location.to_locations(),
304 ConstraintCategory::Boring,
306 let annotation = &self.cx.user_type_annotations[annotation_index];
310 "bad constant user type {:?} vs {:?}: {:?}",
317 let tcx = self.tcx();
318 if let ty::ConstKind::Unevaluated(def, substs, promoted) = constant.literal.val {
319 if let Some(promoted) = promoted {
320 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
321 promoted: &Body<'tcx>,
324 if let Err(terr) = verifier.cx.eq_types(
327 location.to_locations(),
328 ConstraintCategory::Boring,
333 "bad promoted type ({:?}: {:?}): {:?}",
341 if !self.errors_reported {
342 let promoted_body = &self.promoted[promoted];
343 self.sanitize_promoted(promoted_body, location);
345 let promoted_ty = promoted_body.return_ty();
346 check_err(self, promoted_body, ty, promoted_ty);
349 if let Err(terr) = self.cx.fully_perform_op(
350 location.to_locations(),
351 ConstraintCategory::Boring,
352 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
355 UserSubsts { substs, user_self_ty: None },
361 "bad constant type {:?} ({:?})",
367 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
368 let unnormalized_ty = tcx.type_of(static_def_id);
369 let locations = location.to_locations();
370 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
371 let literal_ty = constant.literal.ty.builtin_deref(true).unwrap().ty;
373 if let Err(terr) = self.cx.eq_types(
377 ConstraintCategory::Boring,
379 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
383 if let ty::FnDef(def_id, substs) = *constant.literal.ty.kind() {
384 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
385 self.cx.normalize_and_prove_instantiated_predicates(
386 instantiated_predicates,
387 location.to_locations(),
393 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
394 self.super_rvalue(rvalue, location);
395 let rval_ty = rvalue.ty(self.body, self.tcx());
396 self.sanitize_type(rvalue, rval_ty);
399 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
400 self.super_local_decl(local, local_decl);
401 self.sanitize_type(local_decl, local_decl.ty);
403 if let Some(user_ty) = &local_decl.user_ty {
404 for (user_ty, span) in user_ty.projections_and_spans() {
405 let ty = if !local_decl.is_nonref_binding() {
406 // If we have a binding of the form `let ref x: T = ..`
407 // then remove the outermost reference so we can check the
408 // type annotation for the remaining type.
409 if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
412 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
418 if let Err(terr) = self.cx.relate_type_and_user_type(
420 ty::Variance::Invariant,
422 Locations::All(*span),
423 ConstraintCategory::TypeAnnotation,
428 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
439 fn visit_body(&mut self, body: &Body<'tcx>) {
440 self.sanitize_type(&"return type", body.return_ty());
441 for local_decl in &body.local_decls {
442 self.sanitize_type(local_decl, local_decl.ty);
444 if self.errors_reported {
447 self.super_body(body);
451 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
453 cx: &'a mut TypeChecker<'b, 'tcx>,
454 body: &'b Body<'tcx>,
455 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
457 TypeVerifier { body, promoted, cx, last_span: body.span, errors_reported: false }
460 fn tcx(&self) -> TyCtxt<'tcx> {
464 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
465 if ty.has_escaping_bound_vars() || ty.references_error() {
466 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
472 /// Checks that the types internal to the `place` match up with
473 /// what would be expected.
478 context: PlaceContext,
480 debug!("sanitize_place: {:?}", place);
482 let mut place_ty = PlaceTy::from_ty(self.body.local_decls[place.local].ty);
484 for elem in place.projection.iter() {
485 if place_ty.variant_index.is_none() {
486 if place_ty.ty.references_error() {
487 assert!(self.errors_reported);
488 return PlaceTy::from_ty(self.tcx().ty_error());
491 place_ty = self.sanitize_projection(place_ty, elem, place, location)
494 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
495 let tcx = self.tcx();
496 let trait_ref = ty::TraitRef {
497 def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
498 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
501 // To have a `Copy` operand, the type `T` of the
502 // value must be `Copy`. Note that we prove that `T: Copy`,
503 // rather than using the `is_copy_modulo_regions`
504 // test. This is important because
505 // `is_copy_modulo_regions` ignores the resulting region
506 // obligations and assumes they pass. This can result in
507 // bounds from `Copy` impls being unsoundly ignored (e.g.,
508 // #29149). Note that we decide to use `Copy` before knowing
509 // whether the bounds fully apply: in effect, the rule is
510 // that if a value of some type could implement `Copy`, then
512 self.cx.prove_trait_ref(
514 location.to_locations(),
515 ConstraintCategory::CopyBound,
522 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
523 // Determine the constraints from the promoted MIR by running the type
524 // checker on the promoted MIR, then transfer the constraints back to
525 // the main MIR, changing the locations to the provided location.
527 let parent_body = mem::replace(&mut self.body, promoted_body);
529 // Use new sets of constraints and closure bounds so that we can
530 // modify their locations.
531 let all_facts = &mut None;
532 let mut constraints = Default::default();
533 let mut closure_bounds = Default::default();
534 let mut liveness_constraints =
535 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
536 // Don't try to add borrow_region facts for the promoted MIR
538 let mut swap_constraints = |this: &mut Self| {
539 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
541 &mut this.cx.borrowck_context.constraints.outlives_constraints,
545 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
549 &mut this.cx.borrowck_context.constraints.liveness_constraints,
550 &mut liveness_constraints,
554 swap_constraints(self);
556 self.visit_body(&promoted_body);
558 if !self.errors_reported {
559 // if verifier failed, don't do further checks to avoid ICEs
560 self.cx.typeck_mir(promoted_body);
563 self.body = parent_body;
564 // Merge the outlives constraints back in, at the given location.
565 swap_constraints(self);
567 let locations = location.to_locations();
568 for constraint in constraints.outlives().iter() {
569 let mut constraint = *constraint;
570 constraint.locations = locations;
571 if let ConstraintCategory::Return(_)
572 | ConstraintCategory::UseAsConst
573 | ConstraintCategory::UseAsStatic = constraint.category
575 // "Returning" from a promoted is an assignment to a
576 // temporary from the user's point of view.
577 constraint.category = ConstraintCategory::Boring;
579 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
581 for live_region in liveness_constraints.rows() {
585 .liveness_constraints
586 .add_element(live_region, location);
589 if !closure_bounds.is_empty() {
590 let combined_bounds_mapping =
591 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
596 .closure_bounds_mapping
597 .insert(location, combined_bounds_mapping);
598 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
602 fn sanitize_projection(
609 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
610 let tcx = self.tcx();
611 let base_ty = base.ty;
613 ProjectionElem::Deref => {
614 let deref_ty = base_ty.builtin_deref(true);
615 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
616 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
619 ProjectionElem::Index(i) => {
620 let index_ty = Place::from(i).ty(self.body, tcx).ty;
621 if index_ty != tcx.types.usize {
622 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
624 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
625 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
629 ProjectionElem::ConstantIndex { .. } => {
630 // consider verifying in-bounds
631 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
632 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
635 ProjectionElem::Subslice { from, to, from_end } => {
636 PlaceTy::from_ty(match base_ty.kind() {
637 ty::Array(inner, _) => {
638 assert!(!from_end, "array subslices should not use from_end");
639 tcx.mk_array(inner, to - from)
642 assert!(from_end, "slice subslices should use from_end");
645 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
648 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
649 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
650 if index.as_usize() >= adt_def.variants.len() {
651 PlaceTy::from_ty(span_mirbug_and_err!(
654 "cast to variant #{:?} but enum only has {:?}",
656 adt_def.variants.len()
659 PlaceTy { ty: base_ty, variant_index: Some(index) }
662 // We do not need to handle generators here, because this runs
663 // before the generator transform stage.
665 let ty = if let Some(name) = maybe_name {
666 span_mirbug_and_err!(
669 "can't downcast {:?} as {:?}",
674 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
679 ProjectionElem::Field(field, fty) => {
680 let fty = self.sanitize_type(place, fty);
681 match self.field_ty(place, base, field, location) {
683 let ty = self.cx.normalize(ty, location);
684 if let Err(terr) = self.cx.eq_types(
687 location.to_locations(),
688 ConstraintCategory::Boring,
693 "bad field access ({:?}: {:?}): {:?}",
700 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
703 "accessed field #{} but variant only has {}",
708 PlaceTy::from_ty(fty)
713 fn error(&mut self) -> Ty<'tcx> {
714 self.errors_reported = true;
715 self.tcx().ty_error()
720 parent: &dyn fmt::Debug,
721 base_ty: PlaceTy<'tcx>,
724 ) -> Result<Ty<'tcx>, FieldAccessError> {
725 let tcx = self.tcx();
727 let (variant, substs) = match base_ty {
728 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
729 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
730 ty::Generator(def_id, substs, _) => {
731 let mut variants = substs.as_generator().state_tys(def_id, tcx);
732 let mut variant = match variants.nth(variant_index.into()) {
735 "variant_index of generator out of range: {:?}/{:?}",
737 substs.as_generator().state_tys(def_id, tcx).count()
740 return match variant.nth(field.index()) {
742 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
745 _ => bug!("can't have downcast of non-adt non-generator type"),
747 PlaceTy { ty, variant_index: None } => match *ty.kind() {
748 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
749 (&adt_def.variants[VariantIdx::new(0)], substs)
751 ty::Closure(_, substs) => {
752 return match substs.as_closure().upvar_tys().nth(field.index()) {
754 None => Err(FieldAccessError::OutOfRange {
755 field_count: substs.as_closure().upvar_tys().count(),
759 ty::Generator(_, substs, _) => {
760 // Only prefix fields (upvars and current state) are
761 // accessible without a variant index.
762 return match substs.as_generator().prefix_tys().nth(field.index()) {
764 None => Err(FieldAccessError::OutOfRange {
765 field_count: substs.as_generator().prefix_tys().count(),
770 return match tys.get(field.index()) {
771 Some(&ty) => Ok(ty.expect_ty()),
772 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
776 return Ok(span_mirbug_and_err!(
779 "can't project out of {:?}",
786 if let Some(field) = variant.fields.get(field.index()) {
787 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
789 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
794 /// The MIR type checker. Visits the MIR and enforces all the
795 /// constraints needed for it to be valid and well-typed. Along the
796 /// way, it accrues region constraints -- these can later be used by
797 /// NLL region checking.
798 struct TypeChecker<'a, 'tcx> {
799 infcx: &'a InferCtxt<'a, 'tcx>,
800 param_env: ty::ParamEnv<'tcx>,
802 body: &'a Body<'tcx>,
803 /// User type annotations are shared between the main MIR and the MIR of
804 /// all of the promoted items.
805 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
806 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
807 implicit_region_bound: ty::Region<'tcx>,
808 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
809 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
810 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
811 opaque_type_values: FxHashMap<DefId, ty::ResolvedOpaqueTy<'tcx>>,
814 struct BorrowCheckContext<'a, 'tcx> {
815 universal_regions: &'a UniversalRegions<'tcx>,
816 location_table: &'a LocationTable,
817 all_facts: &'a mut Option<AllFacts>,
818 borrow_set: &'a BorrowSet<'tcx>,
819 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
823 crate struct MirTypeckResults<'tcx> {
824 crate constraints: MirTypeckRegionConstraints<'tcx>,
825 pub(in crate::borrow_check) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
826 crate opaque_type_values: FxHashMap<DefId, ty::ResolvedOpaqueTy<'tcx>>,
829 /// A collection of region constraints that must be satisfied for the
830 /// program to be considered well-typed.
831 crate struct MirTypeckRegionConstraints<'tcx> {
832 /// Maps from a `ty::Placeholder` to the corresponding
833 /// `PlaceholderIndex` bit that we will use for it.
835 /// To keep everything in sync, do not insert this set
836 /// directly. Instead, use the `placeholder_region` helper.
837 crate placeholder_indices: PlaceholderIndices,
839 /// Each time we add a placeholder to `placeholder_indices`, we
840 /// also create a corresponding "representative" region vid for
841 /// that wraps it. This vector tracks those. This way, when we
842 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
843 /// the same underlying `RegionVid`.
844 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
846 /// In general, the type-checker is not responsible for enforcing
847 /// liveness constraints; this job falls to the region inferencer,
848 /// which performs a liveness analysis. However, in some limited
849 /// cases, the MIR type-checker creates temporary regions that do
850 /// not otherwise appear in the MIR -- in particular, the
851 /// late-bound regions that it instantiates at call-sites -- and
852 /// hence it must report on their liveness constraints.
853 crate liveness_constraints: LivenessValues<RegionVid>,
855 crate outlives_constraints: OutlivesConstraintSet,
857 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
859 crate closure_bounds_mapping:
860 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
862 crate type_tests: Vec<TypeTest<'tcx>>,
865 impl MirTypeckRegionConstraints<'tcx> {
866 fn placeholder_region(
868 infcx: &InferCtxt<'_, 'tcx>,
869 placeholder: ty::PlaceholderRegion,
870 ) -> ty::Region<'tcx> {
871 let placeholder_index = self.placeholder_indices.insert(placeholder);
872 match self.placeholder_index_to_region.get(placeholder_index) {
875 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
876 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
877 self.placeholder_index_to_region.push(region);
884 /// The `Locations` type summarizes *where* region constraints are
885 /// required to hold. Normally, this is at a particular point which
886 /// created the obligation, but for constraints that the user gave, we
887 /// want the constraint to hold at all points.
888 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
890 /// Indicates that a type constraint should always be true. This
891 /// is particularly important in the new borrowck analysis for
892 /// things like the type of the return slot. Consider this
896 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
898 /// return &y; // error
902 /// Here, we wind up with the signature from the return type being
903 /// something like `&'1 u32` where `'1` is a universal region. But
904 /// the type of the return slot `_0` is something like `&'2 u32`
905 /// where `'2` is an existential region variable. The type checker
906 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
907 /// older NLL analysis, we required this only at the entry point
908 /// to the function. By the nature of the constraints, this wound
909 /// up propagating to all points reachable from start (because
910 /// `'1` -- as a universal region -- is live everywhere). In the
911 /// newer analysis, though, this doesn't work: `_0` is considered
912 /// dead at the start (it has no usable value) and hence this type
913 /// equality is basically a no-op. Then, later on, when we do `_0
914 /// = &'3 y`, that region `'3` never winds up related to the
915 /// universal region `'1` and hence no error occurs. Therefore, we
916 /// use Locations::All instead, which ensures that the `'1` and
917 /// `'2` are equal everything. We also use this for other
918 /// user-given type annotations; e.g., if the user wrote `let mut
919 /// x: &'static u32 = ...`, we would ensure that all values
920 /// assigned to `x` are of `'static` lifetime.
922 /// The span points to the place the constraint arose. For example,
923 /// it points to the type in a user-given type annotation. If
924 /// there's no sensible span then it's DUMMY_SP.
927 /// An outlives constraint that only has to hold at a single location,
928 /// usually it represents a point where references flow from one spot to
929 /// another (e.g., `x = y`)
934 pub fn from_location(&self) -> Option<Location> {
936 Locations::All(_) => None,
937 Locations::Single(from_location) => Some(*from_location),
941 /// Gets a span representing the location.
942 pub fn span(&self, body: &Body<'_>) -> Span {
944 Locations::All(span) => *span,
945 Locations::Single(l) => body.source_info(*l).span,
950 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
952 infcx: &'a InferCtxt<'a, 'tcx>,
953 body: &'a Body<'tcx>,
954 param_env: ty::ParamEnv<'tcx>,
955 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
956 implicit_region_bound: ty::Region<'tcx>,
957 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
958 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
960 let mut checker = Self {
964 user_type_annotations: &body.user_type_annotations,
967 implicit_region_bound,
969 reported_errors: Default::default(),
970 universal_region_relations,
971 opaque_type_values: FxHashMap::default(),
973 checker.check_user_type_annotations();
977 /// Equate the inferred type and the annotated type for user type annotations
978 fn check_user_type_annotations(&mut self) {
980 "check_user_type_annotations: user_type_annotations={:?}",
981 self.user_type_annotations
983 for user_annotation in self.user_type_annotations {
984 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
985 let (annotation, _) =
986 self.infcx.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
988 UserType::Ty(mut ty) => {
989 ty = self.normalize(ty, Locations::All(span));
991 if let Err(terr) = self.eq_types(
994 Locations::All(span),
995 ConstraintCategory::BoringNoLocation,
1000 "bad user type ({:?} = {:?}): {:?}",
1007 self.prove_predicate(
1008 ty::PredicateAtom::WellFormed(inferred_ty.into()).to_predicate(self.tcx()),
1009 Locations::All(span),
1010 ConstraintCategory::TypeAnnotation,
1013 UserType::TypeOf(def_id, user_substs) => {
1014 if let Err(terr) = self.fully_perform_op(
1015 Locations::All(span),
1016 ConstraintCategory::BoringNoLocation,
1017 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1026 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1038 /// Given some operation `op` that manipulates types, proves
1039 /// predicates, or otherwise uses the inference context, executes
1040 /// `op` and then executes all the further obligations that `op`
1041 /// returns. This will yield a set of outlives constraints amongst
1042 /// regions which are extracted and stored as having occurred at
1045 /// **Any `rustc_infer::infer` operations that might generate region
1046 /// constraints should occur within this method so that those
1047 /// constraints can be properly localized!**
1048 fn fully_perform_op<R>(
1050 locations: Locations,
1051 category: ConstraintCategory,
1052 op: impl type_op::TypeOp<'tcx, Output = R>,
1054 let (r, opt_data) = op.fully_perform(self.infcx)?;
1056 if let Some(data) = &opt_data {
1057 self.push_region_constraints(locations, category, data);
1063 fn push_region_constraints(
1065 locations: Locations,
1066 category: ConstraintCategory,
1067 data: &QueryRegionConstraints<'tcx>,
1069 debug!("push_region_constraints: constraints generated at {:?} are {:#?}", locations, data);
1071 constraint_conversion::ConstraintConversion::new(
1073 self.borrowck_context.universal_regions,
1074 self.region_bound_pairs,
1075 Some(self.implicit_region_bound),
1079 &mut self.borrowck_context.constraints,
1084 /// Convenient wrapper around `relate_tys::relate_types` -- see
1085 /// that fn for docs.
1091 locations: Locations,
1092 category: ConstraintCategory,
1094 relate_tys::relate_types(
1101 Some(self.borrowck_context),
1109 locations: Locations,
1110 category: ConstraintCategory,
1112 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1115 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1116 /// variables in `sub` with their inferred definitions and try
1117 /// again. This is used for opaque types in places (e.g., `let x:
1118 /// impl Foo = ..`).
1119 fn sub_types_or_anon(
1123 locations: Locations,
1124 category: ConstraintCategory,
1126 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1127 if let ty::Opaque(..) = sup.kind() {
1128 // When you have `let x: impl Foo = ...` in a closure,
1129 // the resulting inferend values are stored with the
1130 // def-id of the base function.
1132 self.tcx().closure_base_def_id(self.body.source.def_id()).expect_local();
1133 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1145 locations: Locations,
1146 category: ConstraintCategory,
1148 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1151 fn relate_type_and_user_type(
1155 user_ty: &UserTypeProjection,
1156 locations: Locations,
1157 category: ConstraintCategory,
1160 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1161 a, v, user_ty, locations,
1164 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1165 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1167 let tcx = self.infcx.tcx;
1169 for proj in &user_ty.projs {
1170 let projected_ty = curr_projected_ty.projection_ty_core(
1174 |this, field, &()| {
1175 let ty = this.field_ty(tcx, field);
1176 self.normalize(ty, locations)
1179 curr_projected_ty = projected_ty;
1182 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1183 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1186 let ty = curr_projected_ty.ty;
1187 self.relate_types(a, v, ty, locations, category)?;
1192 fn eq_opaque_type_and_type(
1194 revealed_ty: Ty<'tcx>,
1196 anon_owner_def_id: LocalDefId,
1197 locations: Locations,
1198 category: ConstraintCategory,
1201 "eq_opaque_type_and_type( \
1204 revealed_ty, anon_ty
1207 // Fast path for the common case.
1208 if !anon_ty.has_opaque_types() {
1209 if let Err(terr) = self.eq_types(anon_ty, revealed_ty, locations, category) {
1213 "eq_opaque_type_and_type: `{:?}=={:?}` failed with `{:?}`",
1222 let infcx = self.infcx;
1223 let tcx = infcx.tcx;
1224 let param_env = self.param_env;
1225 let body = self.body;
1226 let concrete_opaque_types = &tcx.typeck(anon_owner_def_id).concrete_opaque_types;
1227 let mut opaque_type_values = Vec::new();
1229 debug!("eq_opaque_type_and_type: mir_def_id={:?}", body.source.def_id());
1230 let opaque_type_map = self.fully_perform_op(
1235 let mut obligations = ObligationAccumulator::default();
1237 let dummy_body_id = hir::CRATE_HIR_ID;
1238 let (output_ty, opaque_type_map) =
1239 obligations.add(infcx.instantiate_opaque_types(
1244 locations.span(body),
1247 "eq_opaque_type_and_type: \
1248 instantiated output_ty={:?} \
1249 opaque_type_map={:#?} \
1251 output_ty, opaque_type_map, revealed_ty
1253 // Make sure that the inferred types are well-formed. I'm
1254 // not entirely sure this is needed (the HIR type check
1255 // didn't do this) but it seems sensible to prevent opaque
1256 // types hiding ill-formed types.
1257 obligations.obligations.push(traits::Obligation::new(
1258 ObligationCause::dummy(),
1260 ty::PredicateAtom::WellFormed(revealed_ty.into()).to_predicate(infcx.tcx),
1264 .at(&ObligationCause::dummy(), param_env)
1265 .eq(output_ty, revealed_ty)?,
1268 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1269 let resolved_ty = infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty);
1270 let concrete_is_opaque = if let ty::Opaque(def_id, _) = resolved_ty.kind() {
1271 *def_id == opaque_def_id
1275 let opaque_defn_ty = match concrete_opaque_types.get(&opaque_def_id) {
1277 if !concrete_is_opaque {
1278 tcx.sess.delay_span_bug(
1281 "Non-defining use of {:?} with revealed type",
1288 Some(opaque_defn_ty) => opaque_defn_ty,
1290 debug!("opaque_defn_ty = {:?}", opaque_defn_ty);
1291 let subst_opaque_defn_ty =
1292 opaque_defn_ty.concrete_type.subst(tcx, opaque_decl.substs);
1293 let renumbered_opaque_defn_ty =
1294 renumber::renumber_regions(infcx, &subst_opaque_defn_ty);
1297 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1298 opaque_decl.concrete_ty, resolved_ty, renumbered_opaque_defn_ty,
1301 if !concrete_is_opaque {
1302 // Equate concrete_ty (an inference variable) with
1303 // the renumbered type from typeck.
1306 .at(&ObligationCause::dummy(), param_env)
1307 .eq(opaque_decl.concrete_ty, renumbered_opaque_defn_ty)?,
1309 opaque_type_values.push((
1311 ty::ResolvedOpaqueTy {
1312 concrete_type: renumbered_opaque_defn_ty,
1313 substs: opaque_decl.substs,
1317 // We're using an opaque `impl Trait` type without
1318 // 'revealing' it. For example, code like this:
1320 // type Foo = impl Debug;
1321 // fn foo1() -> Foo { ... }
1322 // fn foo2() -> Foo { foo1() }
1324 // In `foo2`, we're not revealing the type of `Foo` - we're
1325 // just treating it as the opaque type.
1327 // When this occurs, we do *not* want to try to equate
1328 // the concrete type with the underlying defining type
1329 // of the opaque type - this will always fail, since
1330 // the defining type of an opaque type is always
1331 // some other type (e.g. not itself)
1332 // Essentially, none of the normal obligations apply here -
1333 // we're just passing around some unknown opaque type,
1334 // without actually looking at the underlying type it
1335 // gets 'revealed' into
1337 "eq_opaque_type_and_type: non-defining use of {:?}",
1343 debug!("eq_opaque_type_and_type: equated");
1346 value: Some(opaque_type_map),
1347 obligations: obligations.into_vec(),
1350 || "input_output".to_string(),
1354 self.opaque_type_values.extend(opaque_type_values);
1356 let universal_region_relations = self.universal_region_relations;
1358 // Finally, if we instantiated the anon types successfully, we
1359 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1360 // prove that `T: Iterator` where `T` is the type we
1361 // instantiated it with).
1362 if let Some(opaque_type_map) = opaque_type_map {
1363 for (opaque_def_id, opaque_decl) in opaque_type_map {
1364 self.fully_perform_op(
1366 ConstraintCategory::OpaqueType,
1369 infcx.constrain_opaque_type(
1372 GenerateMemberConstraints::IfNoStaticBound,
1373 universal_region_relations,
1375 Ok(InferOk { value: (), obligations: vec![] })
1377 || "opaque_type_map".to_string(),
1385 fn tcx(&self) -> TyCtxt<'tcx> {
1389 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1390 debug!("check_stmt: {:?}", stmt);
1391 let tcx = self.tcx();
1393 StatementKind::Assign(box (ref place, ref rv)) => {
1394 // Assignments to temporaries are not "interesting";
1395 // they are not caused by the user, but rather artifacts
1396 // of lowering. Assignments to other sorts of places *are* interesting
1398 let category = match place.as_local() {
1399 Some(RETURN_PLACE) => {
1400 if let BorrowCheckContext {
1402 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1404 } = self.borrowck_context
1406 if tcx.is_static(*def_id) {
1407 ConstraintCategory::UseAsStatic
1409 ConstraintCategory::UseAsConst
1412 ConstraintCategory::Return(ReturnConstraint::Normal)
1415 Some(l) if !body.local_decls[l].is_user_variable() => {
1416 ConstraintCategory::Boring
1418 _ => ConstraintCategory::Assignment,
1421 let place_ty = place.ty(body, tcx).ty;
1422 let place_ty = self.normalize(place_ty, location);
1423 let rv_ty = rv.ty(body, tcx);
1424 let rv_ty = self.normalize(rv_ty, location);
1426 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1431 "bad assignment ({:?} = {:?}): {:?}",
1438 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1439 if let Err(terr) = self.relate_type_and_user_type(
1441 ty::Variance::Invariant,
1442 &UserTypeProjection { base: annotation_index, projs: vec![] },
1443 location.to_locations(),
1444 ConstraintCategory::Boring,
1446 let annotation = &self.user_type_annotations[annotation_index];
1450 "bad user type on rvalue ({:?} = {:?}): {:?}",
1458 self.check_rvalue(body, rv, location);
1459 if !self.tcx().features().unsized_locals {
1460 let trait_ref = ty::TraitRef {
1461 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1462 substs: tcx.mk_substs_trait(place_ty, &[]),
1464 self.prove_trait_ref(
1466 location.to_locations(),
1467 ConstraintCategory::SizedBound,
1471 StatementKind::SetDiscriminant { ref place, variant_index } => {
1472 let place_type = place.ty(body, tcx).ty;
1473 let adt = match place_type.kind() {
1474 ty::Adt(adt, _) if adt.is_enum() => adt,
1477 stmt.source_info.span,
1478 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1484 if variant_index.as_usize() >= adt.variants.len() {
1486 stmt.source_info.span,
1487 "bad set discriminant ({:?} = {:?}): value of of range",
1493 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1494 let place_ty = place.ty(body, tcx).ty;
1495 if let Err(terr) = self.relate_type_and_user_type(
1499 Locations::All(stmt.source_info.span),
1500 ConstraintCategory::TypeAnnotation,
1502 let annotation = &self.user_type_annotations[projection.base];
1506 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1514 StatementKind::FakeRead(..)
1515 | StatementKind::StorageLive(..)
1516 | StatementKind::StorageDead(..)
1517 | StatementKind::LlvmInlineAsm { .. }
1518 | StatementKind::Retag { .. }
1519 | StatementKind::Coverage(..)
1520 | StatementKind::Nop => {}
1524 fn check_terminator(
1527 term: &Terminator<'tcx>,
1528 term_location: Location,
1530 debug!("check_terminator: {:?}", term);
1531 let tcx = self.tcx();
1533 TerminatorKind::Goto { .. }
1534 | TerminatorKind::Resume
1535 | TerminatorKind::Abort
1536 | TerminatorKind::Return
1537 | TerminatorKind::GeneratorDrop
1538 | TerminatorKind::Unreachable
1539 | TerminatorKind::Drop { .. }
1540 | TerminatorKind::FalseEdge { .. }
1541 | TerminatorKind::FalseUnwind { .. }
1542 | TerminatorKind::InlineAsm { .. } => {
1543 // no checks needed for these
1546 TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1547 let place_ty = place.ty(body, tcx).ty;
1548 let rv_ty = value.ty(body, tcx);
1550 let locations = term_location.to_locations();
1552 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1557 "bad DropAndReplace ({:?} = {:?}): {:?}",
1564 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1565 let discr_ty = discr.ty(body, tcx);
1566 if let Err(terr) = self.sub_types(
1569 term_location.to_locations(),
1570 ConstraintCategory::Assignment,
1575 "bad SwitchInt ({:?} on {:?}): {:?}",
1581 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1582 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1584 // FIXME: check the values
1586 TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1587 let func_ty = func.ty(body, tcx);
1588 debug!("check_terminator: call, func_ty={:?}", func_ty);
1589 let sig = match func_ty.kind() {
1590 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1592 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1596 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1597 term.source_info.span,
1598 LateBoundRegionConversionTime::FnCall,
1601 let sig = self.normalize(sig, term_location);
1602 self.check_call_dest(body, term, &sig, destination, term_location);
1604 self.prove_predicates(
1605 sig.inputs_and_output.iter().map(|ty| ty::PredicateAtom::WellFormed(ty.into())),
1606 term_location.to_locations(),
1607 ConstraintCategory::Boring,
1610 // The ordinary liveness rules will ensure that all
1611 // regions in the type of the callee are live here. We
1612 // then further constrain the late-bound regions that
1613 // were instantiated at the call site to be live as
1614 // well. The resulting is that all the input (and
1615 // output) types in the signature must be live, since
1616 // all the inputs that fed into it were live.
1617 for &late_bound_region in map.values() {
1619 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1620 self.borrowck_context
1622 .liveness_constraints
1623 .add_element(region_vid, term_location);
1626 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1628 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1629 let cond_ty = cond.ty(body, tcx);
1630 if cond_ty != tcx.types.bool {
1631 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1634 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1635 if len.ty(body, tcx) != tcx.types.usize {
1636 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1638 if index.ty(body, tcx) != tcx.types.usize {
1639 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1643 TerminatorKind::Yield { ref value, .. } => {
1644 let value_ty = value.ty(body, tcx);
1645 match body.yield_ty {
1646 None => span_mirbug!(self, term, "yield in non-generator"),
1648 if let Err(terr) = self.sub_types(
1651 term_location.to_locations(),
1652 ConstraintCategory::Yield,
1657 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1672 term: &Terminator<'tcx>,
1673 sig: &ty::FnSig<'tcx>,
1674 destination: &Option<(Place<'tcx>, BasicBlock)>,
1675 term_location: Location,
1677 let tcx = self.tcx();
1678 match *destination {
1679 Some((ref dest, _target_block)) => {
1680 let dest_ty = dest.ty(body, tcx).ty;
1681 let dest_ty = self.normalize(dest_ty, term_location);
1682 let category = match dest.as_local() {
1683 Some(RETURN_PLACE) => {
1684 if let BorrowCheckContext {
1686 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1688 } = self.borrowck_context
1690 if tcx.is_static(*def_id) {
1691 ConstraintCategory::UseAsStatic
1693 ConstraintCategory::UseAsConst
1696 ConstraintCategory::Return(ReturnConstraint::Normal)
1699 Some(l) if !body.local_decls[l].is_user_variable() => {
1700 ConstraintCategory::Boring
1702 _ => ConstraintCategory::Assignment,
1705 let locations = term_location.to_locations();
1708 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1713 "call dest mismatch ({:?} <- {:?}): {:?}",
1720 // When `#![feature(unsized_locals)]` is not enabled,
1721 // this check is done at `check_local`.
1722 if self.tcx().features().unsized_locals {
1723 let span = term.source_info.span;
1724 self.ensure_place_sized(dest_ty, span);
1728 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1729 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1735 fn check_call_inputs(
1738 term: &Terminator<'tcx>,
1739 sig: &ty::FnSig<'tcx>,
1740 args: &[Operand<'tcx>],
1741 term_location: Location,
1742 from_hir_call: bool,
1744 debug!("check_call_inputs({:?}, {:?})", sig, args);
1745 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1746 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1748 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1749 let op_arg_ty = op_arg.ty(body, self.tcx());
1750 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1751 let category = if from_hir_call {
1752 ConstraintCategory::CallArgument
1754 ConstraintCategory::Boring
1757 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1762 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1772 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1773 let is_cleanup = block_data.is_cleanup;
1774 self.last_span = block_data.terminator().source_info.span;
1775 match block_data.terminator().kind {
1776 TerminatorKind::Goto { target } => {
1777 self.assert_iscleanup(body, block_data, target, is_cleanup)
1779 TerminatorKind::SwitchInt { ref targets, .. } => {
1780 for target in targets.all_targets() {
1781 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1784 TerminatorKind::Resume => {
1786 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1789 TerminatorKind::Abort => {
1791 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1794 TerminatorKind::Return => {
1796 span_mirbug!(self, block_data, "return on cleanup block")
1799 TerminatorKind::GeneratorDrop { .. } => {
1801 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1804 TerminatorKind::Yield { resume, drop, .. } => {
1806 span_mirbug!(self, block_data, "yield in cleanup block")
1808 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1809 if let Some(drop) = drop {
1810 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1813 TerminatorKind::Unreachable => {}
1814 TerminatorKind::Drop { target, unwind, .. }
1815 | TerminatorKind::DropAndReplace { target, unwind, .. }
1816 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1817 self.assert_iscleanup(body, block_data, target, is_cleanup);
1818 if let Some(unwind) = unwind {
1820 span_mirbug!(self, block_data, "unwind on cleanup block")
1822 self.assert_iscleanup(body, block_data, unwind, true);
1825 TerminatorKind::Call { ref destination, cleanup, .. } => {
1826 if let &Some((_, target)) = destination {
1827 self.assert_iscleanup(body, block_data, target, is_cleanup);
1829 if let Some(cleanup) = cleanup {
1831 span_mirbug!(self, block_data, "cleanup on cleanup block")
1833 self.assert_iscleanup(body, block_data, cleanup, true);
1836 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1837 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1838 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1840 TerminatorKind::FalseUnwind { real_target, unwind } => {
1841 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1842 if let Some(unwind) = unwind {
1844 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1846 self.assert_iscleanup(body, block_data, unwind, true);
1849 TerminatorKind::InlineAsm { ref destination, .. } => {
1850 if let &Some(target) = destination {
1851 self.assert_iscleanup(body, block_data, target, is_cleanup);
1857 fn assert_iscleanup(
1860 ctxt: &dyn fmt::Debug,
1864 if body[bb].is_cleanup != iscleanuppad {
1865 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1869 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1870 match body.local_kind(local) {
1871 LocalKind::ReturnPointer | LocalKind::Arg => {
1872 // return values of normal functions are required to be
1873 // sized by typeck, but return values of ADT constructors are
1874 // not because we don't include a `Self: Sized` bounds on them.
1876 // Unbound parts of arguments were never required to be Sized
1877 // - maybe we should make that a warning.
1880 LocalKind::Var | LocalKind::Temp => {}
1883 // When `#![feature(unsized_locals)]` is enabled, only function calls
1884 // and nullary ops are checked in `check_call_dest`.
1885 if !self.tcx().features().unsized_locals {
1886 let span = local_decl.source_info.span;
1887 let ty = local_decl.ty;
1888 self.ensure_place_sized(ty, span);
1892 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1893 let tcx = self.tcx();
1895 // Erase the regions from `ty` to get a global type. The
1896 // `Sized` bound in no way depends on precise regions, so this
1897 // shouldn't affect `is_sized`.
1898 let erased_ty = tcx.erase_regions(&ty);
1899 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1900 // in current MIR construction, all non-control-flow rvalue
1901 // expressions evaluate through `as_temp` or `into` a return
1902 // slot or local, so to find all unsized rvalues it is enough
1903 // to check all temps, return slots and locals.
1904 if self.reported_errors.replace((ty, span)).is_none() {
1905 let mut diag = struct_span_err!(
1909 "cannot move a value of type {0}: the size of {0} \
1910 cannot be statically determined",
1914 // While this is located in `nll::typeck` this error is not
1915 // an NLL error, it's a required check to prevent creation
1916 // of unsized rvalues in certain cases:
1917 // * operand of a box expression
1918 // * callee in a call expression
1924 fn aggregate_field_ty(
1926 ak: &AggregateKind<'tcx>,
1929 ) -> Result<Ty<'tcx>, FieldAccessError> {
1930 let tcx = self.tcx();
1933 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1934 let variant = &def.variants[variant_index];
1935 let adj_field_index = active_field_index.unwrap_or(field_index);
1936 if let Some(field) = variant.fields.get(adj_field_index) {
1937 Ok(self.normalize(field.ty(tcx, substs), location))
1939 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1942 AggregateKind::Closure(_, substs) => {
1943 match substs.as_closure().upvar_tys().nth(field_index) {
1945 None => Err(FieldAccessError::OutOfRange {
1946 field_count: substs.as_closure().upvar_tys().count(),
1950 AggregateKind::Generator(_, substs, _) => {
1951 // It doesn't make sense to look at a field beyond the prefix;
1952 // these require a variant index, and are not initialized in
1953 // aggregate rvalues.
1954 match substs.as_generator().prefix_tys().nth(field_index) {
1956 None => Err(FieldAccessError::OutOfRange {
1957 field_count: substs.as_generator().prefix_tys().count(),
1961 AggregateKind::Array(ty) => Ok(ty),
1962 AggregateKind::Tuple => {
1963 unreachable!("This should have been covered in check_rvalues");
1968 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1969 let tcx = self.tcx();
1972 Rvalue::Aggregate(ak, ops) => {
1973 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1976 Rvalue::Repeat(operand, len) => {
1977 // If the length cannot be evaluated we must assume that the length can be larger
1979 // If the length is larger than 1, the repeat expression will need to copy the
1980 // element, so we require the `Copy` trait.
1981 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1982 if let Operand::Move(_) = operand {
1983 // While this is located in `nll::typeck` this error is not an NLL error, it's
1984 // a required check to make sure that repeated elements implement `Copy`.
1985 let span = body.source_info(location).span;
1986 let ty = operand.ty(body, tcx);
1987 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1988 let ccx = ConstCx::new_with_param_env(tcx, body, self.param_env);
1989 // To determine if `const_in_array_repeat_expressions` feature gate should
1990 // be mentioned, need to check if the rvalue is promotable.
1991 let should_suggest =
1992 should_suggest_const_in_array_repeat_expressions_attribute(
1995 debug!("check_rvalue: should_suggest={:?}", should_suggest);
1997 let def_id = body.source.def_id().expect_local();
1998 self.infcx.report_selection_error(
1999 &traits::Obligation::new(
2000 ObligationCause::new(
2002 self.tcx().hir().local_def_id_to_hir_id(def_id),
2003 traits::ObligationCauseCode::RepeatVec(should_suggest),
2006 ty::Binder::bind(ty::TraitRef::new(
2007 self.tcx().require_lang_item(
2009 Some(self.last_span),
2011 tcx.mk_substs_trait(ty, &[]),
2014 .to_predicate(self.tcx()),
2016 &traits::SelectionError::Unimplemented,
2025 Rvalue::NullaryOp(_, ty) => {
2026 // Even with unsized locals cannot box an unsized value.
2027 if self.tcx().features().unsized_locals {
2028 let span = body.source_info(location).span;
2029 self.ensure_place_sized(ty, span);
2032 let trait_ref = ty::TraitRef {
2033 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
2034 substs: tcx.mk_substs_trait(ty, &[]),
2037 self.prove_trait_ref(
2039 location.to_locations(),
2040 ConstraintCategory::SizedBound,
2044 Rvalue::Cast(cast_kind, op, ty) => {
2046 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2047 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2049 // The type that we see in the fcx is like
2050 // `foo::<'a, 'b>`, where `foo` is the path to a
2051 // function definition. When we extract the
2052 // signature, it comes from the `fn_sig` query,
2053 // and hence may contain unnormalized results.
2054 let fn_sig = self.normalize(fn_sig, location);
2056 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2058 if let Err(terr) = self.eq_types(
2061 location.to_locations(),
2062 ConstraintCategory::Cast,
2067 "equating {:?} with {:?} yields {:?}",
2075 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2076 let sig = match op.ty(body, tcx).kind() {
2077 ty::Closure(_, substs) => substs.as_closure().sig(),
2080 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
2082 if let Err(terr) = self.eq_types(
2085 location.to_locations(),
2086 ConstraintCategory::Cast,
2091 "equating {:?} with {:?} yields {:?}",
2099 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2100 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2102 // The type that we see in the fcx is like
2103 // `foo::<'a, 'b>`, where `foo` is the path to a
2104 // function definition. When we extract the
2105 // signature, it comes from the `fn_sig` query,
2106 // and hence may contain unnormalized results.
2107 let fn_sig = self.normalize(fn_sig, location);
2109 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2111 if let Err(terr) = self.eq_types(
2114 location.to_locations(),
2115 ConstraintCategory::Cast,
2120 "equating {:?} with {:?} yields {:?}",
2128 CastKind::Pointer(PointerCast::Unsize) => {
2130 let trait_ref = ty::TraitRef {
2132 .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2133 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2136 self.prove_trait_ref(
2138 location.to_locations(),
2139 ConstraintCategory::Cast,
2143 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2144 let ty_from = match op.ty(body, tcx).kind() {
2145 ty::RawPtr(ty::TypeAndMut {
2147 mutbl: hir::Mutability::Mut,
2153 "unexpected base type for cast {:?}",
2159 let ty_to = match ty.kind() {
2160 ty::RawPtr(ty::TypeAndMut {
2162 mutbl: hir::Mutability::Not,
2168 "unexpected target type for cast {:?}",
2174 if let Err(terr) = self.sub_types(
2177 location.to_locations(),
2178 ConstraintCategory::Cast,
2183 "relating {:?} with {:?} yields {:?}",
2191 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2192 let ty_from = op.ty(body, tcx);
2194 let opt_ty_elem = match ty_from.kind() {
2195 ty::RawPtr(ty::TypeAndMut {
2196 mutbl: hir::Mutability::Not,
2198 }) => match array_ty.kind() {
2199 ty::Array(ty_elem, _) => Some(ty_elem),
2205 let ty_elem = match opt_ty_elem {
2206 Some(ty_elem) => ty_elem,
2211 "ArrayToPointer cast from unexpected type {:?}",
2218 let ty_to = match ty.kind() {
2219 ty::RawPtr(ty::TypeAndMut {
2220 mutbl: hir::Mutability::Not,
2227 "ArrayToPointer cast to unexpected type {:?}",
2234 if let Err(terr) = self.sub_types(
2237 location.to_locations(),
2238 ConstraintCategory::Cast,
2243 "relating {:?} with {:?} yields {:?}",
2252 let ty_from = op.ty(body, tcx);
2253 let cast_ty_from = CastTy::from_ty(ty_from);
2254 let cast_ty_to = CastTy::from_ty(ty);
2255 match (cast_ty_from, cast_ty_to) {
2257 | (_, None | Some(CastTy::FnPtr))
2258 | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2259 | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => {
2260 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2263 Some(CastTy::Int(_)),
2264 Some(CastTy::Int(_) | CastTy::Float | CastTy::Ptr(_)),
2266 | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float))
2267 | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_)))
2268 | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (),
2274 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2275 self.add_reborrow_constraint(&body, location, region, borrowed_place);
2279 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2283 let ty_left = left.ty(body, tcx);
2284 match ty_left.kind() {
2285 // Types with regions are comparable if they have a common super-type.
2286 ty::RawPtr(_) | ty::FnPtr(_) => {
2287 let ty_right = right.ty(body, tcx);
2288 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2289 kind: TypeVariableOriginKind::MiscVariable,
2290 span: body.source_info(location).span,
2294 ty::Variance::Contravariant,
2296 location.to_locations(),
2297 ConstraintCategory::Boring,
2299 .unwrap_or_else(|err| {
2300 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2302 if let Err(terr) = self.relate_types(
2304 ty::Variance::Contravariant,
2306 location.to_locations(),
2307 ConstraintCategory::Boring,
2312 "unexpected comparison types {:?} and {:?} yields {:?}",
2319 // For types with no regions we can just check that the
2320 // both operands have the same type.
2321 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2322 if ty_left == right.ty(body, tcx) => {}
2323 // Other types are compared by trait methods, not by
2324 // `Rvalue::BinaryOp`.
2328 "unexpected comparison types {:?} and {:?}",
2335 Rvalue::AddressOf(..)
2336 | Rvalue::ThreadLocalRef(..)
2339 | Rvalue::BinaryOp(..)
2340 | Rvalue::CheckedBinaryOp(..)
2341 | Rvalue::UnaryOp(..)
2342 | Rvalue::Discriminant(..) => {}
2346 /// If this rvalue supports a user-given type annotation, then
2347 /// extract and return it. This represents the final type of the
2348 /// rvalue and will be unified with the inferred type.
2349 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2352 | Rvalue::ThreadLocalRef(_)
2353 | Rvalue::Repeat(..)
2355 | Rvalue::AddressOf(..)
2358 | Rvalue::BinaryOp(..)
2359 | Rvalue::CheckedBinaryOp(..)
2360 | Rvalue::NullaryOp(..)
2361 | Rvalue::UnaryOp(..)
2362 | Rvalue::Discriminant(..) => None,
2364 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2365 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2366 AggregateKind::Array(_) => None,
2367 AggregateKind::Tuple => None,
2368 AggregateKind::Closure(_, _) => None,
2369 AggregateKind::Generator(_, _, _) => None,
2374 fn check_aggregate_rvalue(
2377 rvalue: &Rvalue<'tcx>,
2378 aggregate_kind: &AggregateKind<'tcx>,
2379 operands: &[Operand<'tcx>],
2382 let tcx = self.tcx();
2384 self.prove_aggregate_predicates(aggregate_kind, location);
2386 if *aggregate_kind == AggregateKind::Tuple {
2387 // tuple rvalue field type is always the type of the op. Nothing to check here.
2391 for (i, operand) in operands.iter().enumerate() {
2392 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2393 Ok(field_ty) => field_ty,
2394 Err(FieldAccessError::OutOfRange { field_count }) => {
2398 "accessed field #{} but variant only has {}",
2405 let operand_ty = operand.ty(body, tcx);
2406 let operand_ty = self.normalize(operand_ty, location);
2408 if let Err(terr) = self.sub_types(
2411 location.to_locations(),
2412 ConstraintCategory::Boring,
2417 "{:?} is not a subtype of {:?}: {:?}",
2426 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2430 /// - `location`: the location `L` where the borrow expression occurs
2431 /// - `borrow_region`: the region `'a` associated with the borrow
2432 /// - `borrowed_place`: the place `P` being borrowed
2433 fn add_reborrow_constraint(
2437 borrow_region: ty::Region<'tcx>,
2438 borrowed_place: &Place<'tcx>,
2440 // These constraints are only meaningful during borrowck:
2441 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2442 self.borrowck_context;
2444 // In Polonius mode, we also push a `borrow_region` fact
2445 // linking the loan to the region (in some cases, though,
2446 // there is no loan associated with this borrow expression --
2447 // that occurs when we are borrowing an unsafe place, for
2449 if let Some(all_facts) = all_facts {
2450 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2451 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2452 let region_vid = borrow_region.to_region_vid();
2453 all_facts.borrow_region.push((
2456 location_table.mid_index(location),
2461 // If we are reborrowing the referent of another reference, we
2462 // need to add outlives relationships. In a case like `&mut
2463 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2464 // need to ensure that `'b: 'a`.
2467 "add_reborrow_constraint({:?}, {:?}, {:?})",
2468 location, borrow_region, borrowed_place
2471 let mut cursor = borrowed_place.projection.as_ref();
2472 let tcx = self.infcx.tcx;
2473 let field = path_utils::is_upvar_field_projection(
2475 &self.borrowck_context.upvars,
2476 borrowed_place.as_ref(),
2479 let category = if let Some(field) = field {
2480 ConstraintCategory::ClosureUpvar(self.borrowck_context.upvars[field.index()].var_hir_id)
2482 ConstraintCategory::Boring
2485 while let [proj_base @ .., elem] = cursor {
2488 debug!("add_reborrow_constraint - iteration {:?}", elem);
2491 ProjectionElem::Deref => {
2492 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2494 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2495 match base_ty.kind() {
2496 ty::Ref(ref_region, _, mutbl) => {
2497 constraints.outlives_constraints.push(OutlivesConstraint {
2498 sup: ref_region.to_region_vid(),
2499 sub: borrow_region.to_region_vid(),
2500 locations: location.to_locations(),
2505 hir::Mutability::Not => {
2506 // Immutable reference. We don't need the base
2507 // to be valid for the entire lifetime of
2511 hir::Mutability::Mut => {
2512 // Mutable reference. We *do* need the base
2513 // to be valid, because after the base becomes
2514 // invalid, someone else can use our mutable deref.
2516 // This is in order to make the following function
2519 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2524 // As otherwise you could clone `&mut T` using the
2525 // following function:
2527 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2528 // let my_clone = unsafe_deref(&'a x);
2537 // deref of raw pointer, guaranteed to be valid
2540 ty::Adt(def, _) if def.is_box() => {
2541 // deref of `Box`, need the base to be valid - propagate
2543 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2546 ProjectionElem::Field(..)
2547 | ProjectionElem::Downcast(..)
2548 | ProjectionElem::Index(..)
2549 | ProjectionElem::ConstantIndex { .. }
2550 | ProjectionElem::Subslice { .. } => {
2551 // other field access
2557 fn prove_aggregate_predicates(
2559 aggregate_kind: &AggregateKind<'tcx>,
2562 let tcx = self.tcx();
2565 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2566 aggregate_kind, location
2569 let instantiated_predicates = match aggregate_kind {
2570 AggregateKind::Adt(def, _, substs, _, _) => {
2571 tcx.predicates_of(def.did).instantiate(tcx, substs)
2574 // For closures, we have some **extra requirements** we
2576 // have to check. In particular, in their upvars and
2577 // signatures, closures often reference various regions
2578 // from the surrounding function -- we call those the
2579 // closure's free regions. When we borrow-check (and hence
2580 // region-check) closures, we may find that the closure
2581 // requires certain relationships between those free
2582 // regions. However, because those free regions refer to
2583 // portions of the CFG of their caller, the closure is not
2584 // in a position to verify those relationships. In that
2585 // case, the requirements get "propagated" to us, and so
2586 // we have to solve them here where we instantiate the
2589 // Despite the opacity of the previous parapgrah, this is
2590 // actually relatively easy to understand in terms of the
2591 // desugaring. A closure gets desugared to a struct, and
2592 // these extra requirements are basically like where
2593 // clauses on the struct.
2594 AggregateKind::Closure(def_id, substs)
2595 | AggregateKind::Generator(def_id, substs, _) => {
2596 self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location)
2599 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2602 self.normalize_and_prove_instantiated_predicates(
2603 instantiated_predicates,
2604 location.to_locations(),
2608 fn prove_closure_bounds(
2612 substs: SubstsRef<'tcx>,
2614 ) -> ty::InstantiatedPredicates<'tcx> {
2615 if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2617 let closure_constraints = QueryRegionConstraints {
2618 outlives: closure_region_requirements.apply_requirements(
2624 // Presently, closures never propagate member
2625 // constraints to their parents -- they are enforced
2626 // locally. This is largely a non-issue as member
2627 // constraints only come from `-> impl Trait` and
2628 // friends which don't appear (thus far...) in
2630 member_constraints: vec![],
2633 let bounds_mapping = closure_constraints
2637 .filter_map(|(idx, constraint)| {
2638 let ty::OutlivesPredicate(k1, r2) =
2639 constraint.no_bound_vars().unwrap_or_else(|| {
2640 bug!("query_constraint {:?} contained bound vars", constraint,);
2644 GenericArgKind::Lifetime(r1) => {
2645 // constraint is r1: r2
2646 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2647 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2648 let outlives_requirements =
2649 &closure_region_requirements.outlives_requirements[idx];
2652 (outlives_requirements.category, outlives_requirements.blame_span),
2655 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2663 .closure_bounds_mapping
2664 .insert(location, bounds_mapping);
2665 assert!(existing.is_none(), "Multiple closures at the same location.");
2667 self.push_region_constraints(
2668 location.to_locations(),
2669 ConstraintCategory::ClosureBounds,
2670 &closure_constraints,
2674 tcx.predicates_of(def_id).instantiate(tcx, substs)
2679 trait_ref: ty::TraitRef<'tcx>,
2680 locations: Locations,
2681 category: ConstraintCategory,
2683 self.prove_predicates(
2684 Some(ty::PredicateAtom::Trait(
2685 ty::TraitPredicate { trait_ref },
2686 hir::Constness::NotConst,
2693 fn normalize_and_prove_instantiated_predicates(
2695 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2696 locations: Locations,
2698 for predicate in instantiated_predicates.predicates {
2699 let predicate = self.normalize(predicate, locations);
2700 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2704 fn prove_predicates(
2706 predicates: impl IntoIterator<Item = impl ToPredicate<'tcx>>,
2707 locations: Locations,
2708 category: ConstraintCategory,
2710 for predicate in predicates {
2711 let predicate = predicate.to_predicate(self.tcx());
2712 debug!("prove_predicates(predicate={:?}, locations={:?})", predicate, locations,);
2714 self.prove_predicate(predicate, locations, category);
2720 predicate: ty::Predicate<'tcx>,
2721 locations: Locations,
2722 category: ConstraintCategory,
2724 debug!("prove_predicate(predicate={:?}, location={:?})", predicate, locations,);
2726 let param_env = self.param_env;
2727 self.fully_perform_op(
2730 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2732 .unwrap_or_else(|NoSolution| {
2733 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2737 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2738 self.last_span = body.span;
2739 debug!("run_on_mir: {:?}", body.span);
2741 for (local, local_decl) in body.local_decls.iter_enumerated() {
2742 self.check_local(&body, local, local_decl);
2745 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2746 let mut location = Location { block, statement_index: 0 };
2747 for stmt in &block_data.statements {
2748 if !stmt.source_info.span.is_dummy() {
2749 self.last_span = stmt.source_info.span;
2751 self.check_stmt(body, stmt, location);
2752 location.statement_index += 1;
2755 self.check_terminator(&body, block_data.terminator(), location);
2756 self.check_iscleanup(&body, block_data);
2760 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2762 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2764 debug!("normalize(value={:?}, location={:?})", value, location);
2765 let param_env = self.param_env;
2766 self.fully_perform_op(
2767 location.to_locations(),
2768 ConstraintCategory::Boring,
2769 param_env.and(type_op::normalize::Normalize::new(value)),
2771 .unwrap_or_else(|NoSolution| {
2772 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2778 trait NormalizeLocation: fmt::Debug + Copy {
2779 fn to_locations(self) -> Locations;
2782 impl NormalizeLocation for Locations {
2783 fn to_locations(self) -> Locations {
2788 impl NormalizeLocation for Location {
2789 fn to_locations(self) -> Locations {
2790 Locations::Single(self)
2794 #[derive(Debug, Default)]
2795 struct ObligationAccumulator<'tcx> {
2796 obligations: PredicateObligations<'tcx>,
2799 impl<'tcx> ObligationAccumulator<'tcx> {
2800 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2801 let InferOk { value, obligations } = value;
2802 self.obligations.extend(obligations);
2806 fn into_vec(self) -> PredicateObligations<'tcx> {