1 //! This pass type-checks the MIR to ensure it is not broken.
4 use std::{fmt, iter, mem};
8 use rustc::infer::canonical::QueryRegionConstraints;
9 use rustc::infer::outlives::env::RegionBoundPairs;
10 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
11 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
12 use rustc::mir::interpret::PanicInfo;
13 use rustc::mir::tcx::PlaceTy;
14 use rustc::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
16 use rustc::traits::query::type_op;
17 use rustc::traits::query::type_op::custom::CustomTypeOp;
18 use rustc::traits::query::{Fallible, NoSolution};
19 use rustc::traits::{self, ObligationCause, PredicateObligations};
20 use rustc::ty::adjustment::PointerCast;
21 use rustc::ty::cast::CastTy;
22 use rustc::ty::fold::TypeFoldable;
23 use rustc::ty::layout::VariantIdx;
24 use rustc::ty::subst::{GenericArgKind, Subst, SubstsRef, UserSubsts};
26 self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, RegionVid, ToPolyTraitRef, Ty,
27 TyCtxt, UserType, UserTypeAnnotationIndex,
29 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
30 use rustc_error_codes::*;
31 use rustc_errors::struct_span_err;
33 use rustc_hir::def_id::DefId;
34 use rustc_index::vec::{Idx, IndexVec};
35 use rustc_span::{Span, DUMMY_SP};
37 use crate::dataflow::move_paths::MoveData;
38 use crate::dataflow::FlowAtLocation;
39 use crate::dataflow::MaybeInitializedPlaces;
40 use crate::transform::promote_consts::should_suggest_const_in_array_repeat_expressions_attribute;
42 use crate::borrow_check::{
43 borrow_set::BorrowSet,
44 constraints::{OutlivesConstraint, OutlivesConstraintSet},
46 location::LocationTable,
47 member_constraints::MemberConstraintSet,
49 region_infer::values::{
50 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
52 region_infer::{ClosureRegionRequirementsExt, TypeTest},
54 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
55 universal_regions::{DefiningTy, UniversalRegions},
58 macro_rules! span_mirbug {
59 ($context:expr, $elem:expr, $($message:tt)*) => ({
60 $crate::borrow_check::type_check::mirbug(
64 "broken MIR in {:?} ({:?}): {}",
67 format_args!($($message)*),
73 macro_rules! span_mirbug_and_err {
74 ($context:expr, $elem:expr, $($message:tt)*) => ({
76 span_mirbug!($context, $elem, $($message)*);
82 mod constraint_conversion;
83 pub mod free_region_relations;
88 /// Type checks the given `mir` in the context of the inference
89 /// context `infcx`. Returns any region constraints that have yet to
90 /// be proven. This result is includes liveness constraints that
91 /// ensure that regions appearing in the types of all local variables
92 /// are live at all points where that local variable may later be
95 /// This phase of type-check ought to be infallible -- this is because
96 /// the original, HIR-based type-check succeeded. So if any errors
97 /// occur here, we will get a `bug!` reported.
101 /// - `infcx` -- inference context to use
102 /// - `param_env` -- parameter environment to use for trait solving
103 /// - `mir` -- MIR to type-check
104 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
105 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
106 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
107 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
108 /// to outlive; should represent the fn body
109 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
110 /// the types of the input parameters found in the MIR itself will be equated with these
111 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
112 /// the type for the RETURN_PLACE will be equated with this
113 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
114 /// constraints for the regions in the types of variables
115 /// - `flow_inits` -- results of a maybe-init dataflow analysis
116 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
117 pub(crate) fn type_check<'tcx>(
118 infcx: &InferCtxt<'_, 'tcx>,
119 param_env: ty::ParamEnv<'tcx>,
120 body: ReadOnlyBodyAndCache<'_, 'tcx>,
121 promoted: &IndexVec<Promoted, ReadOnlyBodyAndCache<'_, 'tcx>>,
123 universal_regions: &Rc<UniversalRegions<'tcx>>,
124 location_table: &LocationTable,
125 borrow_set: &BorrowSet<'tcx>,
126 all_facts: &mut Option<AllFacts>,
127 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'_, 'tcx>>,
128 move_data: &MoveData<'tcx>,
129 elements: &Rc<RegionValueElements>,
130 ) -> MirTypeckResults<'tcx> {
131 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
132 let mut constraints = MirTypeckRegionConstraints {
133 placeholder_indices: PlaceholderIndices::default(),
134 placeholder_index_to_region: IndexVec::default(),
135 liveness_constraints: LivenessValues::new(elements.clone()),
136 outlives_constraints: OutlivesConstraintSet::default(),
137 member_constraints: MemberConstraintSet::default(),
138 closure_bounds_mapping: Default::default(),
139 type_tests: Vec::default(),
143 universal_region_relations,
145 normalized_inputs_and_output,
146 } = free_region_relations::create(
149 Some(implicit_region_bound),
154 let mut borrowck_context = BorrowCheckContext {
159 constraints: &mut constraints,
169 implicit_region_bound,
170 &mut borrowck_context,
171 &universal_region_relations,
173 cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
174 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
176 translate_outlives_facts(&mut cx);
180 MirTypeckResults { constraints, universal_region_relations }
183 fn type_check_internal<'a, 'tcx, R>(
184 infcx: &'a InferCtxt<'a, 'tcx>,
186 param_env: ty::ParamEnv<'tcx>,
187 body: ReadOnlyBodyAndCache<'a, 'tcx>,
188 promoted: &'a IndexVec<Promoted, ReadOnlyBodyAndCache<'_, 'tcx>>,
189 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
190 implicit_region_bound: ty::Region<'tcx>,
191 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
192 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
193 mut extra: impl FnMut(&mut TypeChecker<'a, 'tcx>) -> R,
195 let mut checker = TypeChecker::new(
201 implicit_region_bound,
203 universal_region_relations,
205 let errors_reported = {
206 let mut verifier = TypeVerifier::new(&mut checker, *body, promoted);
207 verifier.visit_body(body);
208 verifier.errors_reported
211 if !errors_reported {
212 // if verifier failed, don't do further checks to avoid ICEs
213 checker.typeck_mir(body);
219 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
220 let cx = &mut typeck.borrowck_context;
221 if let Some(facts) = cx.all_facts {
222 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
223 let location_table = cx.location_table;
224 facts.outlives.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
225 |constraint: &OutlivesConstraint| {
226 if let Some(from_location) = constraint.locations.from_location() {
227 Either::Left(iter::once((
230 location_table.mid_index(from_location),
236 .map(move |location| (constraint.sup, constraint.sub, location)),
244 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
245 // We sometimes see MIR failures (notably predicate failures) due to
246 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
247 // to avoid reporting bugs in those cases.
248 tcx.sess.diagnostic().delay_span_bug(span, msg);
251 enum FieldAccessError {
252 OutOfRange { field_count: usize },
255 /// Verifies that MIR types are sane to not crash further checks.
257 /// The sanitize_XYZ methods here take an MIR object and compute its
258 /// type, calling `span_mirbug` and returning an error type if there
260 struct TypeVerifier<'a, 'b, 'tcx> {
261 cx: &'a mut TypeChecker<'b, 'tcx>,
262 body: &'b Body<'tcx>,
263 promoted: &'b IndexVec<Promoted, ReadOnlyBodyAndCache<'b, 'tcx>>,
266 errors_reported: bool,
269 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
270 fn visit_span(&mut self, span: &Span) {
271 if !span.is_dummy() {
272 self.last_span = *span;
276 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
277 self.sanitize_place(place, location, context);
280 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
281 self.super_constant(constant, location);
282 let ty = self.sanitize_type(constant, constant.literal.ty);
284 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
285 let live_region_vid =
286 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
290 .liveness_constraints
291 .add_element(live_region_vid, location);
294 if let Some(annotation_index) = constant.user_ty {
295 if let Err(terr) = self.cx.relate_type_and_user_type(
297 ty::Variance::Invariant,
298 &UserTypeProjection { base: annotation_index, projs: vec![] },
299 location.to_locations(),
300 ConstraintCategory::Boring,
302 let annotation = &self.cx.user_type_annotations[annotation_index];
306 "bad constant user type {:?} vs {:?}: {:?}",
313 if let ty::ConstKind::Unevaluated(def_id, substs) = constant.literal.val {
314 if let Err(terr) = self.cx.fully_perform_op(
315 location.to_locations(),
316 ConstraintCategory::Boring,
317 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
320 UserSubsts { substs, user_self_ty: None },
323 span_mirbug!(self, constant, "bad constant type {:?} ({:?})", constant, terr);
326 if let ty::FnDef(def_id, substs) = constant.literal.ty.kind {
327 let tcx = self.tcx();
329 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
330 self.cx.normalize_and_prove_instantiated_predicates(
331 instantiated_predicates,
332 location.to_locations(),
338 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
339 self.super_rvalue(rvalue, location);
340 let rval_ty = rvalue.ty(self.body, self.tcx());
341 self.sanitize_type(rvalue, rval_ty);
344 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
345 self.super_local_decl(local, local_decl);
346 self.sanitize_type(local_decl, local_decl.ty);
348 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
349 let ty = if !local_decl.is_nonref_binding() {
350 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
351 // reference so we can check the type annotation for the remaining type.
352 if let ty::Ref(_, rty, _) = local_decl.ty.kind {
355 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
361 if let Err(terr) = self.cx.relate_type_and_user_type(
363 ty::Variance::Invariant,
365 Locations::All(*span),
366 ConstraintCategory::TypeAnnotation,
371 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
381 fn visit_body(&mut self, body: ReadOnlyBodyAndCache<'_, 'tcx>) {
382 self.sanitize_type(&"return type", body.return_ty());
383 for local_decl in &body.local_decls {
384 self.sanitize_type(local_decl, local_decl.ty);
386 if self.errors_reported {
389 self.super_body(body);
393 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
395 cx: &'a mut TypeChecker<'b, 'tcx>,
396 body: &'b Body<'tcx>,
397 promoted: &'b IndexVec<Promoted, ReadOnlyBodyAndCache<'b, 'tcx>>,
402 mir_def_id: cx.mir_def_id,
404 last_span: body.span,
405 errors_reported: false,
409 fn tcx(&self) -> TyCtxt<'tcx> {
413 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
414 if ty.has_escaping_bound_vars() || ty.references_error() {
415 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
421 /// Checks that the types internal to the `place` match up with
422 /// what would be expected.
427 context: PlaceContext,
429 debug!("sanitize_place: {:?}", place);
431 let mut place_ty = match &place.base {
432 PlaceBase::Local(index) => PlaceTy::from_ty(self.body.local_decls[*index].ty),
433 PlaceBase::Static(box Static { kind, ty, def_id }) => {
434 let san_ty = self.sanitize_type(place, ty);
436 |verifier: &mut TypeVerifier<'a, 'b, 'tcx>, place: &Place<'tcx>, ty, san_ty| {
437 if let Err(terr) = verifier.cx.eq_types(
440 location.to_locations(),
441 ConstraintCategory::Boring,
446 "bad promoted type ({:?}: {:?}): {:?}",
454 StaticKind::Promoted(promoted, _) => {
455 if !self.errors_reported {
456 let promoted_body_cache = self.promoted[*promoted];
457 self.sanitize_promoted(promoted_body_cache, location);
459 let promoted_ty = promoted_body_cache.return_ty();
460 check_err(self, place, promoted_ty, san_ty);
463 StaticKind::Static => {
464 let ty = self.tcx().type_of(*def_id);
465 let ty = self.cx.normalize(ty, location);
467 check_err(self, place, ty, san_ty);
470 PlaceTy::from_ty(san_ty)
474 if place.projection.is_empty() {
475 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
476 let is_promoted = match place.as_ref() {
478 base: &PlaceBase::Static(box Static { kind: StaticKind::Promoted(..), .. }),
485 let tcx = self.tcx();
486 let trait_ref = ty::TraitRef {
487 def_id: tcx.lang_items().copy_trait().unwrap(),
488 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
491 // To have a `Copy` operand, the type `T` of the
492 // value must be `Copy`. Note that we prove that `T: Copy`,
493 // rather than using the `is_copy_modulo_regions`
494 // test. This is important because
495 // `is_copy_modulo_regions` ignores the resulting region
496 // obligations and assumes they pass. This can result in
497 // bounds from `Copy` impls being unsoundly ignored (e.g.,
498 // #29149). Note that we decide to use `Copy` before knowing
499 // whether the bounds fully apply: in effect, the rule is
500 // that if a value of some type could implement `Copy`, then
502 self.cx.prove_trait_ref(
504 location.to_locations(),
505 ConstraintCategory::CopyBound,
511 for elem in place.projection.iter() {
512 if place_ty.variant_index.is_none() {
513 if place_ty.ty.references_error() {
514 assert!(self.errors_reported);
515 return PlaceTy::from_ty(self.tcx().types.err);
518 place_ty = self.sanitize_projection(place_ty, elem, place, location)
524 fn sanitize_promoted(
526 promoted_body: ReadOnlyBodyAndCache<'b, 'tcx>,
529 // Determine the constraints from the promoted MIR by running the type
530 // checker on the promoted MIR, then transfer the constraints back to
531 // the main MIR, changing the locations to the provided location.
533 let parent_body = mem::replace(&mut self.body, *promoted_body);
535 // Use new sets of constraints and closure bounds so that we can
536 // modify their locations.
537 let all_facts = &mut None;
538 let mut constraints = Default::default();
539 let mut closure_bounds = Default::default();
540 let mut liveness_constraints =
541 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
542 // Don't try to add borrow_region facts for the promoted MIR
544 let mut swap_constraints = |this: &mut Self| {
545 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
547 &mut this.cx.borrowck_context.constraints.outlives_constraints,
551 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
555 &mut this.cx.borrowck_context.constraints.liveness_constraints,
556 &mut liveness_constraints,
560 swap_constraints(self);
562 self.visit_body(promoted_body);
564 if !self.errors_reported {
565 // if verifier failed, don't do further checks to avoid ICEs
566 self.cx.typeck_mir(promoted_body);
569 self.body = parent_body;
570 // Merge the outlives constraints back in, at the given location.
571 swap_constraints(self);
573 let locations = location.to_locations();
574 for constraint in constraints.outlives().iter() {
575 let mut constraint = *constraint;
576 constraint.locations = locations;
577 if let ConstraintCategory::Return
578 | ConstraintCategory::UseAsConst
579 | ConstraintCategory::UseAsStatic = constraint.category
581 // "Returning" from a promoted is an assigment to a
582 // temporary from the user's point of view.
583 constraint.category = ConstraintCategory::Boring;
585 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
587 for live_region in liveness_constraints.rows() {
591 .liveness_constraints
592 .add_element(live_region, location);
595 if !closure_bounds.is_empty() {
596 let combined_bounds_mapping =
597 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
602 .closure_bounds_mapping
603 .insert(location, combined_bounds_mapping);
604 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
608 fn sanitize_projection(
611 pi: &PlaceElem<'tcx>,
615 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
616 let tcx = self.tcx();
617 let base_ty = base.ty;
619 ProjectionElem::Deref => {
620 let deref_ty = base_ty.builtin_deref(true);
621 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
622 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
625 ProjectionElem::Index(i) => {
626 let index_ty = Place::from(i).ty(self.body, tcx).ty;
627 if index_ty != tcx.types.usize {
628 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
630 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
631 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
635 ProjectionElem::ConstantIndex { .. } => {
636 // consider verifying in-bounds
637 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
638 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
641 ProjectionElem::Subslice { from, to, from_end } => {
642 PlaceTy::from_ty(match base_ty.kind {
643 ty::Array(inner, _) => {
644 assert!(!from_end, "array subslices should not use from_end");
645 tcx.mk_array(inner, (to - from) as u64)
648 assert!(from_end, "slice subslices should use from_end");
651 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
654 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind {
655 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
656 if index.as_usize() >= adt_def.variants.len() {
657 PlaceTy::from_ty(span_mirbug_and_err!(
660 "cast to variant #{:?} but enum only has {:?}",
662 adt_def.variants.len()
665 PlaceTy { ty: base_ty, variant_index: Some(index) }
668 // We do not need to handle generators here, because this runs
669 // before the generator transform stage.
671 let ty = if let Some(name) = maybe_name {
672 span_mirbug_and_err!(
675 "can't downcast {:?} as {:?}",
680 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
685 ProjectionElem::Field(field, fty) => {
686 let fty = self.sanitize_type(place, fty);
687 match self.field_ty(place, base, field, location) {
689 if let Err(terr) = self.cx.eq_types(
692 location.to_locations(),
693 ConstraintCategory::Boring,
698 "bad field access ({:?}: {:?}): {:?}",
705 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
708 "accessed field #{} but variant only has {}",
713 PlaceTy::from_ty(fty)
718 fn error(&mut self) -> Ty<'tcx> {
719 self.errors_reported = true;
725 parent: &dyn fmt::Debug,
726 base_ty: PlaceTy<'tcx>,
729 ) -> Result<Ty<'tcx>, FieldAccessError> {
730 let tcx = self.tcx();
732 let (variant, substs) = match base_ty {
733 PlaceTy { ty, variant_index: Some(variant_index) } => match ty.kind {
734 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
735 ty::Generator(def_id, substs, _) => {
736 let mut variants = substs.as_generator().state_tys(def_id, tcx);
737 let mut variant = match variants.nth(variant_index.into()) {
740 "variant_index of generator out of range: {:?}/{:?}",
742 substs.as_generator().state_tys(def_id, tcx).count()
745 return match variant.nth(field.index()) {
747 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
750 _ => bug!("can't have downcast of non-adt non-generator type"),
752 PlaceTy { ty, variant_index: None } => match ty.kind {
753 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
754 (&adt_def.variants[VariantIdx::new(0)], substs)
756 ty::Closure(def_id, substs) => {
757 return match substs.as_closure().upvar_tys(def_id, tcx).nth(field.index()) {
759 None => Err(FieldAccessError::OutOfRange {
760 field_count: substs.as_closure().upvar_tys(def_id, tcx).count(),
764 ty::Generator(def_id, substs, _) => {
765 // Only prefix fields (upvars and current state) are
766 // accessible without a variant index.
767 return match substs.as_generator().prefix_tys(def_id, tcx).nth(field.index()) {
769 None => Err(FieldAccessError::OutOfRange {
770 field_count: substs.as_generator().prefix_tys(def_id, tcx).count(),
775 return match tys.get(field.index()) {
776 Some(&ty) => Ok(ty.expect_ty()),
777 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
781 return Ok(span_mirbug_and_err!(
784 "can't project out of {:?}",
791 if let Some(field) = variant.fields.get(field.index()) {
792 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
794 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
799 /// The MIR type checker. Visits the MIR and enforces all the
800 /// constraints needed for it to be valid and well-typed. Along the
801 /// way, it accrues region constraints -- these can later be used by
802 /// NLL region checking.
803 struct TypeChecker<'a, 'tcx> {
804 infcx: &'a InferCtxt<'a, 'tcx>,
805 param_env: ty::ParamEnv<'tcx>,
807 body: &'a Body<'tcx>,
808 /// User type annotations are shared between the main MIR and the MIR of
809 /// all of the promoted items.
810 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
812 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
813 implicit_region_bound: ty::Region<'tcx>,
814 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
815 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
816 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
819 struct BorrowCheckContext<'a, 'tcx> {
820 universal_regions: &'a UniversalRegions<'tcx>,
821 location_table: &'a LocationTable,
822 all_facts: &'a mut Option<AllFacts>,
823 borrow_set: &'a BorrowSet<'tcx>,
824 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
827 crate struct MirTypeckResults<'tcx> {
828 crate constraints: MirTypeckRegionConstraints<'tcx>,
829 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
832 /// A collection of region constraints that must be satisfied for the
833 /// program to be considered well-typed.
834 crate struct MirTypeckRegionConstraints<'tcx> {
835 /// Maps from a `ty::Placeholder` to the corresponding
836 /// `PlaceholderIndex` bit that we will use for it.
838 /// To keep everything in sync, do not insert this set
839 /// directly. Instead, use the `placeholder_region` helper.
840 crate placeholder_indices: PlaceholderIndices,
842 /// Each time we add a placeholder to `placeholder_indices`, we
843 /// also create a corresponding "representative" region vid for
844 /// that wraps it. This vector tracks those. This way, when we
845 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
846 /// the same underlying `RegionVid`.
847 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
849 /// In general, the type-checker is not responsible for enforcing
850 /// liveness constraints; this job falls to the region inferencer,
851 /// which performs a liveness analysis. However, in some limited
852 /// cases, the MIR type-checker creates temporary regions that do
853 /// not otherwise appear in the MIR -- in particular, the
854 /// late-bound regions that it instantiates at call-sites -- and
855 /// hence it must report on their liveness constraints.
856 crate liveness_constraints: LivenessValues<RegionVid>,
858 crate outlives_constraints: OutlivesConstraintSet,
860 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
862 crate closure_bounds_mapping:
863 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
865 crate type_tests: Vec<TypeTest<'tcx>>,
868 impl MirTypeckRegionConstraints<'tcx> {
869 fn placeholder_region(
871 infcx: &InferCtxt<'_, 'tcx>,
872 placeholder: ty::PlaceholderRegion,
873 ) -> ty::Region<'tcx> {
874 let placeholder_index = self.placeholder_indices.insert(placeholder);
875 match self.placeholder_index_to_region.get(placeholder_index) {
878 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
879 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
880 self.placeholder_index_to_region.push(region);
887 /// The `Locations` type summarizes *where* region constraints are
888 /// required to hold. Normally, this is at a particular point which
889 /// created the obligation, but for constraints that the user gave, we
890 /// want the constraint to hold at all points.
891 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
893 /// Indicates that a type constraint should always be true. This
894 /// is particularly important in the new borrowck analysis for
895 /// things like the type of the return slot. Consider this
899 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
901 /// return &y; // error
905 /// Here, we wind up with the signature from the return type being
906 /// something like `&'1 u32` where `'1` is a universal region. But
907 /// the type of the return slot `_0` is something like `&'2 u32`
908 /// where `'2` is an existential region variable. The type checker
909 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
910 /// older NLL analysis, we required this only at the entry point
911 /// to the function. By the nature of the constraints, this wound
912 /// up propagating to all points reachable from start (because
913 /// `'1` -- as a universal region -- is live everywhere). In the
914 /// newer analysis, though, this doesn't work: `_0` is considered
915 /// dead at the start (it has no usable value) and hence this type
916 /// equality is basically a no-op. Then, later on, when we do `_0
917 /// = &'3 y`, that region `'3` never winds up related to the
918 /// universal region `'1` and hence no error occurs. Therefore, we
919 /// use Locations::All instead, which ensures that the `'1` and
920 /// `'2` are equal everything. We also use this for other
921 /// user-given type annotations; e.g., if the user wrote `let mut
922 /// x: &'static u32 = ...`, we would ensure that all values
923 /// assigned to `x` are of `'static` lifetime.
925 /// The span points to the place the constraint arose. For example,
926 /// it points to the type in a user-given type annotation. If
927 /// there's no sensible span then it's DUMMY_SP.
930 /// An outlives constraint that only has to hold at a single location,
931 /// usually it represents a point where references flow from one spot to
932 /// another (e.g., `x = y`)
937 pub fn from_location(&self) -> Option<Location> {
939 Locations::All(_) => None,
940 Locations::Single(from_location) => Some(*from_location),
944 /// Gets a span representing the location.
945 pub fn span(&self, body: &Body<'_>) -> Span {
947 Locations::All(span) => *span,
948 Locations::Single(l) => body.source_info(*l).span,
953 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
955 infcx: &'a InferCtxt<'a, 'tcx>,
956 body: &'a Body<'tcx>,
958 param_env: ty::ParamEnv<'tcx>,
959 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
960 implicit_region_bound: ty::Region<'tcx>,
961 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
962 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
964 let mut checker = Self {
969 user_type_annotations: &body.user_type_annotations,
972 implicit_region_bound,
974 reported_errors: Default::default(),
975 universal_region_relations,
977 checker.check_user_type_annotations();
981 /// Equate the inferred type and the annotated type for user type annotations
982 fn check_user_type_annotations(&mut self) {
984 "check_user_type_annotations: user_type_annotations={:?}",
985 self.user_type_annotations
987 for user_annotation in self.user_type_annotations {
988 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
989 let (annotation, _) =
990 self.infcx.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
992 UserType::Ty(mut ty) => {
993 ty = self.normalize(ty, Locations::All(span));
995 if let Err(terr) = self.eq_types(
998 Locations::All(span),
999 ConstraintCategory::BoringNoLocation,
1004 "bad user type ({:?} = {:?}): {:?}",
1011 self.prove_predicate(
1012 ty::Predicate::WellFormed(inferred_ty),
1013 Locations::All(span),
1014 ConstraintCategory::TypeAnnotation,
1017 UserType::TypeOf(def_id, user_substs) => {
1018 if let Err(terr) = self.fully_perform_op(
1019 Locations::All(span),
1020 ConstraintCategory::BoringNoLocation,
1021 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1030 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1042 /// Given some operation `op` that manipulates types, proves
1043 /// predicates, or otherwise uses the inference context, executes
1044 /// `op` and then executes all the further obligations that `op`
1045 /// returns. This will yield a set of outlives constraints amongst
1046 /// regions which are extracted and stored as having occurred at
1049 /// **Any `rustc::infer` operations that might generate region
1050 /// constraints should occur within this method so that those
1051 /// constraints can be properly localized!**
1052 fn fully_perform_op<R>(
1054 locations: Locations,
1055 category: ConstraintCategory,
1056 op: impl type_op::TypeOp<'tcx, Output = R>,
1058 let (r, opt_data) = op.fully_perform(self.infcx)?;
1060 if let Some(data) = &opt_data {
1061 self.push_region_constraints(locations, category, data);
1067 fn push_region_constraints(
1069 locations: Locations,
1070 category: ConstraintCategory,
1071 data: &QueryRegionConstraints<'tcx>,
1073 debug!("push_region_constraints: constraints generated at {:?} are {:#?}", locations, data);
1075 constraint_conversion::ConstraintConversion::new(
1077 self.borrowck_context.universal_regions,
1078 self.region_bound_pairs,
1079 Some(self.implicit_region_bound),
1083 &mut self.borrowck_context.constraints,
1088 /// Convenient wrapper around `relate_tys::relate_types` -- see
1089 /// that fn for docs.
1095 locations: Locations,
1096 category: ConstraintCategory,
1098 relate_tys::relate_types(
1105 Some(self.borrowck_context),
1113 locations: Locations,
1114 category: ConstraintCategory,
1116 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1119 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1120 /// variables in `sub` with their inferred definitions and try
1121 /// again. This is used for opaque types in places (e.g., `let x:
1122 /// impl Foo = ..`).
1123 fn sub_types_or_anon(
1127 locations: Locations,
1128 category: ConstraintCategory,
1130 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1131 if let ty::Opaque(..) = sup.kind {
1132 // When you have `let x: impl Foo = ...` in a closure,
1133 // the resulting inferend values are stored with the
1134 // def-id of the base function.
1135 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1136 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1148 locations: Locations,
1149 category: ConstraintCategory,
1151 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1154 fn relate_type_and_user_type(
1158 user_ty: &UserTypeProjection,
1159 locations: Locations,
1160 category: ConstraintCategory,
1163 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1164 a, v, user_ty, locations,
1167 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1168 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1170 let tcx = self.infcx.tcx;
1172 for proj in &user_ty.projs {
1173 let projected_ty = curr_projected_ty.projection_ty_core(
1177 |this, field, &()| {
1178 let ty = this.field_ty(tcx, field);
1179 self.normalize(ty, locations)
1182 curr_projected_ty = projected_ty;
1185 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1186 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1189 let ty = curr_projected_ty.ty;
1190 self.relate_types(a, v, ty, locations, category)?;
1195 fn eq_opaque_type_and_type(
1197 revealed_ty: Ty<'tcx>,
1199 anon_owner_def_id: DefId,
1200 locations: Locations,
1201 category: ConstraintCategory,
1204 "eq_opaque_type_and_type( \
1207 revealed_ty, anon_ty
1209 let infcx = self.infcx;
1210 let tcx = infcx.tcx;
1211 let param_env = self.param_env;
1212 let body = self.body;
1213 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1214 let opaque_type_map = self.fully_perform_op(
1219 let mut obligations = ObligationAccumulator::default();
1221 let dummy_body_id = ObligationCause::dummy().body_id;
1222 let (output_ty, opaque_type_map) =
1223 obligations.add(infcx.instantiate_opaque_types(
1228 locations.span(body),
1231 "eq_opaque_type_and_type: \
1232 instantiated output_ty={:?} \
1233 opaque_type_map={:#?} \
1235 output_ty, opaque_type_map, revealed_ty
1239 .at(&ObligationCause::dummy(), param_env)
1240 .eq(output_ty, revealed_ty)?,
1243 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1244 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1245 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1246 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1247 let concrete_is_opaque = infcx
1248 .resolve_vars_if_possible(&opaque_decl.concrete_ty)
1252 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?} \
1253 concrete_is_opaque={}",
1254 opaque_decl.concrete_ty,
1255 infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty),
1260 // concrete_is_opaque is `true` when we're using an opaque `impl Trait`
1261 // type without 'revealing' it. For example, code like this:
1263 // type Foo = impl Debug;
1264 // fn foo1() -> Foo { ... }
1265 // fn foo2() -> Foo { foo1() }
1267 // In `foo2`, we're not revealing the type of `Foo` - we're
1268 // just treating it as the opaque type.
1270 // When this occurs, we do *not* want to try to equate
1271 // the concrete type with the underlying defining type
1272 // of the opaque type - this will always fail, since
1273 // the defining type of an opaque type is always
1274 // some other type (e.g. not itself)
1275 // Essentially, none of the normal obligations apply here -
1276 // we're just passing around some unknown opaque type,
1277 // without actually looking at the underlying type it
1278 // gets 'revealed' into
1280 if !concrete_is_opaque {
1283 .at(&ObligationCause::dummy(), param_env)
1284 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?,
1289 debug!("eq_opaque_type_and_type: equated");
1292 value: Some(opaque_type_map),
1293 obligations: obligations.into_vec(),
1296 || "input_output".to_string(),
1300 let universal_region_relations = self.universal_region_relations;
1302 // Finally, if we instantiated the anon types successfully, we
1303 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1304 // prove that `T: Iterator` where `T` is the type we
1305 // instantiated it with).
1306 if let Some(opaque_type_map) = opaque_type_map {
1307 for (opaque_def_id, opaque_decl) in opaque_type_map {
1308 self.fully_perform_op(
1310 ConstraintCategory::OpaqueType,
1313 infcx.constrain_opaque_type(
1316 universal_region_relations,
1318 Ok(InferOk { value: (), obligations: vec![] })
1320 || "opaque_type_map".to_string(),
1328 fn tcx(&self) -> TyCtxt<'tcx> {
1334 body: ReadOnlyBodyAndCache<'_, 'tcx>,
1335 stmt: &Statement<'tcx>,
1338 debug!("check_stmt: {:?}", stmt);
1339 let tcx = self.tcx();
1341 StatementKind::Assign(box (ref place, ref rv)) => {
1342 // Assignments to temporaries are not "interesting";
1343 // they are not caused by the user, but rather artifacts
1344 // of lowering. Assignments to other sorts of places *are* interesting
1346 let category = match place.as_local() {
1347 Some(RETURN_PLACE) => {
1348 if let BorrowCheckContext {
1350 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1352 } = self.borrowck_context
1354 if tcx.is_static(*def_id) {
1355 ConstraintCategory::UseAsStatic
1357 ConstraintCategory::UseAsConst
1360 ConstraintCategory::Return
1363 Some(l) if !body.local_decls[l].is_user_variable() => {
1364 ConstraintCategory::Boring
1366 _ => ConstraintCategory::Assignment,
1369 let place_ty = place.ty(*body, tcx).ty;
1370 let place_ty = self.normalize(place_ty, location);
1371 let rv_ty = rv.ty(*body, tcx);
1372 let rv_ty = self.normalize(rv_ty, location);
1374 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1379 "bad assignment ({:?} = {:?}): {:?}",
1386 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1387 if let Err(terr) = self.relate_type_and_user_type(
1389 ty::Variance::Invariant,
1390 &UserTypeProjection { base: annotation_index, projs: vec![] },
1391 location.to_locations(),
1392 ConstraintCategory::Boring,
1394 let annotation = &self.user_type_annotations[annotation_index];
1398 "bad user type on rvalue ({:?} = {:?}): {:?}",
1406 self.check_rvalue(body, rv, location);
1407 if !self.tcx().features().unsized_locals {
1408 let trait_ref = ty::TraitRef {
1409 def_id: tcx.lang_items().sized_trait().unwrap(),
1410 substs: tcx.mk_substs_trait(place_ty, &[]),
1412 self.prove_trait_ref(
1414 location.to_locations(),
1415 ConstraintCategory::SizedBound,
1419 StatementKind::SetDiscriminant { ref place, variant_index } => {
1420 let place_type = place.ty(*body, tcx).ty;
1421 let adt = match place_type.kind {
1422 ty::Adt(adt, _) if adt.is_enum() => adt,
1425 stmt.source_info.span,
1426 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1432 if variant_index.as_usize() >= adt.variants.len() {
1434 stmt.source_info.span,
1435 "bad set discriminant ({:?} = {:?}): value of of range",
1441 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1442 let place_ty = place.ty(*body, tcx).ty;
1443 if let Err(terr) = self.relate_type_and_user_type(
1447 Locations::All(stmt.source_info.span),
1448 ConstraintCategory::TypeAnnotation,
1450 let annotation = &self.user_type_annotations[projection.base];
1454 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1462 StatementKind::FakeRead(..)
1463 | StatementKind::StorageLive(..)
1464 | StatementKind::StorageDead(..)
1465 | StatementKind::InlineAsm { .. }
1466 | StatementKind::Retag { .. }
1467 | StatementKind::Nop => {}
1471 fn check_terminator(
1474 term: &Terminator<'tcx>,
1475 term_location: Location,
1477 debug!("check_terminator: {:?}", term);
1478 let tcx = self.tcx();
1480 TerminatorKind::Goto { .. }
1481 | TerminatorKind::Resume
1482 | TerminatorKind::Abort
1483 | TerminatorKind::Return
1484 | TerminatorKind::GeneratorDrop
1485 | TerminatorKind::Unreachable
1486 | TerminatorKind::Drop { .. }
1487 | TerminatorKind::FalseEdges { .. }
1488 | TerminatorKind::FalseUnwind { .. } => {
1489 // no checks needed for these
1492 TerminatorKind::DropAndReplace { ref location, ref value, target: _, unwind: _ } => {
1493 let place_ty = location.ty(body, tcx).ty;
1494 let rv_ty = value.ty(body, tcx);
1496 let locations = term_location.to_locations();
1498 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1503 "bad DropAndReplace ({:?} = {:?}): {:?}",
1510 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1511 let discr_ty = discr.ty(body, tcx);
1512 if let Err(terr) = self.sub_types(
1515 term_location.to_locations(),
1516 ConstraintCategory::Assignment,
1521 "bad SwitchInt ({:?} on {:?}): {:?}",
1527 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1528 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1530 // FIXME: check the values
1532 TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1533 let func_ty = func.ty(body, tcx);
1534 debug!("check_terminator: call, func_ty={:?}", func_ty);
1535 let sig = match func_ty.kind {
1536 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1538 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1542 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1543 term.source_info.span,
1544 LateBoundRegionConversionTime::FnCall,
1547 let sig = self.normalize(sig, term_location);
1548 self.check_call_dest(body, term, &sig, destination, term_location);
1550 self.prove_predicates(
1551 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1552 term_location.to_locations(),
1553 ConstraintCategory::Boring,
1556 // The ordinary liveness rules will ensure that all
1557 // regions in the type of the callee are live here. We
1558 // then further constrain the late-bound regions that
1559 // were instantiated at the call site to be live as
1560 // well. The resulting is that all the input (and
1561 // output) types in the signature must be live, since
1562 // all the inputs that fed into it were live.
1563 for &late_bound_region in map.values() {
1565 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1566 self.borrowck_context
1568 .liveness_constraints
1569 .add_element(region_vid, term_location);
1572 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1574 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1575 let cond_ty = cond.ty(body, tcx);
1576 if cond_ty != tcx.types.bool {
1577 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1580 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
1581 if len.ty(body, tcx) != tcx.types.usize {
1582 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1584 if index.ty(body, tcx) != tcx.types.usize {
1585 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1589 TerminatorKind::Yield { ref value, .. } => {
1590 let value_ty = value.ty(body, tcx);
1591 match body.yield_ty {
1592 None => span_mirbug!(self, term, "yield in non-generator"),
1594 if let Err(terr) = self.sub_types(
1597 term_location.to_locations(),
1598 ConstraintCategory::Yield,
1603 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1618 term: &Terminator<'tcx>,
1619 sig: &ty::FnSig<'tcx>,
1620 destination: &Option<(Place<'tcx>, BasicBlock)>,
1621 term_location: Location,
1623 let tcx = self.tcx();
1624 match *destination {
1625 Some((ref dest, _target_block)) => {
1626 let dest_ty = dest.ty(body, tcx).ty;
1627 let dest_ty = self.normalize(dest_ty, term_location);
1628 let category = match dest.as_local() {
1629 Some(RETURN_PLACE) => {
1630 if let BorrowCheckContext {
1632 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1634 } = self.borrowck_context
1636 if tcx.is_static(*def_id) {
1637 ConstraintCategory::UseAsStatic
1639 ConstraintCategory::UseAsConst
1642 ConstraintCategory::Return
1645 Some(l) if !body.local_decls[l].is_user_variable() => {
1646 ConstraintCategory::Boring
1648 _ => ConstraintCategory::Assignment,
1651 let locations = term_location.to_locations();
1654 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1659 "call dest mismatch ({:?} <- {:?}): {:?}",
1666 // When `#![feature(unsized_locals)]` is not enabled,
1667 // this check is done at `check_local`.
1668 if self.tcx().features().unsized_locals {
1669 let span = term.source_info.span;
1670 self.ensure_place_sized(dest_ty, span);
1674 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1675 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1681 fn check_call_inputs(
1684 term: &Terminator<'tcx>,
1685 sig: &ty::FnSig<'tcx>,
1686 args: &[Operand<'tcx>],
1687 term_location: Location,
1688 from_hir_call: bool,
1690 debug!("check_call_inputs({:?}, {:?})", sig, args);
1691 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1692 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1694 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1695 let op_arg_ty = op_arg.ty(body, self.tcx());
1696 let category = if from_hir_call {
1697 ConstraintCategory::CallArgument
1699 ConstraintCategory::Boring
1702 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1707 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1717 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1718 let is_cleanup = block_data.is_cleanup;
1719 self.last_span = block_data.terminator().source_info.span;
1720 match block_data.terminator().kind {
1721 TerminatorKind::Goto { target } => {
1722 self.assert_iscleanup(body, block_data, target, is_cleanup)
1724 TerminatorKind::SwitchInt { ref targets, .. } => {
1725 for target in targets {
1726 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1729 TerminatorKind::Resume => {
1731 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1734 TerminatorKind::Abort => {
1736 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1739 TerminatorKind::Return => {
1741 span_mirbug!(self, block_data, "return on cleanup block")
1744 TerminatorKind::GeneratorDrop { .. } => {
1746 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1749 TerminatorKind::Yield { resume, drop, .. } => {
1751 span_mirbug!(self, block_data, "yield in cleanup block")
1753 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1754 if let Some(drop) = drop {
1755 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1758 TerminatorKind::Unreachable => {}
1759 TerminatorKind::Drop { target, unwind, .. }
1760 | TerminatorKind::DropAndReplace { target, unwind, .. }
1761 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1762 self.assert_iscleanup(body, block_data, target, is_cleanup);
1763 if let Some(unwind) = unwind {
1765 span_mirbug!(self, block_data, "unwind on cleanup block")
1767 self.assert_iscleanup(body, block_data, unwind, true);
1770 TerminatorKind::Call { ref destination, cleanup, .. } => {
1771 if let &Some((_, target)) = destination {
1772 self.assert_iscleanup(body, block_data, target, is_cleanup);
1774 if let Some(cleanup) = cleanup {
1776 span_mirbug!(self, block_data, "cleanup on cleanup block")
1778 self.assert_iscleanup(body, block_data, cleanup, true);
1781 TerminatorKind::FalseEdges { real_target, imaginary_target } => {
1782 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1783 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1785 TerminatorKind::FalseUnwind { real_target, unwind } => {
1786 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1787 if let Some(unwind) = unwind {
1789 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1791 self.assert_iscleanup(body, block_data, unwind, true);
1797 fn assert_iscleanup(
1800 ctxt: &dyn fmt::Debug,
1804 if body[bb].is_cleanup != iscleanuppad {
1805 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1809 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1810 match body.local_kind(local) {
1811 LocalKind::ReturnPointer | LocalKind::Arg => {
1812 // return values of normal functions are required to be
1813 // sized by typeck, but return values of ADT constructors are
1814 // not because we don't include a `Self: Sized` bounds on them.
1816 // Unbound parts of arguments were never required to be Sized
1817 // - maybe we should make that a warning.
1820 LocalKind::Var | LocalKind::Temp => {}
1823 // When `#![feature(unsized_locals)]` is enabled, only function calls
1824 // and nullary ops are checked in `check_call_dest`.
1825 if !self.tcx().features().unsized_locals {
1826 let span = local_decl.source_info.span;
1827 let ty = local_decl.ty;
1828 self.ensure_place_sized(ty, span);
1832 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1833 let tcx = self.tcx();
1835 // Erase the regions from `ty` to get a global type. The
1836 // `Sized` bound in no way depends on precise regions, so this
1837 // shouldn't affect `is_sized`.
1838 let erased_ty = tcx.erase_regions(&ty);
1839 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1840 // in current MIR construction, all non-control-flow rvalue
1841 // expressions evaluate through `as_temp` or `into` a return
1842 // slot or local, so to find all unsized rvalues it is enough
1843 // to check all temps, return slots and locals.
1844 if let None = self.reported_errors.replace((ty, span)) {
1845 let mut diag = struct_span_err!(
1849 "cannot move a value of type {0}: the size of {0} \
1850 cannot be statically determined",
1854 // While this is located in `nll::typeck` this error is not
1855 // an NLL error, it's a required check to prevent creation
1856 // of unsized rvalues in certain cases:
1857 // * operand of a box expression
1858 // * callee in a call expression
1864 fn aggregate_field_ty(
1866 ak: &AggregateKind<'tcx>,
1869 ) -> Result<Ty<'tcx>, FieldAccessError> {
1870 let tcx = self.tcx();
1873 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1874 let variant = &def.variants[variant_index];
1875 let adj_field_index = active_field_index.unwrap_or(field_index);
1876 if let Some(field) = variant.fields.get(adj_field_index) {
1877 Ok(self.normalize(field.ty(tcx, substs), location))
1879 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1882 AggregateKind::Closure(def_id, substs) => {
1883 match substs.as_closure().upvar_tys(def_id, tcx).nth(field_index) {
1885 None => Err(FieldAccessError::OutOfRange {
1886 field_count: substs.as_closure().upvar_tys(def_id, tcx).count(),
1890 AggregateKind::Generator(def_id, substs, _) => {
1891 // It doesn't make sense to look at a field beyond the prefix;
1892 // these require a variant index, and are not initialized in
1893 // aggregate rvalues.
1894 match substs.as_generator().prefix_tys(def_id, tcx).nth(field_index) {
1896 None => Err(FieldAccessError::OutOfRange {
1897 field_count: substs.as_generator().prefix_tys(def_id, tcx).count(),
1901 AggregateKind::Array(ty) => Ok(ty),
1902 AggregateKind::Tuple => {
1903 unreachable!("This should have been covered in check_rvalues");
1910 body: ReadOnlyBodyAndCache<'_, 'tcx>,
1911 rvalue: &Rvalue<'tcx>,
1914 let tcx = self.tcx();
1917 Rvalue::Aggregate(ak, ops) => {
1918 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1921 Rvalue::Repeat(operand, len) => {
1923 if let Operand::Move(_) = operand {
1924 // While this is located in `nll::typeck` this error is not an NLL error, it's
1925 // a required check to make sure that repeated elements implement `Copy`.
1926 let span = body.source_info(location).span;
1927 let ty = operand.ty(*body, tcx);
1928 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1929 // To determine if `const_in_array_repeat_expressions` feature gate should
1930 // be mentioned, need to check if the rvalue is promotable.
1931 let should_suggest =
1932 should_suggest_const_in_array_repeat_expressions_attribute(
1938 debug!("check_rvalue: should_suggest={:?}", should_suggest);
1940 self.infcx.report_selection_error(
1941 &traits::Obligation::new(
1942 ObligationCause::new(
1944 self.tcx().hir().def_index_to_hir_id(self.mir_def_id.index),
1945 traits::ObligationCauseCode::RepeatVec(should_suggest),
1948 ty::Predicate::Trait(ty::Binder::bind(ty::TraitPredicate {
1949 trait_ref: ty::TraitRef::new(
1950 self.tcx().lang_items().copy_trait().unwrap(),
1951 tcx.mk_substs_trait(ty, &[]),
1955 &traits::SelectionError::Unimplemented,
1964 Rvalue::NullaryOp(_, ty) => {
1965 // Even with unsized locals cannot box an unsized value.
1966 if self.tcx().features().unsized_locals {
1967 let span = body.source_info(location).span;
1968 self.ensure_place_sized(ty, span);
1971 let trait_ref = ty::TraitRef {
1972 def_id: tcx.lang_items().sized_trait().unwrap(),
1973 substs: tcx.mk_substs_trait(ty, &[]),
1976 self.prove_trait_ref(
1978 location.to_locations(),
1979 ConstraintCategory::SizedBound,
1983 Rvalue::Cast(cast_kind, op, ty) => {
1985 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1986 let fn_sig = op.ty(*body, tcx).fn_sig(tcx);
1988 // The type that we see in the fcx is like
1989 // `foo::<'a, 'b>`, where `foo` is the path to a
1990 // function definition. When we extract the
1991 // signature, it comes from the `fn_sig` query,
1992 // and hence may contain unnormalized results.
1993 let fn_sig = self.normalize(fn_sig, location);
1995 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1997 if let Err(terr) = self.eq_types(
2000 location.to_locations(),
2001 ConstraintCategory::Cast,
2006 "equating {:?} with {:?} yields {:?}",
2014 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2015 let sig = match op.ty(*body, tcx).kind {
2016 ty::Closure(def_id, substs) => {
2017 substs.as_closure().sig_ty(def_id, tcx).fn_sig(tcx)
2021 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2023 if let Err(terr) = self.eq_types(
2026 location.to_locations(),
2027 ConstraintCategory::Cast,
2032 "equating {:?} with {:?} yields {:?}",
2040 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2041 let fn_sig = op.ty(*body, tcx).fn_sig(tcx);
2043 // The type that we see in the fcx is like
2044 // `foo::<'a, 'b>`, where `foo` is the path to a
2045 // function definition. When we extract the
2046 // signature, it comes from the `fn_sig` query,
2047 // and hence may contain unnormalized results.
2048 let fn_sig = self.normalize(fn_sig, location);
2050 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2052 if let Err(terr) = self.eq_types(
2055 location.to_locations(),
2056 ConstraintCategory::Cast,
2061 "equating {:?} with {:?} yields {:?}",
2069 CastKind::Pointer(PointerCast::Unsize) => {
2071 let trait_ref = ty::TraitRef {
2072 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2073 substs: tcx.mk_substs_trait(op.ty(*body, tcx), &[ty.into()]),
2076 self.prove_trait_ref(
2078 location.to_locations(),
2079 ConstraintCategory::Cast,
2083 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2084 let ty_from = match op.ty(*body, tcx).kind {
2085 ty::RawPtr(ty::TypeAndMut {
2087 mutbl: hir::Mutability::Mut,
2093 "unexpected base type for cast {:?}",
2099 let ty_to = match ty.kind {
2100 ty::RawPtr(ty::TypeAndMut {
2102 mutbl: hir::Mutability::Not,
2108 "unexpected target type for cast {:?}",
2114 if let Err(terr) = self.sub_types(
2117 location.to_locations(),
2118 ConstraintCategory::Cast,
2123 "relating {:?} with {:?} yields {:?}",
2131 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2132 let ty_from = op.ty(*body, tcx);
2134 let opt_ty_elem = match ty_from.kind {
2135 ty::RawPtr(ty::TypeAndMut {
2136 mutbl: hir::Mutability::Not,
2138 }) => match array_ty.kind {
2139 ty::Array(ty_elem, _) => Some(ty_elem),
2145 let ty_elem = match opt_ty_elem {
2146 Some(ty_elem) => ty_elem,
2151 "ArrayToPointer cast from unexpected type {:?}",
2158 let ty_to = match ty.kind {
2159 ty::RawPtr(ty::TypeAndMut {
2160 mutbl: hir::Mutability::Not,
2167 "ArrayToPointer cast to unexpected type {:?}",
2174 if let Err(terr) = self.sub_types(
2177 location.to_locations(),
2178 ConstraintCategory::Cast,
2183 "relating {:?} with {:?} yields {:?}",
2192 let ty_from = op.ty(*body, tcx);
2193 let cast_ty_from = CastTy::from_ty(ty_from);
2194 let cast_ty_to = CastTy::from_ty(ty);
2195 match (cast_ty_from, cast_ty_to) {
2198 | (_, Some(CastTy::FnPtr))
2199 | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2200 | (Some(CastTy::Ptr(_)), Some(CastTy::Float))
2201 | (Some(CastTy::FnPtr), Some(CastTy::Float)) => {
2202 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2204 (Some(CastTy::Int(_)), Some(CastTy::Int(_)))
2205 | (Some(CastTy::Float), Some(CastTy::Int(_)))
2206 | (Some(CastTy::Int(_)), Some(CastTy::Float))
2207 | (Some(CastTy::Float), Some(CastTy::Float))
2208 | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_)))
2209 | (Some(CastTy::FnPtr), Some(CastTy::Int(_)))
2210 | (Some(CastTy::Int(_)), Some(CastTy::Ptr(_)))
2211 | (Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_)))
2212 | (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
2218 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2219 self.add_reborrow_constraint(&body, location, region, borrowed_place);
2222 Rvalue::BinaryOp(BinOp::Eq, left, right)
2223 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2224 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2225 | Rvalue::BinaryOp(BinOp::Le, left, right)
2226 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2227 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2228 let ty_left = left.ty(*body, tcx);
2229 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.kind {
2230 let ty_right = right.ty(*body, tcx);
2231 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2232 kind: TypeVariableOriginKind::MiscVariable,
2233 span: body.source_info(location).span,
2238 location.to_locations(),
2239 ConstraintCategory::Boring,
2241 .unwrap_or_else(|err| {
2242 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2244 if let Err(terr) = self.sub_types(
2247 location.to_locations(),
2248 ConstraintCategory::Boring,
2253 "unexpected comparison types {:?} and {:?} yields {:?}",
2262 Rvalue::AddressOf(..)
2265 | Rvalue::BinaryOp(..)
2266 | Rvalue::CheckedBinaryOp(..)
2267 | Rvalue::UnaryOp(..)
2268 | Rvalue::Discriminant(..) => {}
2272 /// If this rvalue supports a user-given type annotation, then
2273 /// extract and return it. This represents the final type of the
2274 /// rvalue and will be unified with the inferred type.
2275 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2278 | Rvalue::Repeat(..)
2280 | Rvalue::AddressOf(..)
2283 | Rvalue::BinaryOp(..)
2284 | Rvalue::CheckedBinaryOp(..)
2285 | Rvalue::NullaryOp(..)
2286 | Rvalue::UnaryOp(..)
2287 | Rvalue::Discriminant(..) => None,
2289 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2290 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2291 AggregateKind::Array(_) => None,
2292 AggregateKind::Tuple => None,
2293 AggregateKind::Closure(_, _) => None,
2294 AggregateKind::Generator(_, _, _) => None,
2299 fn check_aggregate_rvalue(
2302 rvalue: &Rvalue<'tcx>,
2303 aggregate_kind: &AggregateKind<'tcx>,
2304 operands: &[Operand<'tcx>],
2307 let tcx = self.tcx();
2309 self.prove_aggregate_predicates(aggregate_kind, location);
2311 if *aggregate_kind == AggregateKind::Tuple {
2312 // tuple rvalue field type is always the type of the op. Nothing to check here.
2316 for (i, operand) in operands.iter().enumerate() {
2317 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2318 Ok(field_ty) => field_ty,
2319 Err(FieldAccessError::OutOfRange { field_count }) => {
2323 "accessed field #{} but variant only has {}",
2330 let operand_ty = operand.ty(body, tcx);
2332 if let Err(terr) = self.sub_types(
2335 location.to_locations(),
2336 ConstraintCategory::Boring,
2341 "{:?} is not a subtype of {:?}: {:?}",
2350 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2354 /// - `location`: the location `L` where the borrow expression occurs
2355 /// - `borrow_region`: the region `'a` associated with the borrow
2356 /// - `borrowed_place`: the place `P` being borrowed
2357 fn add_reborrow_constraint(
2361 borrow_region: ty::Region<'tcx>,
2362 borrowed_place: &Place<'tcx>,
2364 // These constraints are only meaningful during borrowck:
2365 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2366 self.borrowck_context;
2368 // In Polonius mode, we also push a `borrow_region` fact
2369 // linking the loan to the region (in some cases, though,
2370 // there is no loan associated with this borrow expression --
2371 // that occurs when we are borrowing an unsafe place, for
2373 if let Some(all_facts) = all_facts {
2374 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2375 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2376 let region_vid = borrow_region.to_region_vid();
2377 all_facts.borrow_region.push((
2380 location_table.mid_index(location),
2385 // If we are reborrowing the referent of another reference, we
2386 // need to add outlives relationships. In a case like `&mut
2387 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2388 // need to ensure that `'b: 'a`.
2391 "add_reborrow_constraint({:?}, {:?}, {:?})",
2392 location, borrow_region, borrowed_place
2395 let mut cursor = borrowed_place.projection.as_ref();
2396 while let [proj_base @ .., elem] = cursor {
2399 debug!("add_reborrow_constraint - iteration {:?}", elem);
2402 ProjectionElem::Deref => {
2403 let tcx = self.infcx.tcx;
2404 let base_ty = Place::ty_from(&borrowed_place.base, proj_base, body, tcx).ty;
2406 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2407 match base_ty.kind {
2408 ty::Ref(ref_region, _, mutbl) => {
2409 constraints.outlives_constraints.push(OutlivesConstraint {
2410 sup: ref_region.to_region_vid(),
2411 sub: borrow_region.to_region_vid(),
2412 locations: location.to_locations(),
2413 category: ConstraintCategory::Boring,
2417 hir::Mutability::Not => {
2418 // Immutable reference. We don't need the base
2419 // to be valid for the entire lifetime of
2423 hir::Mutability::Mut => {
2424 // Mutable reference. We *do* need the base
2425 // to be valid, because after the base becomes
2426 // invalid, someone else can use our mutable deref.
2428 // This is in order to make the following function
2431 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2436 // As otherwise you could clone `&mut T` using the
2437 // following function:
2439 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2440 // let my_clone = unsafe_deref(&'a x);
2449 // deref of raw pointer, guaranteed to be valid
2452 ty::Adt(def, _) if def.is_box() => {
2453 // deref of `Box`, need the base to be valid - propagate
2455 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2458 ProjectionElem::Field(..)
2459 | ProjectionElem::Downcast(..)
2460 | ProjectionElem::Index(..)
2461 | ProjectionElem::ConstantIndex { .. }
2462 | ProjectionElem::Subslice { .. } => {
2463 // other field access
2469 fn prove_aggregate_predicates(
2471 aggregate_kind: &AggregateKind<'tcx>,
2474 let tcx = self.tcx();
2477 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2478 aggregate_kind, location
2481 let instantiated_predicates = match aggregate_kind {
2482 AggregateKind::Adt(def, _, substs, _, _) => {
2483 tcx.predicates_of(def.did).instantiate(tcx, substs)
2486 // For closures, we have some **extra requirements** we
2488 // have to check. In particular, in their upvars and
2489 // signatures, closures often reference various regions
2490 // from the surrounding function -- we call those the
2491 // closure's free regions. When we borrow-check (and hence
2492 // region-check) closures, we may find that the closure
2493 // requires certain relationships between those free
2494 // regions. However, because those free regions refer to
2495 // portions of the CFG of their caller, the closure is not
2496 // in a position to verify those relationships. In that
2497 // case, the requirements get "propagated" to us, and so
2498 // we have to solve them here where we instantiate the
2501 // Despite the opacity of the previous parapgrah, this is
2502 // actually relatively easy to understand in terms of the
2503 // desugaring. A closure gets desugared to a struct, and
2504 // these extra requirements are basically like where
2505 // clauses on the struct.
2506 AggregateKind::Closure(def_id, substs)
2507 | AggregateKind::Generator(def_id, substs, _) => {
2508 self.prove_closure_bounds(tcx, *def_id, substs, location)
2511 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2514 self.normalize_and_prove_instantiated_predicates(
2515 instantiated_predicates,
2516 location.to_locations(),
2520 fn prove_closure_bounds(
2524 substs: SubstsRef<'tcx>,
2526 ) -> ty::InstantiatedPredicates<'tcx> {
2527 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2528 let closure_constraints = QueryRegionConstraints {
2529 outlives: closure_region_requirements.apply_requirements(tcx, def_id, substs),
2531 // Presently, closures never propagate member
2532 // constraints to their parents -- they are enforced
2533 // locally. This is largely a non-issue as member
2534 // constraints only come from `-> impl Trait` and
2535 // friends which don't appear (thus far...) in
2537 member_constraints: vec![],
2540 let bounds_mapping = closure_constraints
2544 .filter_map(|(idx, constraint)| {
2545 let ty::OutlivesPredicate(k1, r2) =
2546 constraint.no_bound_vars().unwrap_or_else(|| {
2547 bug!("query_constraint {:?} contained bound vars", constraint,);
2551 GenericArgKind::Lifetime(r1) => {
2552 // constraint is r1: r2
2553 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2554 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2555 let outlives_requirements =
2556 &closure_region_requirements.outlives_requirements[idx];
2559 (outlives_requirements.category, outlives_requirements.blame_span),
2562 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2570 .closure_bounds_mapping
2571 .insert(location, bounds_mapping);
2572 assert!(existing.is_none(), "Multiple closures at the same location.");
2574 self.push_region_constraints(
2575 location.to_locations(),
2576 ConstraintCategory::ClosureBounds,
2577 &closure_constraints,
2581 tcx.predicates_of(def_id).instantiate(tcx, substs)
2586 trait_ref: ty::TraitRef<'tcx>,
2587 locations: Locations,
2588 category: ConstraintCategory,
2590 self.prove_predicates(
2591 Some(ty::Predicate::Trait(trait_ref.to_poly_trait_ref().to_poly_trait_predicate())),
2597 fn normalize_and_prove_instantiated_predicates(
2599 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2600 locations: Locations,
2602 for predicate in instantiated_predicates.predicates {
2603 let predicate = self.normalize(predicate, locations);
2604 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2608 fn prove_predicates(
2610 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2611 locations: Locations,
2612 category: ConstraintCategory,
2614 for predicate in predicates {
2615 debug!("prove_predicates(predicate={:?}, locations={:?})", predicate, locations,);
2617 self.prove_predicate(predicate, locations, category);
2623 predicate: ty::Predicate<'tcx>,
2624 locations: Locations,
2625 category: ConstraintCategory,
2627 debug!("prove_predicate(predicate={:?}, location={:?})", predicate, locations,);
2629 let param_env = self.param_env;
2630 self.fully_perform_op(
2633 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2635 .unwrap_or_else(|NoSolution| {
2636 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2640 fn typeck_mir(&mut self, body: ReadOnlyBodyAndCache<'_, 'tcx>) {
2641 self.last_span = body.span;
2642 debug!("run_on_mir: {:?}", body.span);
2644 for (local, local_decl) in body.local_decls.iter_enumerated() {
2645 self.check_local(&body, local, local_decl);
2648 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2649 let mut location = Location { block, statement_index: 0 };
2650 for stmt in &block_data.statements {
2651 if !stmt.source_info.span.is_dummy() {
2652 self.last_span = stmt.source_info.span;
2654 self.check_stmt(body, stmt, location);
2655 location.statement_index += 1;
2658 self.check_terminator(&body, block_data.terminator(), location);
2659 self.check_iscleanup(&body, block_data);
2663 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2665 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2667 debug!("normalize(value={:?}, location={:?})", value, location);
2668 let param_env = self.param_env;
2669 self.fully_perform_op(
2670 location.to_locations(),
2671 ConstraintCategory::Boring,
2672 param_env.and(type_op::normalize::Normalize::new(value)),
2674 .unwrap_or_else(|NoSolution| {
2675 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2681 trait NormalizeLocation: fmt::Debug + Copy {
2682 fn to_locations(self) -> Locations;
2685 impl NormalizeLocation for Locations {
2686 fn to_locations(self) -> Locations {
2691 impl NormalizeLocation for Location {
2692 fn to_locations(self) -> Locations {
2693 Locations::Single(self)
2697 #[derive(Debug, Default)]
2698 struct ObligationAccumulator<'tcx> {
2699 obligations: PredicateObligations<'tcx>,
2702 impl<'tcx> ObligationAccumulator<'tcx> {
2703 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2704 let InferOk { value, obligations } = value;
2705 self.obligations.extend(obligations);
2709 fn into_vec(self) -> PredicateObligations<'tcx> {