1 //! This pass type-checks the MIR to ensure it is not broken.
3 #![allow(unreachable_code)]
5 use crate::borrow_check::borrow_set::BorrowSet;
6 use crate::borrow_check::location::LocationTable;
7 use crate::borrow_check::nll::constraints::{OutlivesConstraintSet, OutlivesConstraint};
8 use crate::borrow_check::nll::member_constraints::MemberConstraintSet;
9 use crate::borrow_check::nll::facts::AllFacts;
10 use crate::borrow_check::nll::region_infer::values::LivenessValues;
11 use crate::borrow_check::nll::region_infer::values::PlaceholderIndex;
12 use crate::borrow_check::nll::region_infer::values::PlaceholderIndices;
13 use crate::borrow_check::nll::region_infer::values::RegionValueElements;
14 use crate::borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
15 use crate::borrow_check::nll::renumber;
16 use crate::borrow_check::nll::type_check::free_region_relations::{
17 CreateResult, UniversalRegionRelations,
19 use crate::borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
20 use crate::borrow_check::nll::ToRegionVid;
21 use crate::dataflow::move_paths::MoveData;
22 use crate::dataflow::FlowAtLocation;
23 use crate::dataflow::MaybeInitializedPlaces;
26 use rustc::hir::def_id::DefId;
27 use rustc::infer::canonical::QueryRegionConstraints;
28 use rustc::infer::outlives::env::RegionBoundPairs;
29 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
30 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
31 use rustc::mir::interpret::{ConstValue, PanicMessage};
32 use rustc::mir::tcx::PlaceTy;
33 use rustc::mir::visit::{PlaceContext, Visitor, NonMutatingUseContext};
35 use rustc::traits::query::type_op;
36 use rustc::traits::query::type_op::custom::CustomTypeOp;
37 use rustc::traits::query::{Fallible, NoSolution};
38 use rustc::traits::{self, ObligationCause, PredicateObligations};
39 use rustc::ty::adjustment::{PointerCast};
40 use rustc::ty::fold::TypeFoldable;
41 use rustc::ty::subst::{Subst, SubstsRef, UnpackedKind, UserSubsts};
43 self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, UserType,
44 CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
45 UserTypeAnnotationIndex,
47 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
48 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
49 use rustc::ty::layout::VariantIdx;
51 use std::{fmt, iter, mem};
52 use syntax_pos::{Span, DUMMY_SP};
54 macro_rules! span_mirbug {
55 ($context:expr, $elem:expr, $($message:tt)*) => ({
56 $crate::borrow_check::nll::type_check::mirbug(
60 "broken MIR in {:?} ({:?}): {}",
63 format_args!($($message)*),
69 macro_rules! span_mirbug_and_err {
70 ($context:expr, $elem:expr, $($message:tt)*) => ({
72 span_mirbug!($context, $elem, $($message)*);
78 mod constraint_conversion;
79 pub mod free_region_relations;
84 /// Type checks the given `mir` in the context of the inference
85 /// context `infcx`. Returns any region constraints that have yet to
86 /// be proven. This result is includes liveness constraints that
87 /// ensure that regions appearing in the types of all local variables
88 /// are live at all points where that local variable may later be
91 /// This phase of type-check ought to be infallible -- this is because
92 /// the original, HIR-based type-check succeeded. So if any errors
93 /// occur here, we will get a `bug!` reported.
97 /// - `infcx` -- inference context to use
98 /// - `param_env` -- parameter environment to use for trait solving
99 /// - `mir` -- MIR to type-check
100 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
101 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
102 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
103 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
104 /// to outlive; should represent the fn body
105 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
106 /// the types of the input parameters found in the MIR itself will be equated with these
107 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
108 /// the type for the RETURN_PLACE will be equated with this
109 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
110 /// constraints for the regions in the types of variables
111 /// - `flow_inits` -- results of a maybe-init dataflow analysis
112 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
113 pub(crate) fn type_check<'tcx>(
114 infcx: &InferCtxt<'_, 'tcx>,
115 param_env: ty::ParamEnv<'tcx>,
118 universal_regions: &Rc<UniversalRegions<'tcx>>,
119 location_table: &LocationTable,
120 borrow_set: &BorrowSet<'tcx>,
121 all_facts: &mut Option<AllFacts>,
122 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'_, 'tcx>>,
123 move_data: &MoveData<'tcx>,
124 elements: &Rc<RegionValueElements>,
125 ) -> MirTypeckResults<'tcx> {
126 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
127 let mut constraints = MirTypeckRegionConstraints {
128 placeholder_indices: PlaceholderIndices::default(),
129 placeholder_index_to_region: IndexVec::default(),
130 liveness_constraints: LivenessValues::new(elements.clone()),
131 outlives_constraints: OutlivesConstraintSet::default(),
132 member_constraints: MemberConstraintSet::default(),
133 closure_bounds_mapping: Default::default(),
134 type_tests: Vec::default(),
138 universal_region_relations,
140 normalized_inputs_and_output,
141 } = free_region_relations::create(
144 Some(implicit_region_bound),
149 let mut borrowck_context = BorrowCheckContext {
154 constraints: &mut constraints,
163 implicit_region_bound,
164 &mut borrowck_context,
165 &universal_region_relations,
167 cx.equate_inputs_and_outputs(body, universal_regions, &normalized_inputs_and_output);
168 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
170 translate_outlives_facts(cx.borrowck_context);
176 universal_region_relations,
180 fn type_check_internal<'a, 'tcx, R>(
181 infcx: &'a InferCtxt<'a, 'tcx>,
183 param_env: ty::ParamEnv<'tcx>,
184 body: &'a Body<'tcx>,
185 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
186 implicit_region_bound: ty::Region<'tcx>,
187 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
188 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
189 mut extra: impl FnMut(&mut TypeChecker<'a, 'tcx>) -> R,
191 let mut checker = TypeChecker::new(
197 implicit_region_bound,
199 universal_region_relations,
201 let errors_reported = {
202 let mut verifier = TypeVerifier::new(&mut checker, body);
203 verifier.visit_body(body);
204 verifier.errors_reported
207 if !errors_reported {
208 // if verifier failed, don't do further checks to avoid ICEs
209 checker.typeck_mir(body);
215 fn translate_outlives_facts(cx: &mut BorrowCheckContext<'_, '_>) {
216 if let Some(facts) = cx.all_facts {
217 let location_table = cx.location_table;
220 .extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
221 |constraint: &OutlivesConstraint| {
222 if let Some(from_location) = constraint.locations.from_location() {
223 Either::Left(iter::once((
226 location_table.mid_index(from_location),
232 .map(move |location| (constraint.sup, constraint.sub, location)),
240 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
241 // We sometimes see MIR failures (notably predicate failures) due to
242 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
243 // to avoid reporting bugs in those cases.
244 tcx.sess.diagnostic().delay_span_bug(span, msg);
247 enum FieldAccessError {
248 OutOfRange { field_count: usize },
251 /// Verifies that MIR types are sane to not crash further checks.
253 /// The sanitize_XYZ methods here take an MIR object and compute its
254 /// type, calling `span_mirbug` and returning an error type if there
256 struct TypeVerifier<'a, 'b, 'tcx> {
257 cx: &'a mut TypeChecker<'b, 'tcx>,
258 body: &'b Body<'tcx>,
261 errors_reported: bool,
264 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
265 fn visit_span(&mut self, span: &Span) {
266 if !span.is_dummy() {
267 self.last_span = *span;
271 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
272 self.sanitize_place(place, location, context);
275 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
276 self.super_constant(constant, location);
277 self.sanitize_constant(constant, location);
278 self.sanitize_type(constant, constant.ty);
280 if let Some(annotation_index) = constant.user_ty {
281 if let Err(terr) = self.cx.relate_type_and_user_type(
283 ty::Variance::Invariant,
284 &UserTypeProjection { base: annotation_index, projs: vec![], },
285 location.to_locations(),
286 ConstraintCategory::Boring,
288 let annotation = &self.cx.user_type_annotations[annotation_index];
292 "bad constant user type {:?} vs {:?}: {:?}",
299 if let ConstValue::Unevaluated(def_id, substs) = constant.literal.val {
300 if let Err(terr) = self.cx.fully_perform_op(
301 location.to_locations(),
302 ConstraintCategory::Boring,
303 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
304 constant.ty, def_id, UserSubsts { substs, user_self_ty: None },
310 "bad constant type {:?} ({:?})",
316 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
317 let tcx = self.tcx();
319 let instantiated_predicates = tcx
320 .predicates_of(def_id)
321 .instantiate(tcx, substs);
322 self.cx.normalize_and_prove_instantiated_predicates(
323 instantiated_predicates,
324 location.to_locations(),
330 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
331 self.super_rvalue(rvalue, location);
332 let rval_ty = rvalue.ty(self.body, self.tcx());
333 self.sanitize_type(rvalue, rval_ty);
336 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
337 self.super_local_decl(local, local_decl);
338 self.sanitize_type(local_decl, local_decl.ty);
340 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
341 let ty = if !local_decl.is_nonref_binding() {
342 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
343 // reference so we can check the type annotation for the remaining type.
344 if let ty::Ref(_, rty, _) = local_decl.ty.sty {
347 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
353 if let Err(terr) = self.cx.relate_type_and_user_type(
355 ty::Variance::Invariant,
357 Locations::All(*span),
358 ConstraintCategory::TypeAnnotation,
363 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
373 fn visit_body(&mut self, body: &Body<'tcx>) {
374 self.sanitize_type(&"return type", body.return_ty());
375 for local_decl in &body.local_decls {
376 self.sanitize_type(local_decl, local_decl.ty);
378 if self.errors_reported {
381 self.super_body(body);
385 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
386 fn new(cx: &'a mut TypeChecker<'b, 'tcx>, body: &'b Body<'tcx>) -> Self {
389 mir_def_id: cx.mir_def_id,
391 last_span: body.span,
392 errors_reported: false,
396 fn tcx(&self) -> TyCtxt<'tcx> {
400 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
401 if ty.has_escaping_bound_vars() || ty.references_error() {
402 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
408 /// Checks that the constant's `ty` field matches up with what would be
409 /// expected from its literal. Unevaluated constants and well-formed
410 /// constraints are checked by `visit_constant`.
411 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
413 "sanitize_constant(constant={:?}, location={:?})",
417 let literal = constant.literal;
419 if let ConstValue::Unevaluated(..) = literal.val {
423 debug!("sanitize_constant: expected_ty={:?}", literal.ty);
425 if let Err(terr) = self.cx.eq_types(
428 location.to_locations(),
429 ConstraintCategory::Boring,
434 "constant {:?} should have type {:?} but has {:?} ({:?})",
443 /// Checks that the types internal to the `place` match up with
444 /// what would be expected.
449 context: PlaceContext,
451 debug!("sanitize_place: {:?}", place);
453 place.iterate(|place_base, place_projection| {
454 let mut place_ty = match place_base {
455 PlaceBase::Local(index) =>
456 PlaceTy::from_ty(self.body.local_decls[*index].ty),
457 PlaceBase::Static(box Static { kind, ty: sty }) => {
458 let sty = self.sanitize_type(place, sty);
460 |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
464 if let Err(terr) = verifier.cx.eq_types(
467 location.to_locations(),
468 ConstraintCategory::Boring,
473 "bad promoted type ({:?}: {:?}): {:?}",
481 StaticKind::Promoted(promoted) => {
482 if !self.errors_reported {
483 let promoted_body = &self.body.promoted[*promoted];
484 self.sanitize_promoted(promoted_body, location);
486 let promoted_ty = promoted_body.return_ty();
487 check_err(self, place, promoted_ty, sty);
490 StaticKind::Static(def_id) => {
491 let ty = self.tcx().type_of(*def_id);
492 let ty = self.cx.normalize(ty, location);
494 check_err(self, place, ty, sty);
497 PlaceTy::from_ty(sty)
501 // FIXME use place_projection.is_empty() when is available
502 if place.projection.is_none() {
503 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
504 let is_promoted = match place {
506 base: PlaceBase::Static(box Static {
507 kind: StaticKind::Promoted(_),
516 let tcx = self.tcx();
517 let trait_ref = ty::TraitRef {
518 def_id: tcx.lang_items().copy_trait().unwrap(),
519 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
522 // In order to have a Copy operand, the type T of the
523 // value must be Copy. Note that we prove that T: Copy,
524 // rather than using the `is_copy_modulo_regions`
525 // test. This is important because
526 // `is_copy_modulo_regions` ignores the resulting region
527 // obligations and assumes they pass. This can result in
528 // bounds from Copy impls being unsoundly ignored (e.g.,
529 // #29149). Note that we decide to use Copy before knowing
530 // whether the bounds fully apply: in effect, the rule is
531 // that if a value of some type could implement Copy, then
533 self.cx.prove_trait_ref(
535 location.to_locations(),
536 ConstraintCategory::CopyBound,
542 for proj in place_projection {
543 if place_ty.variant_index.is_none() {
544 if place_ty.ty.references_error() {
545 assert!(self.errors_reported);
546 return PlaceTy::from_ty(self.tcx().types.err);
549 place_ty = self.sanitize_projection(place_ty, &proj.elem, place, location)
556 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
557 // Determine the constraints from the promoted MIR by running the type
558 // checker on the promoted MIR, then transfer the constraints back to
559 // the main MIR, changing the locations to the provided location.
561 let parent_body = mem::replace(&mut self.body, promoted_body);
563 let all_facts = &mut None;
564 let mut constraints = Default::default();
565 let mut closure_bounds = Default::default();
566 // Don't try to add borrow_region facts for the promoted MIR
567 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
569 // Use a new sets of constraints and closure bounds so that we can
570 // modify their locations.
572 &mut self.cx.borrowck_context.constraints.outlives_constraints,
576 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
580 self.visit_body(promoted_body);
582 if !self.errors_reported {
583 // if verifier failed, don't do further checks to avoid ICEs
584 self.cx.typeck_mir(promoted_body);
587 self.body = parent_body;
588 // Merge the outlives constraints back in, at the given location.
589 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
591 &mut self.cx.borrowck_context.constraints.outlives_constraints,
595 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
599 let locations = location.to_locations();
600 for constraint in constraints.outlives().iter() {
601 let mut constraint = *constraint;
602 constraint.locations = locations;
603 if let ConstraintCategory::Return
604 | ConstraintCategory::UseAsConst
605 | ConstraintCategory::UseAsStatic = constraint.category
607 // "Returning" from a promoted is an assigment to a
608 // temporary from the user's point of view.
609 constraint.category = ConstraintCategory::Boring;
611 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
614 if !closure_bounds.is_empty() {
615 let combined_bounds_mapping = closure_bounds
617 .flat_map(|(_, value)| value)
619 let existing = self.cx.borrowck_context
621 .closure_bounds_mapping
622 .insert(location, combined_bounds_mapping);
625 "Multiple promoteds/closures at the same location."
630 fn sanitize_projection(
633 pi: &PlaceElem<'tcx>,
637 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
638 let tcx = self.tcx();
639 let base_ty = base.ty;
641 ProjectionElem::Deref => {
642 let deref_ty = base_ty.builtin_deref(true);
644 deref_ty.map(|t| t.ty).unwrap_or_else(|| {
645 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
649 ProjectionElem::Index(i) => {
650 let index_ty = Place::from(i).ty(self.body, tcx).ty;
651 if index_ty != tcx.types.usize {
653 span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
657 base_ty.builtin_index().unwrap_or_else(|| {
658 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
663 ProjectionElem::ConstantIndex { .. } => {
664 // consider verifying in-bounds
666 base_ty.builtin_index().unwrap_or_else(|| {
667 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
671 ProjectionElem::Subslice { from, to } => PlaceTy::from_ty(
673 ty::Array(inner, size) => {
674 let size = size.unwrap_usize(tcx);
675 let min_size = (from as u64) + (to as u64);
676 if let Some(rest_size) = size.checked_sub(min_size) {
677 tcx.mk_array(inner, rest_size)
679 span_mirbug_and_err!(
682 "taking too-small slice of {:?}",
687 ty::Slice(..) => base_ty,
688 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
691 ProjectionElem::Downcast(maybe_name, index) => match base_ty.sty {
692 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
693 if index.as_usize() >= adt_def.variants.len() {
695 span_mirbug_and_err!(
698 "cast to variant #{:?} but enum only has {:?}",
700 adt_def.variants.len()
706 variant_index: Some(index),
710 // We do not need to handle generators here, because this runs
711 // before the generator transform stage.
713 let ty = if let Some(name) = maybe_name {
714 span_mirbug_and_err!(
717 "can't downcast {:?} as {:?}",
722 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
727 ProjectionElem::Field(field, fty) => {
728 let fty = self.sanitize_type(place, fty);
729 match self.field_ty(place, base, field, location) {
730 Ok(ty) => if let Err(terr) = self.cx.eq_types(
733 location.to_locations(),
734 ConstraintCategory::Boring,
739 "bad field access ({:?}: {:?}): {:?}",
745 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
748 "accessed field #{} but variant only has {}",
753 PlaceTy::from_ty(fty)
758 fn error(&mut self) -> Ty<'tcx> {
759 self.errors_reported = true;
765 parent: &dyn fmt::Debug,
766 base_ty: PlaceTy<'tcx>,
769 ) -> Result<Ty<'tcx>, FieldAccessError> {
770 let tcx = self.tcx();
772 let (variant, substs) = match base_ty {
773 PlaceTy { ty, variant_index: Some(variant_index) } => match ty.sty {
774 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
775 ty::Generator(def_id, substs, _) => {
776 let mut variants = substs.state_tys(def_id, tcx);
777 let mut variant = match variants.nth(variant_index.into()) {
780 bug!("variant_index of generator out of range: {:?}/{:?}",
782 substs.state_tys(def_id, tcx).count())
785 return match variant.nth(field.index()) {
787 None => Err(FieldAccessError::OutOfRange {
788 field_count: variant.count(),
792 _ => bug!("can't have downcast of non-adt non-generator type"),
794 PlaceTy { ty, variant_index: None } => match ty.sty {
795 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
796 (&adt_def.variants[VariantIdx::new(0)], substs),
797 ty::Closure(def_id, substs) => {
798 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
800 None => Err(FieldAccessError::OutOfRange {
801 field_count: substs.upvar_tys(def_id, tcx).count(),
805 ty::Generator(def_id, substs, _) => {
806 // Only prefix fields (upvars and current state) are
807 // accessible without a variant index.
808 return match substs.prefix_tys(def_id, tcx).nth(field.index()) {
810 None => Err(FieldAccessError::OutOfRange {
811 field_count: substs.prefix_tys(def_id, tcx).count(),
816 return match tys.get(field.index()) {
817 Some(&ty) => Ok(ty.expect_ty()),
818 None => Err(FieldAccessError::OutOfRange {
819 field_count: tys.len(),
824 return Ok(span_mirbug_and_err!(
827 "can't project out of {:?}",
834 if let Some(field) = variant.fields.get(field.index()) {
835 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
837 Err(FieldAccessError::OutOfRange {
838 field_count: variant.fields.len(),
844 /// The MIR type checker. Visits the MIR and enforces all the
845 /// constraints needed for it to be valid and well-typed. Along the
846 /// way, it accrues region constraints -- these can later be used by
847 /// NLL region checking.
848 struct TypeChecker<'a, 'tcx> {
849 infcx: &'a InferCtxt<'a, 'tcx>,
850 param_env: ty::ParamEnv<'tcx>,
852 body: &'a Body<'tcx>,
853 /// User type annotations are shared between the main MIR and the MIR of
854 /// all of the promoted items.
855 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
857 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
858 implicit_region_bound: ty::Region<'tcx>,
859 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
860 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
861 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
864 struct BorrowCheckContext<'a, 'tcx> {
865 universal_regions: &'a UniversalRegions<'tcx>,
866 location_table: &'a LocationTable,
867 all_facts: &'a mut Option<AllFacts>,
868 borrow_set: &'a BorrowSet<'tcx>,
869 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
872 crate struct MirTypeckResults<'tcx> {
873 crate constraints: MirTypeckRegionConstraints<'tcx>,
874 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
877 /// A collection of region constraints that must be satisfied for the
878 /// program to be considered well-typed.
879 crate struct MirTypeckRegionConstraints<'tcx> {
880 /// Maps from a `ty::Placeholder` to the corresponding
881 /// `PlaceholderIndex` bit that we will use for it.
883 /// To keep everything in sync, do not insert this set
884 /// directly. Instead, use the `placeholder_region` helper.
885 crate placeholder_indices: PlaceholderIndices,
887 /// Each time we add a placeholder to `placeholder_indices`, we
888 /// also create a corresponding "representative" region vid for
889 /// that wraps it. This vector tracks those. This way, when we
890 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
891 /// the same underlying `RegionVid`.
892 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
894 /// In general, the type-checker is not responsible for enforcing
895 /// liveness constraints; this job falls to the region inferencer,
896 /// which performs a liveness analysis. However, in some limited
897 /// cases, the MIR type-checker creates temporary regions that do
898 /// not otherwise appear in the MIR -- in particular, the
899 /// late-bound regions that it instantiates at call-sites -- and
900 /// hence it must report on their liveness constraints.
901 crate liveness_constraints: LivenessValues<RegionVid>,
903 crate outlives_constraints: OutlivesConstraintSet,
905 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
907 crate closure_bounds_mapping:
908 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
910 crate type_tests: Vec<TypeTest<'tcx>>,
913 impl MirTypeckRegionConstraints<'tcx> {
914 fn placeholder_region(
916 infcx: &InferCtxt<'_, 'tcx>,
917 placeholder: ty::PlaceholderRegion,
918 ) -> ty::Region<'tcx> {
919 let placeholder_index = self.placeholder_indices.insert(placeholder);
920 match self.placeholder_index_to_region.get(placeholder_index) {
923 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
924 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
925 self.placeholder_index_to_region.push(region);
932 /// The `Locations` type summarizes *where* region constraints are
933 /// required to hold. Normally, this is at a particular point which
934 /// created the obligation, but for constraints that the user gave, we
935 /// want the constraint to hold at all points.
936 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
938 /// Indicates that a type constraint should always be true. This
939 /// is particularly important in the new borrowck analysis for
940 /// things like the type of the return slot. Consider this
944 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
946 /// return &y; // error
950 /// Here, we wind up with the signature from the return type being
951 /// something like `&'1 u32` where `'1` is a universal region. But
952 /// the type of the return slot `_0` is something like `&'2 u32`
953 /// where `'2` is an existential region variable. The type checker
954 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
955 /// older NLL analysis, we required this only at the entry point
956 /// to the function. By the nature of the constraints, this wound
957 /// up propagating to all points reachable from start (because
958 /// `'1` -- as a universal region -- is live everywhere). In the
959 /// newer analysis, though, this doesn't work: `_0` is considered
960 /// dead at the start (it has no usable value) and hence this type
961 /// equality is basically a no-op. Then, later on, when we do `_0
962 /// = &'3 y`, that region `'3` never winds up related to the
963 /// universal region `'1` and hence no error occurs. Therefore, we
964 /// use Locations::All instead, which ensures that the `'1` and
965 /// `'2` are equal everything. We also use this for other
966 /// user-given type annotations; e.g., if the user wrote `let mut
967 /// x: &'static u32 = ...`, we would ensure that all values
968 /// assigned to `x` are of `'static` lifetime.
970 /// The span points to the place the constraint arose. For example,
971 /// it points to the type in a user-given type annotation. If
972 /// there's no sensible span then it's DUMMY_SP.
975 /// An outlives constraint that only has to hold at a single location,
976 /// usually it represents a point where references flow from one spot to
977 /// another (e.g., `x = y`)
982 pub fn from_location(&self) -> Option<Location> {
984 Locations::All(_) => None,
985 Locations::Single(from_location) => Some(*from_location),
989 /// Gets a span representing the location.
990 pub fn span(&self, body: &Body<'_>) -> Span {
992 Locations::All(span) => *span,
993 Locations::Single(l) => body.source_info(*l).span,
998 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1000 infcx: &'a InferCtxt<'a, 'tcx>,
1001 body: &'a Body<'tcx>,
1003 param_env: ty::ParamEnv<'tcx>,
1004 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1005 implicit_region_bound: ty::Region<'tcx>,
1006 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1007 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
1009 let mut checker = Self {
1011 last_span: DUMMY_SP,
1014 user_type_annotations: &body.user_type_annotations,
1017 implicit_region_bound,
1019 reported_errors: Default::default(),
1020 universal_region_relations,
1022 checker.check_user_type_annotations();
1026 /// Equate the inferred type and the annotated type for user type annotations
1027 fn check_user_type_annotations(&mut self) {
1029 "check_user_type_annotations: user_type_annotations={:?}",
1030 self.user_type_annotations
1032 for user_annotation in self.user_type_annotations {
1033 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1034 let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
1038 UserType::Ty(mut ty) => {
1039 ty = self.normalize(ty, Locations::All(span));
1041 if let Err(terr) = self.eq_types(
1044 Locations::All(span),
1045 ConstraintCategory::BoringNoLocation,
1050 "bad user type ({:?} = {:?}): {:?}",
1057 self.prove_predicate(
1058 ty::Predicate::WellFormed(inferred_ty),
1059 Locations::All(span),
1060 ConstraintCategory::TypeAnnotation,
1063 UserType::TypeOf(def_id, user_substs) => {
1064 if let Err(terr) = self.fully_perform_op(
1065 Locations::All(span),
1066 ConstraintCategory::BoringNoLocation,
1067 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1068 inferred_ty, def_id, user_substs,
1074 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1086 /// Given some operation `op` that manipulates types, proves
1087 /// predicates, or otherwise uses the inference context, executes
1088 /// `op` and then executes all the further obligations that `op`
1089 /// returns. This will yield a set of outlives constraints amongst
1090 /// regions which are extracted and stored as having occurred at
1093 /// **Any `rustc::infer` operations that might generate region
1094 /// constraints should occur within this method so that those
1095 /// constraints can be properly localized!**
1096 fn fully_perform_op<R>(
1098 locations: Locations,
1099 category: ConstraintCategory,
1100 op: impl type_op::TypeOp<'tcx, Output = R>,
1102 let (r, opt_data) = op.fully_perform(self.infcx)?;
1104 if let Some(data) = &opt_data {
1105 self.push_region_constraints(locations, category, data);
1111 fn push_region_constraints(
1113 locations: Locations,
1114 category: ConstraintCategory,
1115 data: &QueryRegionConstraints<'tcx>,
1118 "push_region_constraints: constraints generated at {:?} are {:#?}",
1122 constraint_conversion::ConstraintConversion::new(
1124 self.borrowck_context.universal_regions,
1125 self.region_bound_pairs,
1126 Some(self.implicit_region_bound),
1130 &mut self.borrowck_context.constraints,
1131 ).convert_all(data);
1134 /// Convenient wrapper around `relate_tys::relate_types` -- see
1135 /// that fn for docs.
1141 locations: Locations,
1142 category: ConstraintCategory,
1144 relate_tys::relate_types(
1151 Some(self.borrowck_context),
1159 locations: Locations,
1160 category: ConstraintCategory,
1162 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1165 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1166 /// variables in `sub` with their inferred definitions and try
1167 /// again. This is used for opaque types in places (e.g., `let x:
1168 /// impl Foo = ..`).
1169 fn sub_types_or_anon(
1173 locations: Locations,
1174 category: ConstraintCategory,
1176 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1177 if let ty::Opaque(..) = sup.sty {
1178 // When you have `let x: impl Foo = ...` in a closure,
1179 // the resulting inferend values are stored with the
1180 // def-id of the base function.
1181 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1182 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1194 locations: Locations,
1195 category: ConstraintCategory,
1197 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1200 fn relate_type_and_user_type(
1204 user_ty: &UserTypeProjection,
1205 locations: Locations,
1206 category: ConstraintCategory,
1209 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1210 a, v, user_ty, locations,
1213 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1214 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1216 let tcx = self.infcx.tcx;
1218 for proj in &user_ty.projs {
1219 let projected_ty = curr_projected_ty.projection_ty_core(tcx, proj, |this, field, &()| {
1220 let ty = this.field_ty(tcx, field);
1221 self.normalize(ty, locations)
1223 curr_projected_ty = projected_ty;
1225 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1226 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1228 let ty = curr_projected_ty.ty;
1229 self.relate_types(a, v, ty, locations, category)?;
1234 fn eq_opaque_type_and_type(
1236 revealed_ty: Ty<'tcx>,
1238 anon_owner_def_id: DefId,
1239 locations: Locations,
1240 category: ConstraintCategory,
1243 "eq_opaque_type_and_type( \
1246 revealed_ty, anon_ty
1248 let infcx = self.infcx;
1249 let tcx = infcx.tcx;
1250 let param_env = self.param_env;
1251 let body = self.body;
1252 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1253 let opaque_type_map = self.fully_perform_op(
1258 let mut obligations = ObligationAccumulator::default();
1260 let dummy_body_id = ObligationCause::dummy().body_id;
1261 let (output_ty, opaque_type_map) =
1262 obligations.add(infcx.instantiate_opaque_types(
1267 locations.span(body),
1270 "eq_opaque_type_and_type: \
1271 instantiated output_ty={:?} \
1272 opaque_type_map={:#?} \
1274 output_ty, opaque_type_map, revealed_ty
1276 obligations.add(infcx
1277 .at(&ObligationCause::dummy(), param_env)
1278 .eq(output_ty, revealed_ty)?);
1280 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1281 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1282 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1283 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1284 let concrete_is_opaque = infcx
1285 .resolve_vars_if_possible(&opaque_decl.concrete_ty).is_impl_trait();
1288 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?} \
1289 concrete_is_opaque={}",
1290 opaque_decl.concrete_ty,
1291 infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty),
1296 // concrete_is_opaque is `true` when we're using an existential
1297 // type without 'revealing' it. For example, code like this:
1299 // existential type Foo: Debug;
1300 // fn foo1() -> Foo { ... }
1301 // fn foo2() -> Foo { foo1() }
1303 // In `foo2`, we're not revealing the type of `Foo` - we're
1304 // just treating it as the opaque type.
1306 // When this occurs, we do *not* want to try to equate
1307 // the concrete type with the underlying defining type
1308 // of the existential type - this will always fail, since
1309 // the defining type of an existential type is always
1310 // some other type (e.g. not itself)
1311 // Essentially, none of the normal obligations apply here -
1312 // we're just passing around some unknown opaque type,
1313 // without actually looking at the underlying type it
1314 // gets 'revealed' into
1316 if !concrete_is_opaque {
1317 obligations.add(infcx
1318 .at(&ObligationCause::dummy(), param_env)
1319 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1323 debug!("eq_opaque_type_and_type: equated");
1326 value: Some(opaque_type_map),
1327 obligations: obligations.into_vec(),
1330 || "input_output".to_string(),
1334 let universal_region_relations = self.universal_region_relations;
1336 // Finally, if we instantiated the anon types successfully, we
1337 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1338 // prove that `T: Iterator` where `T` is the type we
1339 // instantiated it with).
1340 if let Some(opaque_type_map) = opaque_type_map {
1341 for (opaque_def_id, opaque_decl) in opaque_type_map {
1342 self.fully_perform_op(
1344 ConstraintCategory::OpaqueType,
1347 infcx.constrain_opaque_type(
1350 universal_region_relations,
1354 obligations: vec![],
1357 || "opaque_type_map".to_string(),
1365 fn tcx(&self) -> TyCtxt<'tcx> {
1369 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1370 debug!("check_stmt: {:?}", stmt);
1371 let tcx = self.tcx();
1373 StatementKind::Assign(ref place, ref rv) => {
1374 // Assignments to temporaries are not "interesting";
1375 // they are not caused by the user, but rather artifacts
1376 // of lowering. Assignments to other sorts of places *are* interesting
1378 let category = match *place {
1380 base: PlaceBase::Local(RETURN_PLACE),
1382 } => if let BorrowCheckContext {
1385 defining_ty: DefiningTy::Const(def_id, _),
1389 } = self.borrowck_context {
1390 if tcx.is_static(*def_id) {
1391 ConstraintCategory::UseAsStatic
1393 ConstraintCategory::UseAsConst
1396 ConstraintCategory::Return
1399 base: PlaceBase::Local(l),
1401 } if !body.local_decls[l].is_user_variable.is_some() => {
1402 ConstraintCategory::Boring
1404 _ => ConstraintCategory::Assignment,
1407 let place_ty = place.ty(body, tcx).ty;
1408 let rv_ty = rv.ty(body, tcx);
1410 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1415 "bad assignment ({:?} = {:?}): {:?}",
1422 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1423 if let Err(terr) = self.relate_type_and_user_type(
1425 ty::Variance::Invariant,
1426 &UserTypeProjection { base: annotation_index, projs: vec![], },
1427 location.to_locations(),
1428 ConstraintCategory::Boring,
1430 let annotation = &self.user_type_annotations[annotation_index];
1434 "bad user type on rvalue ({:?} = {:?}): {:?}",
1442 self.check_rvalue(body, rv, location);
1443 if !self.tcx().features().unsized_locals {
1444 let trait_ref = ty::TraitRef {
1445 def_id: tcx.lang_items().sized_trait().unwrap(),
1446 substs: tcx.mk_substs_trait(place_ty, &[]),
1448 self.prove_trait_ref(
1450 location.to_locations(),
1451 ConstraintCategory::SizedBound,
1455 StatementKind::SetDiscriminant {
1459 let place_type = place.ty(body, tcx).ty;
1460 let adt = match place_type.sty {
1461 ty::Adt(adt, _) if adt.is_enum() => adt,
1464 stmt.source_info.span,
1465 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1471 if variant_index.as_usize() >= adt.variants.len() {
1473 stmt.source_info.span,
1474 "bad set discriminant ({:?} = {:?}): value of of range",
1480 StatementKind::AscribeUserType(ref place, variance, box ref projection) => {
1481 let place_ty = place.ty(body, tcx).ty;
1482 if let Err(terr) = self.relate_type_and_user_type(
1486 Locations::All(stmt.source_info.span),
1487 ConstraintCategory::TypeAnnotation,
1489 let annotation = &self.user_type_annotations[projection.base];
1493 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1501 StatementKind::FakeRead(..)
1502 | StatementKind::StorageLive(..)
1503 | StatementKind::StorageDead(..)
1504 | StatementKind::InlineAsm { .. }
1505 | StatementKind::Retag { .. }
1506 | StatementKind::Nop => {}
1510 fn check_terminator(
1513 term: &Terminator<'tcx>,
1514 term_location: Location,
1516 debug!("check_terminator: {:?}", term);
1517 let tcx = self.tcx();
1519 TerminatorKind::Goto { .. }
1520 | TerminatorKind::Resume
1521 | TerminatorKind::Abort
1522 | TerminatorKind::Return
1523 | TerminatorKind::GeneratorDrop
1524 | TerminatorKind::Unreachable
1525 | TerminatorKind::Drop { .. }
1526 | TerminatorKind::FalseEdges { .. }
1527 | TerminatorKind::FalseUnwind { .. } => {
1528 // no checks needed for these
1531 TerminatorKind::DropAndReplace {
1537 let place_ty = location.ty(body, tcx).ty;
1538 let rv_ty = value.ty(body, tcx);
1540 let locations = term_location.to_locations();
1542 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1547 "bad DropAndReplace ({:?} = {:?}): {:?}",
1554 TerminatorKind::SwitchInt {
1559 let discr_ty = discr.ty(body, tcx);
1560 if let Err(terr) = self.sub_types(
1563 term_location.to_locations(),
1564 ConstraintCategory::Assignment,
1569 "bad SwitchInt ({:?} on {:?}): {:?}",
1575 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1576 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1578 // FIXME: check the values
1580 TerminatorKind::Call {
1587 let func_ty = func.ty(body, tcx);
1588 debug!("check_terminator: call, func_ty={:?}", func_ty);
1589 let sig = match func_ty.sty {
1590 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1592 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1596 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1597 term.source_info.span,
1598 LateBoundRegionConversionTime::FnCall,
1601 let sig = self.normalize(sig, term_location);
1602 self.check_call_dest(body, term, &sig, destination, term_location);
1604 self.prove_predicates(
1605 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1606 term_location.to_locations(),
1607 ConstraintCategory::Boring,
1610 // The ordinary liveness rules will ensure that all
1611 // regions in the type of the callee are live here. We
1612 // then further constrain the late-bound regions that
1613 // were instantiated at the call site to be live as
1614 // well. The resulting is that all the input (and
1615 // output) types in the signature must be live, since
1616 // all the inputs that fed into it were live.
1617 for &late_bound_region in map.values() {
1618 let region_vid = self.borrowck_context
1620 .to_region_vid(late_bound_region);
1621 self.borrowck_context
1623 .liveness_constraints
1624 .add_element(region_vid, term_location);
1627 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1629 TerminatorKind::Assert {
1630 ref cond, ref msg, ..
1632 let cond_ty = cond.ty(body, tcx);
1633 if cond_ty != tcx.types.bool {
1634 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1637 if let PanicMessage::BoundsCheck { ref len, ref index } = *msg {
1638 if len.ty(body, tcx) != tcx.types.usize {
1639 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1641 if index.ty(body, tcx) != tcx.types.usize {
1642 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1646 TerminatorKind::Yield { ref value, .. } => {
1647 let value_ty = value.ty(body, tcx);
1648 match body.yield_ty {
1649 None => span_mirbug!(self, term, "yield in non-generator"),
1651 if let Err(terr) = self.sub_types(
1654 term_location.to_locations(),
1655 ConstraintCategory::Yield,
1660 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1675 term: &Terminator<'tcx>,
1676 sig: &ty::FnSig<'tcx>,
1677 destination: &Option<(Place<'tcx>, BasicBlock)>,
1678 term_location: Location,
1680 let tcx = self.tcx();
1681 match *destination {
1682 Some((ref dest, _target_block)) => {
1683 let dest_ty = dest.ty(body, tcx).ty;
1684 let category = match *dest {
1686 base: PlaceBase::Local(RETURN_PLACE),
1689 if let BorrowCheckContext {
1692 defining_ty: DefiningTy::Const(def_id, _),
1696 } = self.borrowck_context
1698 if tcx.is_static(*def_id) {
1699 ConstraintCategory::UseAsStatic
1701 ConstraintCategory::UseAsConst
1704 ConstraintCategory::Return
1708 base: PlaceBase::Local(l),
1710 } if !body.local_decls[l].is_user_variable.is_some() => {
1711 ConstraintCategory::Boring
1713 _ => ConstraintCategory::Assignment,
1716 let locations = term_location.to_locations();
1719 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1724 "call dest mismatch ({:?} <- {:?}): {:?}",
1731 // When `#![feature(unsized_locals)]` is not enabled,
1732 // this check is done at `check_local`.
1733 if self.tcx().features().unsized_locals {
1734 let span = term.source_info.span;
1735 self.ensure_place_sized(dest_ty, span);
1739 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1740 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1746 fn check_call_inputs(
1749 term: &Terminator<'tcx>,
1750 sig: &ty::FnSig<'tcx>,
1751 args: &[Operand<'tcx>],
1752 term_location: Location,
1753 from_hir_call: bool,
1755 debug!("check_call_inputs({:?}, {:?})", sig, args);
1756 // Do not count the `VaListImpl` argument as a "true" argument to
1757 // a C-variadic function.
1758 let inputs = if sig.c_variadic {
1759 &sig.inputs()[..sig.inputs().len() - 1]
1763 if args.len() < inputs.len() || (args.len() > inputs.len() && !sig.c_variadic) {
1764 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1766 for (n, (fn_arg, op_arg)) in inputs.iter().zip(args).enumerate() {
1767 let op_arg_ty = op_arg.ty(body, self.tcx());
1768 let category = if from_hir_call {
1769 ConstraintCategory::CallArgument
1771 ConstraintCategory::Boring
1774 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1779 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1789 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1790 let is_cleanup = block_data.is_cleanup;
1791 self.last_span = block_data.terminator().source_info.span;
1792 match block_data.terminator().kind {
1793 TerminatorKind::Goto { target } => {
1794 self.assert_iscleanup(body, block_data, target, is_cleanup)
1796 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1797 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1799 TerminatorKind::Resume => if !is_cleanup {
1800 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1802 TerminatorKind::Abort => if !is_cleanup {
1803 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1805 TerminatorKind::Return => if is_cleanup {
1806 span_mirbug!(self, block_data, "return on cleanup block")
1808 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1809 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1811 TerminatorKind::Yield { resume, drop, .. } => {
1813 span_mirbug!(self, block_data, "yield in cleanup block")
1815 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1816 if let Some(drop) = drop {
1817 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1820 TerminatorKind::Unreachable => {}
1821 TerminatorKind::Drop { target, unwind, .. }
1822 | TerminatorKind::DropAndReplace { target, unwind, .. }
1823 | TerminatorKind::Assert {
1828 self.assert_iscleanup(body, block_data, target, is_cleanup);
1829 if let Some(unwind) = unwind {
1831 span_mirbug!(self, block_data, "unwind on cleanup block")
1833 self.assert_iscleanup(body, block_data, unwind, true);
1836 TerminatorKind::Call {
1841 if let &Some((_, target)) = destination {
1842 self.assert_iscleanup(body, block_data, target, is_cleanup);
1844 if let Some(cleanup) = cleanup {
1846 span_mirbug!(self, block_data, "cleanup on cleanup block")
1848 self.assert_iscleanup(body, block_data, cleanup, true);
1851 TerminatorKind::FalseEdges {
1855 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1856 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1858 TerminatorKind::FalseUnwind {
1862 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1863 if let Some(unwind) = unwind {
1868 "cleanup in cleanup block via false unwind"
1871 self.assert_iscleanup(body, block_data, unwind, true);
1877 fn assert_iscleanup(
1880 ctxt: &dyn fmt::Debug,
1884 if body[bb].is_cleanup != iscleanuppad {
1888 "cleanuppad mismatch: {:?} should be {:?}",
1895 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1896 match body.local_kind(local) {
1897 LocalKind::ReturnPointer | LocalKind::Arg => {
1898 // return values of normal functions are required to be
1899 // sized by typeck, but return values of ADT constructors are
1900 // not because we don't include a `Self: Sized` bounds on them.
1902 // Unbound parts of arguments were never required to be Sized
1903 // - maybe we should make that a warning.
1906 LocalKind::Var | LocalKind::Temp => {}
1909 // When `#![feature(unsized_locals)]` is enabled, only function calls
1910 // and nullary ops are checked in `check_call_dest`.
1911 if !self.tcx().features().unsized_locals {
1912 let span = local_decl.source_info.span;
1913 let ty = local_decl.ty;
1914 self.ensure_place_sized(ty, span);
1918 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1919 let tcx = self.tcx();
1921 // Erase the regions from `ty` to get a global type. The
1922 // `Sized` bound in no way depends on precise regions, so this
1923 // shouldn't affect `is_sized`.
1924 let gcx = tcx.global_tcx();
1925 let erased_ty = tcx.erase_regions(&ty);
1926 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1927 // in current MIR construction, all non-control-flow rvalue
1928 // expressions evaluate through `as_temp` or `into` a return
1929 // slot or local, so to find all unsized rvalues it is enough
1930 // to check all temps, return slots and locals.
1931 if let None = self.reported_errors.replace((ty, span)) {
1932 let mut diag = struct_span_err!(
1936 "cannot move a value of type {0}: the size of {0} \
1937 cannot be statically determined",
1941 // While this is located in `nll::typeck` this error is not
1942 // an NLL error, it's a required check to prevent creation
1943 // of unsized rvalues in certain cases:
1944 // * operand of a box expression
1945 // * callee in a call expression
1951 fn aggregate_field_ty(
1953 ak: &AggregateKind<'tcx>,
1956 ) -> Result<Ty<'tcx>, FieldAccessError> {
1957 let tcx = self.tcx();
1960 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1961 let variant = &def.variants[variant_index];
1962 let adj_field_index = active_field_index.unwrap_or(field_index);
1963 if let Some(field) = variant.fields.get(adj_field_index) {
1964 Ok(self.normalize(field.ty(tcx, substs), location))
1966 Err(FieldAccessError::OutOfRange {
1967 field_count: variant.fields.len(),
1971 AggregateKind::Closure(def_id, substs) => {
1972 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1974 None => Err(FieldAccessError::OutOfRange {
1975 field_count: substs.upvar_tys(def_id, tcx).count(),
1979 AggregateKind::Generator(def_id, substs, _) => {
1980 // It doesn't make sense to look at a field beyond the prefix;
1981 // these require a variant index, and are not initialized in
1982 // aggregate rvalues.
1983 match substs.prefix_tys(def_id, tcx).nth(field_index) {
1985 None => Err(FieldAccessError::OutOfRange {
1986 field_count: substs.prefix_tys(def_id, tcx).count(),
1990 AggregateKind::Array(ty) => Ok(ty),
1991 AggregateKind::Tuple => {
1992 unreachable!("This should have been covered in check_rvalues");
1997 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1998 let tcx = self.tcx();
2001 Rvalue::Aggregate(ak, ops) => {
2002 self.check_aggregate_rvalue(body, rvalue, ak, ops, location)
2005 Rvalue::Repeat(operand, len) => if *len > 1 {
2006 if let Operand::Move(_) = operand {
2007 // While this is located in `nll::typeck` this error is not an NLL error, it's
2008 // a required check to make sure that repeated elements implement `Copy`.
2009 let span = body.source_info(location).span;
2010 let ty = operand.ty(body, tcx);
2011 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
2012 self.infcx.report_selection_error(
2013 &traits::Obligation::new(
2014 ObligationCause::new(
2016 self.tcx().hir().def_index_to_hir_id(self.mir_def_id.index),
2017 traits::ObligationCauseCode::RepeatVec,
2020 ty::Predicate::Trait(ty::Binder::bind(ty::TraitPredicate {
2021 trait_ref: ty::TraitRef::new(
2022 self.tcx().lang_items().copy_trait().unwrap(),
2023 tcx.mk_substs_trait(ty, &[]),
2027 &traits::SelectionError::Unimplemented,
2034 Rvalue::NullaryOp(_, ty) => {
2035 // Even with unsized locals cannot box an unsized value.
2036 if self.tcx().features().unsized_locals {
2037 let span = body.source_info(location).span;
2038 self.ensure_place_sized(ty, span);
2041 let trait_ref = ty::TraitRef {
2042 def_id: tcx.lang_items().sized_trait().unwrap(),
2043 substs: tcx.mk_substs_trait(ty, &[]),
2046 self.prove_trait_ref(
2048 location.to_locations(),
2049 ConstraintCategory::SizedBound,
2053 Rvalue::Cast(cast_kind, op, ty) => {
2055 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2056 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2058 // The type that we see in the fcx is like
2059 // `foo::<'a, 'b>`, where `foo` is the path to a
2060 // function definition. When we extract the
2061 // signature, it comes from the `fn_sig` query,
2062 // and hence may contain unnormalized results.
2063 let fn_sig = self.normalize(fn_sig, location);
2065 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2067 if let Err(terr) = self.eq_types(
2070 location.to_locations(),
2071 ConstraintCategory::Cast,
2076 "equating {:?} with {:?} yields {:?}",
2084 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2085 let sig = match op.ty(body, tcx).sty {
2086 ty::Closure(def_id, substs) => {
2087 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
2091 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2093 if let Err(terr) = self.eq_types(
2096 location.to_locations(),
2097 ConstraintCategory::Cast,
2102 "equating {:?} with {:?} yields {:?}",
2110 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2111 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2113 // The type that we see in the fcx is like
2114 // `foo::<'a, 'b>`, where `foo` is the path to a
2115 // function definition. When we extract the
2116 // signature, it comes from the `fn_sig` query,
2117 // and hence may contain unnormalized results.
2118 let fn_sig = self.normalize(fn_sig, location);
2120 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2122 if let Err(terr) = self.eq_types(
2125 location.to_locations(),
2126 ConstraintCategory::Cast,
2131 "equating {:?} with {:?} yields {:?}",
2139 CastKind::Pointer(PointerCast::Unsize) => {
2141 let trait_ref = ty::TraitRef {
2142 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2143 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2146 self.prove_trait_ref(
2148 location.to_locations(),
2149 ConstraintCategory::Cast,
2153 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2154 let ty_from = match op.ty(body, tcx).sty {
2155 ty::RawPtr(ty::TypeAndMut {
2157 mutbl: hir::MutMutable,
2163 "unexpected base type for cast {:?}",
2169 let ty_to = match ty.sty {
2170 ty::RawPtr(ty::TypeAndMut {
2172 mutbl: hir::MutImmutable,
2178 "unexpected target type for cast {:?}",
2184 if let Err(terr) = self.sub_types(
2187 location.to_locations(),
2188 ConstraintCategory::Cast,
2193 "relating {:?} with {:?} yields {:?}",
2202 if let ty::Ref(_, mut ty_from, _) = op.ty(body, tcx).sty {
2203 let (mut ty_to, mutability) = if let ty::RawPtr(ty::TypeAndMut {
2212 "invalid cast types {:?} -> {:?}",
2219 // Handle the direct cast from `&[T; N]` to `*const T` by unwrapping
2220 // any array we find.
2221 while let ty::Array(ty_elem_from, _) = ty_from.sty {
2222 ty_from = ty_elem_from;
2223 if let ty::Array(ty_elem_to, _) = ty_to.sty {
2230 if let hir::MutMutable = mutability {
2231 if let Err(terr) = self.eq_types(
2234 location.to_locations(),
2235 ConstraintCategory::Cast,
2240 "equating {:?} with {:?} yields {:?}",
2247 if let Err(terr) = self.sub_types(
2250 location.to_locations(),
2251 ConstraintCategory::Cast,
2256 "relating {:?} with {:?} yields {:?}",
2268 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2269 self.add_reborrow_constraint(body, location, region, borrowed_place);
2272 Rvalue::BinaryOp(BinOp::Eq, left, right)
2273 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2274 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2275 | Rvalue::BinaryOp(BinOp::Le, left, right)
2276 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2277 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2278 let ty_left = left.ty(body, tcx);
2279 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.sty {
2280 let ty_right = right.ty(body, tcx);
2281 let common_ty = self.infcx.next_ty_var(
2282 TypeVariableOrigin {
2283 kind: TypeVariableOriginKind::MiscVariable,
2284 span: body.source_info(location).span,
2290 location.to_locations(),
2291 ConstraintCategory::Boring
2292 ).unwrap_or_else(|err| {
2293 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2295 if let Err(terr) = self.sub_types(
2298 location.to_locations(),
2299 ConstraintCategory::Boring
2304 "unexpected comparison types {:?} and {:?} yields {:?}",
2315 | Rvalue::BinaryOp(..)
2316 | Rvalue::CheckedBinaryOp(..)
2317 | Rvalue::UnaryOp(..)
2318 | Rvalue::Discriminant(..) => {}
2322 /// If this rvalue supports a user-given type annotation, then
2323 /// extract and return it. This represents the final type of the
2324 /// rvalue and will be unified with the inferred type.
2325 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2328 | Rvalue::Repeat(..)
2332 | Rvalue::BinaryOp(..)
2333 | Rvalue::CheckedBinaryOp(..)
2334 | Rvalue::NullaryOp(..)
2335 | Rvalue::UnaryOp(..)
2336 | Rvalue::Discriminant(..) => None,
2338 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2339 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2340 AggregateKind::Array(_) => None,
2341 AggregateKind::Tuple => None,
2342 AggregateKind::Closure(_, _) => None,
2343 AggregateKind::Generator(_, _, _) => None,
2348 fn check_aggregate_rvalue(
2351 rvalue: &Rvalue<'tcx>,
2352 aggregate_kind: &AggregateKind<'tcx>,
2353 operands: &[Operand<'tcx>],
2356 let tcx = self.tcx();
2358 self.prove_aggregate_predicates(aggregate_kind, location);
2360 if *aggregate_kind == AggregateKind::Tuple {
2361 // tuple rvalue field type is always the type of the op. Nothing to check here.
2365 for (i, operand) in operands.iter().enumerate() {
2366 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2367 Ok(field_ty) => field_ty,
2368 Err(FieldAccessError::OutOfRange { field_count }) => {
2372 "accessed field #{} but variant only has {}",
2379 let operand_ty = operand.ty(body, tcx);
2381 if let Err(terr) = self.sub_types(
2384 location.to_locations(),
2385 ConstraintCategory::Boring,
2390 "{:?} is not a subtype of {:?}: {:?}",
2399 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2403 /// - `location`: the location `L` where the borrow expression occurs
2404 /// - `borrow_region`: the region `'a` associated with the borrow
2405 /// - `borrowed_place`: the place `P` being borrowed
2406 fn add_reborrow_constraint(
2410 borrow_region: ty::Region<'tcx>,
2411 borrowed_place: &Place<'tcx>,
2413 // These constraints are only meaningful during borrowck:
2414 let BorrowCheckContext {
2420 } = self.borrowck_context;
2422 // In Polonius mode, we also push a `borrow_region` fact
2423 // linking the loan to the region (in some cases, though,
2424 // there is no loan associated with this borrow expression --
2425 // that occurs when we are borrowing an unsafe place, for
2427 if let Some(all_facts) = all_facts {
2428 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2429 let region_vid = borrow_region.to_region_vid();
2430 all_facts.borrow_region.push((
2433 location_table.mid_index(location),
2438 // If we are reborrowing the referent of another reference, we
2439 // need to add outlives relationships. In a case like `&mut
2440 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2441 // need to ensure that `'b: 'a`.
2443 let mut borrowed_projection = &borrowed_place.projection;
2446 "add_reborrow_constraint({:?}, {:?}, {:?})",
2447 location, borrow_region, borrowed_place
2449 while let Some(box proj) = borrowed_projection {
2450 debug!("add_reborrow_constraint - iteration {:?}", borrowed_projection);
2453 ProjectionElem::Deref => {
2454 let tcx = self.infcx.tcx;
2455 let base_ty = Place::ty_from(&borrowed_place.base, &proj.base, body, tcx).ty;
2457 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2459 ty::Ref(ref_region, _, mutbl) => {
2460 constraints.outlives_constraints.push(OutlivesConstraint {
2461 sup: ref_region.to_region_vid(),
2462 sub: borrow_region.to_region_vid(),
2463 locations: location.to_locations(),
2464 category: ConstraintCategory::Boring,
2468 hir::Mutability::MutImmutable => {
2469 // Immutable reference. We don't need the base
2470 // to be valid for the entire lifetime of
2474 hir::Mutability::MutMutable => {
2475 // Mutable reference. We *do* need the base
2476 // to be valid, because after the base becomes
2477 // invalid, someone else can use our mutable deref.
2479 // This is in order to make the following function
2482 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2487 // As otherwise you could clone `&mut T` using the
2488 // following function:
2490 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2491 // let my_clone = unsafe_deref(&'a x);
2500 // deref of raw pointer, guaranteed to be valid
2503 ty::Adt(def, _) if def.is_box() => {
2504 // deref of `Box`, need the base to be valid - propagate
2506 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2509 ProjectionElem::Field(..)
2510 | ProjectionElem::Downcast(..)
2511 | ProjectionElem::Index(..)
2512 | ProjectionElem::ConstantIndex { .. }
2513 | ProjectionElem::Subslice { .. } => {
2514 // other field access
2518 // The "propagate" case. We need to check that our base is valid
2519 // for the borrow's lifetime.
2520 borrowed_projection = &proj.base;
2524 fn prove_aggregate_predicates(
2526 aggregate_kind: &AggregateKind<'tcx>,
2529 let tcx = self.tcx();
2532 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2533 aggregate_kind, location
2536 let instantiated_predicates = match aggregate_kind {
2537 AggregateKind::Adt(def, _, substs, _, _) => {
2538 tcx.predicates_of(def.did).instantiate(tcx, substs)
2541 // For closures, we have some **extra requirements** we
2543 // have to check. In particular, in their upvars and
2544 // signatures, closures often reference various regions
2545 // from the surrounding function -- we call those the
2546 // closure's free regions. When we borrow-check (and hence
2547 // region-check) closures, we may find that the closure
2548 // requires certain relationships between those free
2549 // regions. However, because those free regions refer to
2550 // portions of the CFG of their caller, the closure is not
2551 // in a position to verify those relationships. In that
2552 // case, the requirements get "propagated" to us, and so
2553 // we have to solve them here where we instantiate the
2556 // Despite the opacity of the previous parapgrah, this is
2557 // actually relatively easy to understand in terms of the
2558 // desugaring. A closure gets desugared to a struct, and
2559 // these extra requirements are basically like where
2560 // clauses on the struct.
2561 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2562 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2563 self.prove_closure_bounds(tcx, *def_id, substs, location)
2566 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2569 self.normalize_and_prove_instantiated_predicates(
2570 instantiated_predicates,
2571 location.to_locations(),
2575 fn prove_closure_bounds(
2579 substs: SubstsRef<'tcx>,
2581 ) -> ty::InstantiatedPredicates<'tcx> {
2582 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2583 let closure_constraints = QueryRegionConstraints {
2584 outlives: closure_region_requirements.apply_requirements(tcx, def_id, substs),
2586 // Presently, closures never propagate member
2587 // constraints to their parents -- they are enforced
2588 // locally. This is largely a non-issue as member
2589 // constraints only come from `-> impl Trait` and
2590 // friends which don't appear (thus far...) in
2592 member_constraints: vec![],
2595 let bounds_mapping = closure_constraints
2599 .filter_map(|(idx, constraint)| {
2600 let ty::OutlivesPredicate(k1, r2) =
2601 constraint.no_bound_vars().unwrap_or_else(|| {
2602 bug!("query_constraint {:?} contained bound vars", constraint,);
2606 UnpackedKind::Lifetime(r1) => {
2607 // constraint is r1: r2
2608 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2609 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2610 let outlives_requirements =
2611 &closure_region_requirements.outlives_requirements[idx];
2615 outlives_requirements.category,
2616 outlives_requirements.blame_span,
2620 UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2625 let existing = self.borrowck_context
2627 .closure_bounds_mapping
2628 .insert(location, bounds_mapping);
2631 "Multiple closures at the same location."
2634 self.push_region_constraints(
2635 location.to_locations(),
2636 ConstraintCategory::ClosureBounds,
2637 &closure_constraints,
2641 tcx.predicates_of(def_id).instantiate(tcx, substs)
2646 trait_ref: ty::TraitRef<'tcx>,
2647 locations: Locations,
2648 category: ConstraintCategory,
2650 self.prove_predicates(
2651 Some(ty::Predicate::Trait(
2652 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2659 fn normalize_and_prove_instantiated_predicates(
2661 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2662 locations: Locations,
2664 for predicate in instantiated_predicates.predicates {
2665 let predicate = self.normalize(predicate, locations);
2666 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2670 fn prove_predicates(
2672 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2673 locations: Locations,
2674 category: ConstraintCategory,
2676 for predicate in predicates {
2678 "prove_predicates(predicate={:?}, locations={:?})",
2679 predicate, locations,
2682 self.prove_predicate(predicate, locations, category);
2688 predicate: ty::Predicate<'tcx>,
2689 locations: Locations,
2690 category: ConstraintCategory,
2693 "prove_predicate(predicate={:?}, location={:?})",
2694 predicate, locations,
2697 let param_env = self.param_env;
2698 self.fully_perform_op(
2701 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2702 ).unwrap_or_else(|NoSolution| {
2703 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2707 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2708 self.last_span = body.span;
2709 debug!("run_on_mir: {:?}", body.span);
2711 for (local, local_decl) in body.local_decls.iter_enumerated() {
2712 self.check_local(body, local, local_decl);
2715 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2716 let mut location = Location {
2720 for stmt in &block_data.statements {
2721 if !stmt.source_info.span.is_dummy() {
2722 self.last_span = stmt.source_info.span;
2724 self.check_stmt(body, stmt, location);
2725 location.statement_index += 1;
2728 self.check_terminator(body, block_data.terminator(), location);
2729 self.check_iscleanup(body, block_data);
2733 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2735 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2737 debug!("normalize(value={:?}, location={:?})", value, location);
2738 let param_env = self.param_env;
2739 self.fully_perform_op(
2740 location.to_locations(),
2741 ConstraintCategory::Boring,
2742 param_env.and(type_op::normalize::Normalize::new(value)),
2743 ).unwrap_or_else(|NoSolution| {
2744 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2750 trait NormalizeLocation: fmt::Debug + Copy {
2751 fn to_locations(self) -> Locations;
2754 impl NormalizeLocation for Locations {
2755 fn to_locations(self) -> Locations {
2760 impl NormalizeLocation for Location {
2761 fn to_locations(self) -> Locations {
2762 Locations::Single(self)
2766 #[derive(Debug, Default)]
2767 struct ObligationAccumulator<'tcx> {
2768 obligations: PredicateObligations<'tcx>,
2771 impl<'tcx> ObligationAccumulator<'tcx> {
2772 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2773 let InferOk { value, obligations } = value;
2774 self.obligations.extend(obligations);
2778 fn into_vec(self) -> PredicateObligations<'tcx> {