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;
13 use rustc_index::vec::{Idx, IndexVec};
14 use rustc_infer::infer::canonical::QueryRegionConstraints;
15 use rustc_infer::infer::outlives::env::RegionBoundPairs;
16 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
17 use rustc_infer::infer::{
18 InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin,
20 use rustc_middle::mir::tcx::PlaceTy;
21 use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
22 use rustc_middle::mir::AssertKind;
23 use rustc_middle::mir::*;
24 use rustc_middle::ty::adjustment::PointerCast;
25 use rustc_middle::ty::cast::CastTy;
26 use rustc_middle::ty::fold::TypeFoldable;
27 use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef, UserSubsts};
28 use rustc_middle::ty::{
29 self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, RegionVid, ToPolyTraitRef, Ty,
30 TyCtxt, UserType, UserTypeAnnotationIndex,
32 use rustc_span::{Span, DUMMY_SP};
33 use rustc_target::abi::VariantIdx;
34 use rustc_trait_selection::infer::InferCtxtExt as _;
35 use rustc_trait_selection::opaque_types::{GenerateMemberConstraints, InferCtxtExt};
36 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
37 use rustc_trait_selection::traits::query::type_op;
38 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
39 use rustc_trait_selection::traits::query::{Fallible, NoSolution};
40 use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligations};
42 use crate::dataflow::move_paths::MoveData;
43 use crate::dataflow::MaybeInitializedPlaces;
44 use crate::dataflow::ResultsCursor;
45 use crate::transform::promote_consts::should_suggest_const_in_array_repeat_expressions_attribute;
47 use crate::borrow_check::{
48 borrow_set::BorrowSet,
49 constraints::{OutlivesConstraint, OutlivesConstraintSet},
51 location::LocationTable,
52 member_constraints::MemberConstraintSet,
54 region_infer::values::{
55 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
57 region_infer::{ClosureRegionRequirementsExt, TypeTest},
59 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
60 universal_regions::{DefiningTy, UniversalRegions},
63 macro_rules! span_mirbug {
64 ($context:expr, $elem:expr, $($message:tt)*) => ({
65 $crate::borrow_check::type_check::mirbug(
69 "broken MIR in {:?} ({:?}): {}",
72 format_args!($($message)*),
78 macro_rules! span_mirbug_and_err {
79 ($context:expr, $elem:expr, $($message:tt)*) => ({
81 span_mirbug!($context, $elem, $($message)*);
87 mod constraint_conversion;
88 pub mod free_region_relations;
93 /// Type checks the given `mir` in the context of the inference
94 /// context `infcx`. Returns any region constraints that have yet to
95 /// be proven. This result is includes liveness constraints that
96 /// ensure that regions appearing in the types of all local variables
97 /// are live at all points where that local variable may later be
100 /// This phase of type-check ought to be infallible -- this is because
101 /// the original, HIR-based type-check succeeded. So if any errors
102 /// occur here, we will get a `bug!` reported.
106 /// - `infcx` -- inference context to use
107 /// - `param_env` -- parameter environment to use for trait solving
108 /// - `mir` -- MIR to type-check
109 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
110 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
111 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
112 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
113 /// to outlive; should represent the fn body
114 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
115 /// the types of the input parameters found in the MIR itself will be equated with these
116 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
117 /// the type for the RETURN_PLACE will be equated with this
118 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
119 /// constraints for the regions in the types of variables
120 /// - `flow_inits` -- results of a maybe-init dataflow analysis
121 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
122 pub(crate) fn type_check<'mir, 'tcx>(
123 infcx: &InferCtxt<'_, 'tcx>,
124 param_env: ty::ParamEnv<'tcx>,
125 body: ReadOnlyBodyAndCache<'_, 'tcx>,
126 promoted: &IndexVec<Promoted, ReadOnlyBodyAndCache<'_, '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>,
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>,
192 param_env: ty::ParamEnv<'tcx>,
193 body: ReadOnlyBodyAndCache<'a, 'tcx>,
194 promoted: &'a IndexVec<Promoted, ReadOnlyBodyAndCache<'_, '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, ReadOnlyBodyAndCache<'b, 'tcx>>,
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: &ReadOnlyBodyAndCache<'_, '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 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
406 let ty = if !local_decl.is_nonref_binding() {
407 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
408 // reference so we can check the 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 {:?}: {:?} != {:?} ({:?})",
438 fn visit_body(&mut self, body: &Body<'tcx>) {
439 self.sanitize_type(&"return type", body.return_ty());
440 for local_decl in &body.local_decls {
441 self.sanitize_type(local_decl, local_decl.ty);
443 if self.errors_reported {
446 self.super_body(body);
450 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
452 cx: &'a mut TypeChecker<'b, 'tcx>,
453 body: &'b Body<'tcx>,
454 promoted: &'b IndexVec<Promoted, ReadOnlyBodyAndCache<'b, 'tcx>>,
459 mir_def_id: cx.mir_def_id,
461 last_span: body.span,
462 errors_reported: false,
466 fn tcx(&self) -> TyCtxt<'tcx> {
470 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
471 if ty.has_escaping_bound_vars() || ty.references_error() {
472 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
478 /// Checks that the types internal to the `place` match up with
479 /// what would be expected.
484 context: PlaceContext,
486 debug!("sanitize_place: {:?}", place);
488 let mut place_ty = PlaceTy::from_ty(self.body.local_decls[place.local].ty);
490 for elem in place.projection.iter() {
491 if place_ty.variant_index.is_none() {
492 if place_ty.ty.references_error() {
493 assert!(self.errors_reported);
494 return PlaceTy::from_ty(self.tcx().types.err);
497 place_ty = self.sanitize_projection(place_ty, elem, place, location)
500 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
501 let tcx = self.tcx();
502 let trait_ref = ty::TraitRef {
503 def_id: tcx.lang_items().copy_trait().unwrap(),
504 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
507 // To have a `Copy` operand, the type `T` of the
508 // value must be `Copy`. Note that we prove that `T: Copy`,
509 // rather than using the `is_copy_modulo_regions`
510 // test. This is important because
511 // `is_copy_modulo_regions` ignores the resulting region
512 // obligations and assumes they pass. This can result in
513 // bounds from `Copy` impls being unsoundly ignored (e.g.,
514 // #29149). Note that we decide to use `Copy` before knowing
515 // whether the bounds fully apply: in effect, the rule is
516 // that if a value of some type could implement `Copy`, then
518 self.cx.prove_trait_ref(
520 location.to_locations(),
521 ConstraintCategory::CopyBound,
528 fn sanitize_promoted(
530 promoted_body: ReadOnlyBodyAndCache<'b, 'tcx>,
533 // Determine the constraints from the promoted MIR by running the type
534 // checker on the promoted MIR, then transfer the constraints back to
535 // the main MIR, changing the locations to the provided location.
537 let parent_body = mem::replace(&mut self.body, *promoted_body);
539 // Use new sets of constraints and closure bounds so that we can
540 // modify their locations.
541 let all_facts = &mut None;
542 let mut constraints = Default::default();
543 let mut closure_bounds = Default::default();
544 let mut liveness_constraints =
545 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
546 // Don't try to add borrow_region facts for the promoted MIR
548 let mut swap_constraints = |this: &mut Self| {
549 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
551 &mut this.cx.borrowck_context.constraints.outlives_constraints,
555 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
559 &mut this.cx.borrowck_context.constraints.liveness_constraints,
560 &mut liveness_constraints,
564 swap_constraints(self);
566 self.visit_body(&promoted_body);
568 if !self.errors_reported {
569 // if verifier failed, don't do further checks to avoid ICEs
570 self.cx.typeck_mir(promoted_body);
573 self.body = parent_body;
574 // Merge the outlives constraints back in, at the given location.
575 swap_constraints(self);
577 let locations = location.to_locations();
578 for constraint in constraints.outlives().iter() {
579 let mut constraint = *constraint;
580 constraint.locations = locations;
581 if let ConstraintCategory::Return
582 | ConstraintCategory::UseAsConst
583 | ConstraintCategory::UseAsStatic = constraint.category
585 // "Returning" from a promoted is an assignment to a
586 // temporary from the user's point of view.
587 constraint.category = ConstraintCategory::Boring;
589 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
591 for live_region in liveness_constraints.rows() {
595 .liveness_constraints
596 .add_element(live_region, location);
599 if !closure_bounds.is_empty() {
600 let combined_bounds_mapping =
601 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
606 .closure_bounds_mapping
607 .insert(location, combined_bounds_mapping);
608 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
612 fn sanitize_projection(
615 pi: &PlaceElem<'tcx>,
619 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
620 let tcx = self.tcx();
621 let base_ty = base.ty;
623 ProjectionElem::Deref => {
624 let deref_ty = base_ty.builtin_deref(true);
625 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
626 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
629 ProjectionElem::Index(i) => {
630 let index_ty = Place::from(i).ty(self.body, tcx).ty;
631 if index_ty != tcx.types.usize {
632 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
634 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
635 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
639 ProjectionElem::ConstantIndex { .. } => {
640 // consider verifying in-bounds
641 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
642 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
645 ProjectionElem::Subslice { from, to, from_end } => {
646 PlaceTy::from_ty(match base_ty.kind {
647 ty::Array(inner, _) => {
648 assert!(!from_end, "array subslices should not use from_end");
649 tcx.mk_array(inner, (to - from) as u64)
652 assert!(from_end, "slice subslices should use from_end");
655 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
658 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind {
659 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
660 if index.as_usize() >= adt_def.variants.len() {
661 PlaceTy::from_ty(span_mirbug_and_err!(
664 "cast to variant #{:?} but enum only has {:?}",
666 adt_def.variants.len()
669 PlaceTy { ty: base_ty, variant_index: Some(index) }
672 // We do not need to handle generators here, because this runs
673 // before the generator transform stage.
675 let ty = if let Some(name) = maybe_name {
676 span_mirbug_and_err!(
679 "can't downcast {:?} as {:?}",
684 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
689 ProjectionElem::Field(field, fty) => {
690 let fty = self.sanitize_type(place, fty);
691 match self.field_ty(place, base, field, 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>,
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>,
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::Predicate::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);
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 = &tcx.typeck_tables_of(anon_owner_def_id).concrete_opaque_types;
1237 let mut opaque_type_values = Vec::new();
1239 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1240 let opaque_type_map = self.fully_perform_op(
1245 let mut obligations = ObligationAccumulator::default();
1247 let dummy_body_id = ObligationCause::dummy().body_id;
1248 let (output_ty, opaque_type_map) =
1249 obligations.add(infcx.instantiate_opaque_types(
1254 locations.span(body),
1257 "eq_opaque_type_and_type: \
1258 instantiated output_ty={:?} \
1259 opaque_type_map={:#?} \
1261 output_ty, opaque_type_map, revealed_ty
1263 // Make sure that the inferred types are well-formed. I'm
1264 // not entirely sure this is needed (the HIR type check
1265 // didn't do this) but it seems sensible to prevent opaque
1266 // types hiding ill-formed types.
1267 obligations.obligations.push(traits::Obligation::new(
1268 ObligationCause::dummy(),
1270 ty::Predicate::WellFormed(revealed_ty),
1274 .at(&ObligationCause::dummy(), param_env)
1275 .eq(output_ty, revealed_ty)?,
1278 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1279 let resolved_ty = infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty);
1280 let concrete_is_opaque = if let ty::Opaque(def_id, _) = resolved_ty.kind {
1281 def_id == opaque_def_id
1285 let opaque_defn_ty = match concrete_opaque_types.get(&opaque_def_id) {
1287 if !concrete_is_opaque {
1288 tcx.sess.delay_span_bug(
1291 "Non-defining use of {:?} with revealed type",
1298 Some(opaque_defn_ty) => opaque_defn_ty,
1300 debug!("opaque_defn_ty = {:?}", opaque_defn_ty);
1301 let subst_opaque_defn_ty =
1302 opaque_defn_ty.concrete_type.subst(tcx, opaque_decl.substs);
1303 let renumbered_opaque_defn_ty =
1304 renumber::renumber_regions(infcx, &subst_opaque_defn_ty);
1307 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1308 opaque_decl.concrete_ty, resolved_ty, renumbered_opaque_defn_ty,
1311 if !concrete_is_opaque {
1312 // Equate concrete_ty (an inference variable) with
1313 // the renumbered type from typeck.
1316 .at(&ObligationCause::dummy(), param_env)
1317 .eq(opaque_decl.concrete_ty, renumbered_opaque_defn_ty)?,
1319 opaque_type_values.push((
1321 ty::ResolvedOpaqueTy {
1322 concrete_type: renumbered_opaque_defn_ty,
1323 substs: opaque_decl.substs,
1327 // We're using an opaque `impl Trait` type without
1328 // 'revealing' it. For example, code like this:
1330 // type Foo = impl Debug;
1331 // fn foo1() -> Foo { ... }
1332 // fn foo2() -> Foo { foo1() }
1334 // In `foo2`, we're not revealing the type of `Foo` - we're
1335 // just treating it as the opaque type.
1337 // When this occurs, we do *not* want to try to equate
1338 // the concrete type with the underlying defining type
1339 // of the opaque type - this will always fail, since
1340 // the defining type of an opaque type is always
1341 // some other type (e.g. not itself)
1342 // Essentially, none of the normal obligations apply here -
1343 // we're just passing around some unknown opaque type,
1344 // without actually looking at the underlying type it
1345 // gets 'revealed' into
1347 "eq_opaque_type_and_type: non-defining use of {:?}",
1353 debug!("eq_opaque_type_and_type: equated");
1356 value: Some(opaque_type_map),
1357 obligations: obligations.into_vec(),
1360 || "input_output".to_string(),
1364 self.opaque_type_values.extend(opaque_type_values);
1366 let universal_region_relations = self.universal_region_relations;
1368 // Finally, if we instantiated the anon types successfully, we
1369 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1370 // prove that `T: Iterator` where `T` is the type we
1371 // instantiated it with).
1372 if let Some(opaque_type_map) = opaque_type_map {
1373 for (opaque_def_id, opaque_decl) in opaque_type_map {
1374 self.fully_perform_op(
1376 ConstraintCategory::OpaqueType,
1379 infcx.constrain_opaque_type(
1382 GenerateMemberConstraints::IfNoStaticBound,
1383 universal_region_relations,
1385 Ok(InferOk { value: (), obligations: vec![] })
1387 || "opaque_type_map".to_string(),
1395 fn tcx(&self) -> TyCtxt<'tcx> {
1401 body: ReadOnlyBodyAndCache<'_, 'tcx>,
1402 stmt: &Statement<'tcx>,
1405 debug!("check_stmt: {:?}", stmt);
1406 let tcx = self.tcx();
1408 StatementKind::Assign(box (ref place, ref rv)) => {
1409 // Assignments to temporaries are not "interesting";
1410 // they are not caused by the user, but rather artifacts
1411 // of lowering. Assignments to other sorts of places *are* interesting
1413 let category = match place.as_local() {
1414 Some(RETURN_PLACE) => {
1415 if let BorrowCheckContext {
1417 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1419 } = self.borrowck_context
1421 if tcx.is_static(*def_id) {
1422 ConstraintCategory::UseAsStatic
1424 ConstraintCategory::UseAsConst
1427 ConstraintCategory::Return
1430 Some(l) if !body.local_decls[l].is_user_variable() => {
1431 ConstraintCategory::Boring
1433 _ => ConstraintCategory::Assignment,
1436 let place_ty = place.ty(*body, tcx).ty;
1437 let place_ty = self.normalize(place_ty, location);
1438 let rv_ty = rv.ty(*body, tcx);
1439 let rv_ty = self.normalize(rv_ty, location);
1441 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1446 "bad assignment ({:?} = {:?}): {:?}",
1453 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1454 if let Err(terr) = self.relate_type_and_user_type(
1456 ty::Variance::Invariant,
1457 &UserTypeProjection { base: annotation_index, projs: vec![] },
1458 location.to_locations(),
1459 ConstraintCategory::Boring,
1461 let annotation = &self.user_type_annotations[annotation_index];
1465 "bad user type on rvalue ({:?} = {:?}): {:?}",
1473 self.check_rvalue(body, rv, location);
1474 if !self.tcx().features().unsized_locals {
1475 let trait_ref = ty::TraitRef {
1476 def_id: tcx.lang_items().sized_trait().unwrap(),
1477 substs: tcx.mk_substs_trait(place_ty, &[]),
1479 self.prove_trait_ref(
1481 location.to_locations(),
1482 ConstraintCategory::SizedBound,
1486 StatementKind::SetDiscriminant { ref place, variant_index } => {
1487 let place_type = place.ty(*body, tcx).ty;
1488 let adt = match place_type.kind {
1489 ty::Adt(adt, _) if adt.is_enum() => adt,
1492 stmt.source_info.span,
1493 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1499 if variant_index.as_usize() >= adt.variants.len() {
1501 stmt.source_info.span,
1502 "bad set discriminant ({:?} = {:?}): value of of range",
1508 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1509 let place_ty = place.ty(*body, tcx).ty;
1510 if let Err(terr) = self.relate_type_and_user_type(
1514 Locations::All(stmt.source_info.span),
1515 ConstraintCategory::TypeAnnotation,
1517 let annotation = &self.user_type_annotations[projection.base];
1521 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1529 StatementKind::FakeRead(..)
1530 | StatementKind::StorageLive(..)
1531 | StatementKind::StorageDead(..)
1532 | StatementKind::LlvmInlineAsm { .. }
1533 | StatementKind::Retag { .. }
1534 | StatementKind::Nop => {}
1538 fn check_terminator(
1541 term: &Terminator<'tcx>,
1542 term_location: Location,
1544 debug!("check_terminator: {:?}", term);
1545 let tcx = self.tcx();
1547 TerminatorKind::Goto { .. }
1548 | TerminatorKind::Resume
1549 | TerminatorKind::Abort
1550 | TerminatorKind::Return
1551 | TerminatorKind::GeneratorDrop
1552 | TerminatorKind::Unreachable
1553 | TerminatorKind::Drop { .. }
1554 | TerminatorKind::FalseEdges { .. }
1555 | TerminatorKind::FalseUnwind { .. } => {
1556 // no checks needed for these
1559 TerminatorKind::DropAndReplace { ref location, ref value, target: _, unwind: _ } => {
1560 let place_ty = location.ty(body, tcx).ty;
1561 let rv_ty = value.ty(body, tcx);
1563 let locations = term_location.to_locations();
1565 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1570 "bad DropAndReplace ({:?} = {:?}): {:?}",
1577 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1578 let discr_ty = discr.ty(body, tcx);
1579 if let Err(terr) = self.sub_types(
1582 term_location.to_locations(),
1583 ConstraintCategory::Assignment,
1588 "bad SwitchInt ({:?} on {:?}): {:?}",
1594 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1595 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1597 // FIXME: check the values
1599 TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1600 let func_ty = func.ty(body, tcx);
1601 debug!("check_terminator: call, func_ty={:?}", func_ty);
1602 let sig = match func_ty.kind {
1603 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1605 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1609 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1610 term.source_info.span,
1611 LateBoundRegionConversionTime::FnCall,
1614 let sig = self.normalize(sig, term_location);
1615 self.check_call_dest(body, term, &sig, destination, term_location);
1617 self.prove_predicates(
1618 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1619 term_location.to_locations(),
1620 ConstraintCategory::Boring,
1623 // The ordinary liveness rules will ensure that all
1624 // regions in the type of the callee are live here. We
1625 // then further constrain the late-bound regions that
1626 // were instantiated at the call site to be live as
1627 // well. The resulting is that all the input (and
1628 // output) types in the signature must be live, since
1629 // all the inputs that fed into it were live.
1630 for &late_bound_region in map.values() {
1632 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1633 self.borrowck_context
1635 .liveness_constraints
1636 .add_element(region_vid, term_location);
1639 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1641 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1642 let cond_ty = cond.ty(body, tcx);
1643 if cond_ty != tcx.types.bool {
1644 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1647 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1648 if len.ty(body, tcx) != tcx.types.usize {
1649 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1651 if index.ty(body, tcx) != tcx.types.usize {
1652 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1656 TerminatorKind::Yield { ref value, .. } => {
1657 let value_ty = value.ty(body, tcx);
1658 match body.yield_ty {
1659 None => span_mirbug!(self, term, "yield in non-generator"),
1661 if let Err(terr) = self.sub_types(
1664 term_location.to_locations(),
1665 ConstraintCategory::Yield,
1670 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1685 term: &Terminator<'tcx>,
1686 sig: &ty::FnSig<'tcx>,
1687 destination: &Option<(Place<'tcx>, BasicBlock)>,
1688 term_location: Location,
1690 let tcx = self.tcx();
1691 match *destination {
1692 Some((ref dest, _target_block)) => {
1693 let dest_ty = dest.ty(body, tcx).ty;
1694 let dest_ty = self.normalize(dest_ty, term_location);
1695 let category = match dest.as_local() {
1696 Some(RETURN_PLACE) => {
1697 if let BorrowCheckContext {
1699 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1701 } = self.borrowck_context
1703 if tcx.is_static(*def_id) {
1704 ConstraintCategory::UseAsStatic
1706 ConstraintCategory::UseAsConst
1709 ConstraintCategory::Return
1712 Some(l) if !body.local_decls[l].is_user_variable() => {
1713 ConstraintCategory::Boring
1715 _ => ConstraintCategory::Assignment,
1718 let locations = term_location.to_locations();
1721 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1726 "call dest mismatch ({:?} <- {:?}): {:?}",
1733 // When `#![feature(unsized_locals)]` is not enabled,
1734 // this check is done at `check_local`.
1735 if self.tcx().features().unsized_locals {
1736 let span = term.source_info.span;
1737 self.ensure_place_sized(dest_ty, span);
1741 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1742 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1748 fn check_call_inputs(
1751 term: &Terminator<'tcx>,
1752 sig: &ty::FnSig<'tcx>,
1753 args: &[Operand<'tcx>],
1754 term_location: Location,
1755 from_hir_call: bool,
1757 debug!("check_call_inputs({:?}, {:?})", sig, args);
1758 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1759 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1761 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1762 let op_arg_ty = op_arg.ty(body, self.tcx());
1763 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1764 let category = if from_hir_call {
1765 ConstraintCategory::CallArgument
1767 ConstraintCategory::Boring
1770 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1775 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1785 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1786 let is_cleanup = block_data.is_cleanup;
1787 self.last_span = block_data.terminator().source_info.span;
1788 match block_data.terminator().kind {
1789 TerminatorKind::Goto { target } => {
1790 self.assert_iscleanup(body, block_data, target, is_cleanup)
1792 TerminatorKind::SwitchInt { ref targets, .. } => {
1793 for target in targets {
1794 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1797 TerminatorKind::Resume => {
1799 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1802 TerminatorKind::Abort => {
1804 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1807 TerminatorKind::Return => {
1809 span_mirbug!(self, block_data, "return on cleanup block")
1812 TerminatorKind::GeneratorDrop { .. } => {
1814 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1817 TerminatorKind::Yield { resume, drop, .. } => {
1819 span_mirbug!(self, block_data, "yield in cleanup block")
1821 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1822 if let Some(drop) = drop {
1823 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1826 TerminatorKind::Unreachable => {}
1827 TerminatorKind::Drop { target, unwind, .. }
1828 | TerminatorKind::DropAndReplace { target, unwind, .. }
1829 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1830 self.assert_iscleanup(body, block_data, target, is_cleanup);
1831 if let Some(unwind) = unwind {
1833 span_mirbug!(self, block_data, "unwind on cleanup block")
1835 self.assert_iscleanup(body, block_data, unwind, true);
1838 TerminatorKind::Call { ref destination, cleanup, .. } => {
1839 if let &Some((_, target)) = destination {
1840 self.assert_iscleanup(body, block_data, target, is_cleanup);
1842 if let Some(cleanup) = cleanup {
1844 span_mirbug!(self, block_data, "cleanup on cleanup block")
1846 self.assert_iscleanup(body, block_data, cleanup, true);
1849 TerminatorKind::FalseEdges { real_target, imaginary_target } => {
1850 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1851 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1853 TerminatorKind::FalseUnwind { real_target, unwind } => {
1854 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1855 if let Some(unwind) = unwind {
1857 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1859 self.assert_iscleanup(body, block_data, unwind, true);
1865 fn assert_iscleanup(
1868 ctxt: &dyn fmt::Debug,
1872 if body[bb].is_cleanup != iscleanuppad {
1873 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1877 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1878 match body.local_kind(local) {
1879 LocalKind::ReturnPointer | LocalKind::Arg => {
1880 // return values of normal functions are required to be
1881 // sized by typeck, but return values of ADT constructors are
1882 // not because we don't include a `Self: Sized` bounds on them.
1884 // Unbound parts of arguments were never required to be Sized
1885 // - maybe we should make that a warning.
1888 LocalKind::Var | LocalKind::Temp => {}
1891 // When `#![feature(unsized_locals)]` is enabled, only function calls
1892 // and nullary ops are checked in `check_call_dest`.
1893 if !self.tcx().features().unsized_locals {
1894 let span = local_decl.source_info.span;
1895 let ty = local_decl.ty;
1896 self.ensure_place_sized(ty, span);
1900 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1901 let tcx = self.tcx();
1903 // Erase the regions from `ty` to get a global type. The
1904 // `Sized` bound in no way depends on precise regions, so this
1905 // shouldn't affect `is_sized`.
1906 let erased_ty = tcx.erase_regions(&ty);
1907 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1908 // in current MIR construction, all non-control-flow rvalue
1909 // expressions evaluate through `as_temp` or `into` a return
1910 // slot or local, so to find all unsized rvalues it is enough
1911 // to check all temps, return slots and locals.
1912 if self.reported_errors.replace((ty, span)).is_none() {
1913 let mut diag = struct_span_err!(
1917 "cannot move a value of type {0}: the size of {0} \
1918 cannot be statically determined",
1922 // While this is located in `nll::typeck` this error is not
1923 // an NLL error, it's a required check to prevent creation
1924 // of unsized rvalues in certain cases:
1925 // * operand of a box expression
1926 // * callee in a call expression
1932 fn aggregate_field_ty(
1934 ak: &AggregateKind<'tcx>,
1937 ) -> Result<Ty<'tcx>, FieldAccessError> {
1938 let tcx = self.tcx();
1941 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1942 let variant = &def.variants[variant_index];
1943 let adj_field_index = active_field_index.unwrap_or(field_index);
1944 if let Some(field) = variant.fields.get(adj_field_index) {
1945 Ok(self.normalize(field.ty(tcx, substs), location))
1947 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1950 AggregateKind::Closure(_, substs) => {
1951 match substs.as_closure().upvar_tys().nth(field_index) {
1953 None => Err(FieldAccessError::OutOfRange {
1954 field_count: substs.as_closure().upvar_tys().count(),
1958 AggregateKind::Generator(_, substs, _) => {
1959 // It doesn't make sense to look at a field beyond the prefix;
1960 // these require a variant index, and are not initialized in
1961 // aggregate rvalues.
1962 match substs.as_generator().prefix_tys().nth(field_index) {
1964 None => Err(FieldAccessError::OutOfRange {
1965 field_count: substs.as_generator().prefix_tys().count(),
1969 AggregateKind::Array(ty) => Ok(ty),
1970 AggregateKind::Tuple => {
1971 unreachable!("This should have been covered in check_rvalues");
1978 body: ReadOnlyBodyAndCache<'_, 'tcx>,
1979 rvalue: &Rvalue<'tcx>,
1982 let tcx = self.tcx();
1985 Rvalue::Aggregate(ak, ops) => {
1986 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1989 Rvalue::Repeat(operand, len) => {
1990 // If the length cannot be evaluated we must assume that the length can be larger
1992 // If the length is larger than 1, the repeat expression will need to copy the
1993 // element, so we require the `Copy` trait.
1994 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1995 if let Operand::Move(_) = operand {
1996 // While this is located in `nll::typeck` this error is not an NLL error, it's
1997 // a required check to make sure that repeated elements implement `Copy`.
1998 let span = body.source_info(location).span;
1999 let ty = operand.ty(*body, tcx);
2000 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
2001 // To determine if `const_in_array_repeat_expressions` feature gate should
2002 // be mentioned, need to check if the rvalue is promotable.
2003 let should_suggest =
2004 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(
2018 .local_def_id_to_hir_id(self.mir_def_id.expect_local()),
2019 traits::ObligationCauseCode::RepeatVec(should_suggest),
2022 ty::Predicate::Trait(
2023 ty::Binder::bind(ty::TraitPredicate {
2024 trait_ref: ty::TraitRef::new(
2025 self.tcx().lang_items().copy_trait().unwrap(),
2026 tcx.mk_substs_trait(ty, &[]),
2029 hir::Constness::NotConst,
2032 &traits::SelectionError::Unimplemented,
2041 Rvalue::NullaryOp(_, ty) => {
2042 // Even with unsized locals cannot box an unsized value.
2043 if self.tcx().features().unsized_locals {
2044 let span = body.source_info(location).span;
2045 self.ensure_place_sized(ty, span);
2048 let trait_ref = ty::TraitRef {
2049 def_id: tcx.lang_items().sized_trait().unwrap(),
2050 substs: tcx.mk_substs_trait(ty, &[]),
2053 self.prove_trait_ref(
2055 location.to_locations(),
2056 ConstraintCategory::SizedBound,
2060 Rvalue::Cast(cast_kind, op, ty) => {
2062 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2063 let fn_sig = op.ty(*body, tcx).fn_sig(tcx);
2065 // The type that we see in the fcx is like
2066 // `foo::<'a, 'b>`, where `foo` is the path to a
2067 // function definition. When we extract the
2068 // signature, it comes from the `fn_sig` query,
2069 // and hence may contain unnormalized results.
2070 let fn_sig = self.normalize(fn_sig, location);
2072 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2074 if let Err(terr) = self.eq_types(
2077 location.to_locations(),
2078 ConstraintCategory::Cast,
2083 "equating {:?} with {:?} yields {:?}",
2091 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2092 let sig = match op.ty(*body, tcx).kind {
2093 ty::Closure(_, substs) => substs.as_closure().sig(),
2096 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2098 if let Err(terr) = self.eq_types(
2101 location.to_locations(),
2102 ConstraintCategory::Cast,
2107 "equating {:?} with {:?} yields {:?}",
2115 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2116 let fn_sig = op.ty(*body, tcx).fn_sig(tcx);
2118 // The type that we see in the fcx is like
2119 // `foo::<'a, 'b>`, where `foo` is the path to a
2120 // function definition. When we extract the
2121 // signature, it comes from the `fn_sig` query,
2122 // and hence may contain unnormalized results.
2123 let fn_sig = self.normalize(fn_sig, location);
2125 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2127 if let Err(terr) = self.eq_types(
2130 location.to_locations(),
2131 ConstraintCategory::Cast,
2136 "equating {:?} with {:?} yields {:?}",
2144 CastKind::Pointer(PointerCast::Unsize) => {
2146 let trait_ref = ty::TraitRef {
2147 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2148 substs: tcx.mk_substs_trait(op.ty(*body, tcx), &[ty.into()]),
2151 self.prove_trait_ref(
2153 location.to_locations(),
2154 ConstraintCategory::Cast,
2158 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2159 let ty_from = match op.ty(*body, tcx).kind {
2160 ty::RawPtr(ty::TypeAndMut {
2162 mutbl: hir::Mutability::Mut,
2168 "unexpected base type for cast {:?}",
2174 let ty_to = match ty.kind {
2175 ty::RawPtr(ty::TypeAndMut {
2177 mutbl: hir::Mutability::Not,
2183 "unexpected target type for cast {:?}",
2189 if let Err(terr) = self.sub_types(
2192 location.to_locations(),
2193 ConstraintCategory::Cast,
2198 "relating {:?} with {:?} yields {:?}",
2206 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2207 let ty_from = op.ty(*body, tcx);
2209 let opt_ty_elem = match ty_from.kind {
2210 ty::RawPtr(ty::TypeAndMut {
2211 mutbl: hir::Mutability::Not,
2213 }) => match array_ty.kind {
2214 ty::Array(ty_elem, _) => Some(ty_elem),
2220 let ty_elem = match opt_ty_elem {
2221 Some(ty_elem) => ty_elem,
2226 "ArrayToPointer cast from unexpected type {:?}",
2233 let ty_to = match ty.kind {
2234 ty::RawPtr(ty::TypeAndMut {
2235 mutbl: hir::Mutability::Not,
2242 "ArrayToPointer cast to unexpected type {:?}",
2249 if let Err(terr) = self.sub_types(
2252 location.to_locations(),
2253 ConstraintCategory::Cast,
2258 "relating {:?} with {:?} yields {:?}",
2267 let ty_from = op.ty(*body, tcx);
2268 let cast_ty_from = CastTy::from_ty(ty_from);
2269 let cast_ty_to = CastTy::from_ty(ty);
2270 match (cast_ty_from, cast_ty_to) {
2272 | (_, None | Some(CastTy::FnPtr))
2273 | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2274 | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => {
2275 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2278 Some(CastTy::Int(_)),
2279 Some(CastTy::Int(_) | CastTy::Float | CastTy::Ptr(_)),
2281 | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float))
2282 | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_)))
2283 | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (),
2289 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2290 self.add_reborrow_constraint(&body, location, region, borrowed_place);
2294 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2298 let ty_left = left.ty(*body, tcx);
2299 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.kind {
2300 let ty_right = right.ty(*body, tcx);
2301 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2302 kind: TypeVariableOriginKind::MiscVariable,
2303 span: body.source_info(location).span,
2308 location.to_locations(),
2309 ConstraintCategory::Boring,
2311 .unwrap_or_else(|err| {
2312 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2314 if let Err(terr) = self.sub_types(
2317 location.to_locations(),
2318 ConstraintCategory::Boring,
2323 "unexpected comparison types {:?} and {:?} yields {:?}",
2332 Rvalue::AddressOf(..)
2335 | Rvalue::BinaryOp(..)
2336 | Rvalue::CheckedBinaryOp(..)
2337 | Rvalue::UnaryOp(..)
2338 | Rvalue::Discriminant(..) => {}
2342 /// If this rvalue supports a user-given type annotation, then
2343 /// extract and return it. This represents the final type of the
2344 /// rvalue and will be unified with the inferred type.
2345 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2348 | Rvalue::Repeat(..)
2350 | Rvalue::AddressOf(..)
2353 | Rvalue::BinaryOp(..)
2354 | Rvalue::CheckedBinaryOp(..)
2355 | Rvalue::NullaryOp(..)
2356 | Rvalue::UnaryOp(..)
2357 | Rvalue::Discriminant(..) => None,
2359 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2360 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2361 AggregateKind::Array(_) => None,
2362 AggregateKind::Tuple => None,
2363 AggregateKind::Closure(_, _) => None,
2364 AggregateKind::Generator(_, _, _) => None,
2369 fn check_aggregate_rvalue(
2372 rvalue: &Rvalue<'tcx>,
2373 aggregate_kind: &AggregateKind<'tcx>,
2374 operands: &[Operand<'tcx>],
2377 let tcx = self.tcx();
2379 self.prove_aggregate_predicates(aggregate_kind, location);
2381 if *aggregate_kind == AggregateKind::Tuple {
2382 // tuple rvalue field type is always the type of the op. Nothing to check here.
2386 for (i, operand) in operands.iter().enumerate() {
2387 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2388 Ok(field_ty) => field_ty,
2389 Err(FieldAccessError::OutOfRange { field_count }) => {
2393 "accessed field #{} but variant only has {}",
2400 let operand_ty = operand.ty(body, tcx);
2401 let operand_ty = self.normalize(operand_ty, location);
2403 if let Err(terr) = self.sub_types(
2406 location.to_locations(),
2407 ConstraintCategory::Boring,
2412 "{:?} is not a subtype of {:?}: {:?}",
2421 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2425 /// - `location`: the location `L` where the borrow expression occurs
2426 /// - `borrow_region`: the region `'a` associated with the borrow
2427 /// - `borrowed_place`: the place `P` being borrowed
2428 fn add_reborrow_constraint(
2432 borrow_region: ty::Region<'tcx>,
2433 borrowed_place: &Place<'tcx>,
2435 // These constraints are only meaningful during borrowck:
2436 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2437 self.borrowck_context;
2439 // In Polonius mode, we also push a `borrow_region` fact
2440 // linking the loan to the region (in some cases, though,
2441 // there is no loan associated with this borrow expression --
2442 // that occurs when we are borrowing an unsafe place, for
2444 if let Some(all_facts) = all_facts {
2445 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2446 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2447 let region_vid = borrow_region.to_region_vid();
2448 all_facts.borrow_region.push((
2451 location_table.mid_index(location),
2456 // If we are reborrowing the referent of another reference, we
2457 // need to add outlives relationships. In a case like `&mut
2458 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2459 // need to ensure that `'b: 'a`.
2462 "add_reborrow_constraint({:?}, {:?}, {:?})",
2463 location, borrow_region, borrowed_place
2466 let mut cursor = borrowed_place.projection.as_ref();
2467 while let [proj_base @ .., elem] = cursor {
2470 debug!("add_reborrow_constraint - iteration {:?}", elem);
2473 ProjectionElem::Deref => {
2474 let tcx = self.infcx.tcx;
2475 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2477 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2478 match base_ty.kind {
2479 ty::Ref(ref_region, _, mutbl) => {
2480 constraints.outlives_constraints.push(OutlivesConstraint {
2481 sup: ref_region.to_region_vid(),
2482 sub: borrow_region.to_region_vid(),
2483 locations: location.to_locations(),
2484 category: ConstraintCategory::Boring,
2488 hir::Mutability::Not => {
2489 // Immutable reference. We don't need the base
2490 // to be valid for the entire lifetime of
2494 hir::Mutability::Mut => {
2495 // Mutable reference. We *do* need the base
2496 // to be valid, because after the base becomes
2497 // invalid, someone else can use our mutable deref.
2499 // This is in order to make the following function
2502 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2507 // As otherwise you could clone `&mut T` using the
2508 // following function:
2510 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2511 // let my_clone = unsafe_deref(&'a x);
2520 // deref of raw pointer, guaranteed to be valid
2523 ty::Adt(def, _) if def.is_box() => {
2524 // deref of `Box`, need the base to be valid - propagate
2526 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2529 ProjectionElem::Field(..)
2530 | ProjectionElem::Downcast(..)
2531 | ProjectionElem::Index(..)
2532 | ProjectionElem::ConstantIndex { .. }
2533 | ProjectionElem::Subslice { .. } => {
2534 // other field access
2540 fn prove_aggregate_predicates(
2542 aggregate_kind: &AggregateKind<'tcx>,
2545 let tcx = self.tcx();
2548 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2549 aggregate_kind, location
2552 let instantiated_predicates = match aggregate_kind {
2553 AggregateKind::Adt(def, _, substs, _, _) => {
2554 tcx.predicates_of(def.did).instantiate(tcx, substs)
2557 // For closures, we have some **extra requirements** we
2559 // have to check. In particular, in their upvars and
2560 // signatures, closures often reference various regions
2561 // from the surrounding function -- we call those the
2562 // closure's free regions. When we borrow-check (and hence
2563 // region-check) closures, we may find that the closure
2564 // requires certain relationships between those free
2565 // regions. However, because those free regions refer to
2566 // portions of the CFG of their caller, the closure is not
2567 // in a position to verify those relationships. In that
2568 // case, the requirements get "propagated" to us, and so
2569 // we have to solve them here where we instantiate the
2572 // Despite the opacity of the previous parapgrah, this is
2573 // actually relatively easy to understand in terms of the
2574 // desugaring. A closure gets desugared to a struct, and
2575 // these extra requirements are basically like where
2576 // clauses on the struct.
2577 AggregateKind::Closure(def_id, substs)
2578 | AggregateKind::Generator(def_id, substs, _) => {
2579 self.prove_closure_bounds(tcx, *def_id, substs, location)
2582 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2585 self.normalize_and_prove_instantiated_predicates(
2586 instantiated_predicates,
2587 location.to_locations(),
2591 fn prove_closure_bounds(
2595 substs: SubstsRef<'tcx>,
2597 ) -> ty::InstantiatedPredicates<'tcx> {
2598 if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2600 let closure_constraints = QueryRegionConstraints {
2601 outlives: closure_region_requirements.apply_requirements(tcx, def_id, substs),
2603 // Presently, closures never propagate member
2604 // constraints to their parents -- they are enforced
2605 // locally. This is largely a non-issue as member
2606 // constraints only come from `-> impl Trait` and
2607 // friends which don't appear (thus far...) in
2609 member_constraints: vec![],
2612 let bounds_mapping = closure_constraints
2616 .filter_map(|(idx, constraint)| {
2617 let ty::OutlivesPredicate(k1, r2) =
2618 constraint.no_bound_vars().unwrap_or_else(|| {
2619 bug!("query_constraint {:?} contained bound vars", constraint,);
2623 GenericArgKind::Lifetime(r1) => {
2624 // constraint is r1: r2
2625 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2626 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2627 let outlives_requirements =
2628 &closure_region_requirements.outlives_requirements[idx];
2631 (outlives_requirements.category, outlives_requirements.blame_span),
2634 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2642 .closure_bounds_mapping
2643 .insert(location, bounds_mapping);
2644 assert!(existing.is_none(), "Multiple closures at the same location.");
2646 self.push_region_constraints(
2647 location.to_locations(),
2648 ConstraintCategory::ClosureBounds,
2649 &closure_constraints,
2653 tcx.predicates_of(def_id).instantiate(tcx, substs)
2658 trait_ref: ty::TraitRef<'tcx>,
2659 locations: Locations,
2660 category: ConstraintCategory,
2662 self.prove_predicates(
2663 Some(ty::Predicate::Trait(
2664 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2665 hir::Constness::NotConst,
2672 fn normalize_and_prove_instantiated_predicates(
2674 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2675 locations: Locations,
2677 for predicate in instantiated_predicates.predicates {
2678 let predicate = self.normalize(predicate, locations);
2679 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2683 fn prove_predicates(
2685 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2686 locations: Locations,
2687 category: ConstraintCategory,
2689 for predicate in predicates {
2690 debug!("prove_predicates(predicate={:?}, locations={:?})", predicate, locations,);
2692 self.prove_predicate(predicate, locations, category);
2698 predicate: ty::Predicate<'tcx>,
2699 locations: Locations,
2700 category: ConstraintCategory,
2702 debug!("prove_predicate(predicate={:?}, location={:?})", predicate, locations,);
2704 let param_env = self.param_env;
2705 self.fully_perform_op(
2708 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2710 .unwrap_or_else(|NoSolution| {
2711 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2715 fn typeck_mir(&mut self, body: ReadOnlyBodyAndCache<'_, 'tcx>) {
2716 self.last_span = body.span;
2717 debug!("run_on_mir: {:?}", body.span);
2719 for (local, local_decl) in body.local_decls.iter_enumerated() {
2720 self.check_local(&body, local, local_decl);
2723 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2724 let mut location = Location { block, statement_index: 0 };
2725 for stmt in &block_data.statements {
2726 if !stmt.source_info.span.is_dummy() {
2727 self.last_span = stmt.source_info.span;
2729 self.check_stmt(body, stmt, location);
2730 location.statement_index += 1;
2733 self.check_terminator(&body, block_data.terminator(), location);
2734 self.check_iscleanup(&body, block_data);
2738 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2740 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2742 debug!("normalize(value={:?}, location={:?})", value, location);
2743 let param_env = self.param_env;
2744 self.fully_perform_op(
2745 location.to_locations(),
2746 ConstraintCategory::Boring,
2747 param_env.and(type_op::normalize::Normalize::new(value)),
2749 .unwrap_or_else(|NoSolution| {
2750 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2756 trait NormalizeLocation: fmt::Debug + Copy {
2757 fn to_locations(self) -> Locations;
2760 impl NormalizeLocation for Locations {
2761 fn to_locations(self) -> Locations {
2766 impl NormalizeLocation for Location {
2767 fn to_locations(self) -> Locations {
2768 Locations::Single(self)
2772 #[derive(Debug, Default)]
2773 struct ObligationAccumulator<'tcx> {
2774 obligations: PredicateObligations<'tcx>,
2777 impl<'tcx> ObligationAccumulator<'tcx> {
2778 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2779 let InferOk { value, obligations } = value;
2780 self.obligations.extend(obligations);
2784 fn into_vec(self) -> PredicateObligations<'tcx> {