1 //! This pass type-checks the MIR to ensure it is not broken.
3 use crate::borrow_check::borrow_set::BorrowSet;
4 use crate::borrow_check::location::LocationTable;
5 use crate::borrow_check::nll::constraints::{OutlivesConstraintSet, OutlivesConstraint};
6 use crate::borrow_check::nll::member_constraints::MemberConstraintSet;
7 use crate::borrow_check::nll::facts::AllFacts;
8 use crate::borrow_check::nll::region_infer::values::LivenessValues;
9 use crate::borrow_check::nll::region_infer::values::PlaceholderIndex;
10 use crate::borrow_check::nll::region_infer::values::PlaceholderIndices;
11 use crate::borrow_check::nll::region_infer::values::RegionValueElements;
12 use crate::borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
13 use crate::borrow_check::nll::renumber;
14 use crate::borrow_check::nll::type_check::free_region_relations::{
15 CreateResult, UniversalRegionRelations,
17 use crate::borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
18 use crate::borrow_check::nll::ToRegionVid;
19 use crate::dataflow::move_paths::MoveData;
20 use crate::dataflow::FlowAtLocation;
21 use crate::dataflow::MaybeInitializedPlaces;
24 use rustc::hir::def_id::DefId;
25 use rustc::infer::canonical::QueryRegionConstraints;
26 use rustc::infer::outlives::env::RegionBoundPairs;
27 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
28 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
29 use rustc::mir::interpret::{ConstValue, PanicMessage};
30 use rustc::mir::tcx::PlaceTy;
31 use rustc::mir::visit::{PlaceContext, Visitor, NonMutatingUseContext};
33 use rustc::traits::query::type_op;
34 use rustc::traits::query::type_op::custom::CustomTypeOp;
35 use rustc::traits::query::{Fallible, NoSolution};
36 use rustc::traits::{self, ObligationCause, PredicateObligations};
37 use rustc::ty::adjustment::{PointerCast};
38 use rustc::ty::fold::TypeFoldable;
39 use rustc::ty::subst::{Subst, SubstsRef, UnpackedKind, UserSubsts};
41 self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, UserType,
42 CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
43 UserTypeAnnotationIndex,
45 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
46 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
47 use rustc::ty::layout::VariantIdx;
49 use std::{fmt, iter, mem};
50 use syntax_pos::{Span, DUMMY_SP};
52 macro_rules! span_mirbug {
53 ($context:expr, $elem:expr, $($message:tt)*) => ({
54 $crate::borrow_check::nll::type_check::mirbug(
58 "broken MIR in {:?} ({:?}): {}",
61 format_args!($($message)*),
67 macro_rules! span_mirbug_and_err {
68 ($context:expr, $elem:expr, $($message:tt)*) => ({
70 span_mirbug!($context, $elem, $($message)*);
76 mod constraint_conversion;
77 pub mod free_region_relations;
82 /// Type checks the given `mir` in the context of the inference
83 /// context `infcx`. Returns any region constraints that have yet to
84 /// be proven. This result is includes liveness constraints that
85 /// ensure that regions appearing in the types of all local variables
86 /// are live at all points where that local variable may later be
89 /// This phase of type-check ought to be infallible -- this is because
90 /// the original, HIR-based type-check succeeded. So if any errors
91 /// occur here, we will get a `bug!` reported.
95 /// - `infcx` -- inference context to use
96 /// - `param_env` -- parameter environment to use for trait solving
97 /// - `mir` -- MIR to type-check
98 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
99 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
100 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
101 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
102 /// to outlive; should represent the fn body
103 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
104 /// the types of the input parameters found in the MIR itself will be equated with these
105 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
106 /// the type for the RETURN_PLACE will be equated with this
107 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
108 /// constraints for the regions in the types of variables
109 /// - `flow_inits` -- results of a maybe-init dataflow analysis
110 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
111 pub(crate) fn type_check<'tcx>(
112 infcx: &InferCtxt<'_, 'tcx>,
113 param_env: ty::ParamEnv<'tcx>,
116 universal_regions: &Rc<UniversalRegions<'tcx>>,
117 location_table: &LocationTable,
118 borrow_set: &BorrowSet<'tcx>,
119 all_facts: &mut Option<AllFacts>,
120 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'_, 'tcx>>,
121 move_data: &MoveData<'tcx>,
122 elements: &Rc<RegionValueElements>,
123 ) -> MirTypeckResults<'tcx> {
124 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
125 let mut constraints = MirTypeckRegionConstraints {
126 placeholder_indices: PlaceholderIndices::default(),
127 placeholder_index_to_region: IndexVec::default(),
128 liveness_constraints: LivenessValues::new(elements.clone()),
129 outlives_constraints: OutlivesConstraintSet::default(),
130 member_constraints: MemberConstraintSet::default(),
131 closure_bounds_mapping: Default::default(),
132 type_tests: Vec::default(),
136 universal_region_relations,
138 normalized_inputs_and_output,
139 } = free_region_relations::create(
142 Some(implicit_region_bound),
147 let mut borrowck_context = BorrowCheckContext {
152 constraints: &mut constraints,
161 implicit_region_bound,
162 &mut borrowck_context,
163 &universal_region_relations,
165 cx.equate_inputs_and_outputs(body, universal_regions, &normalized_inputs_and_output);
166 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
168 translate_outlives_facts(cx.borrowck_context);
174 universal_region_relations,
178 fn type_check_internal<'a, 'tcx, R>(
179 infcx: &'a InferCtxt<'a, 'tcx>,
181 param_env: ty::ParamEnv<'tcx>,
182 body: &'a Body<'tcx>,
183 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
184 implicit_region_bound: ty::Region<'tcx>,
185 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
186 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
187 mut extra: impl FnMut(&mut TypeChecker<'a, 'tcx>) -> R,
189 let mut checker = TypeChecker::new(
195 implicit_region_bound,
197 universal_region_relations,
199 let errors_reported = {
200 let mut verifier = TypeVerifier::new(&mut checker, body);
201 verifier.visit_body(body);
202 verifier.errors_reported
205 if !errors_reported {
206 // if verifier failed, don't do further checks to avoid ICEs
207 checker.typeck_mir(body);
213 fn translate_outlives_facts(cx: &mut BorrowCheckContext<'_, '_>) {
214 if let Some(facts) = cx.all_facts {
215 let location_table = cx.location_table;
218 .extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
219 |constraint: &OutlivesConstraint| {
220 if let Some(from_location) = constraint.locations.from_location() {
221 Either::Left(iter::once((
224 location_table.mid_index(from_location),
230 .map(move |location| (constraint.sup, constraint.sub, location)),
238 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
239 // We sometimes see MIR failures (notably predicate failures) due to
240 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
241 // to avoid reporting bugs in those cases.
242 tcx.sess.diagnostic().delay_span_bug(span, msg);
245 enum FieldAccessError {
246 OutOfRange { field_count: usize },
249 /// Verifies that MIR types are sane to not crash further checks.
251 /// The sanitize_XYZ methods here take an MIR object and compute its
252 /// type, calling `span_mirbug` and returning an error type if there
254 struct TypeVerifier<'a, 'b, 'tcx> {
255 cx: &'a mut TypeChecker<'b, 'tcx>,
256 body: &'b Body<'tcx>,
259 errors_reported: bool,
262 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
263 fn visit_span(&mut self, span: &Span) {
264 if !span.is_dummy() {
265 self.last_span = *span;
269 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
270 self.sanitize_place(place, location, context);
273 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
274 self.super_constant(constant, location);
275 self.sanitize_constant(constant, location);
276 self.sanitize_type(constant, constant.ty);
278 if let Some(annotation_index) = constant.user_ty {
279 if let Err(terr) = self.cx.relate_type_and_user_type(
281 ty::Variance::Invariant,
282 &UserTypeProjection { base: annotation_index, projs: vec![], },
283 location.to_locations(),
284 ConstraintCategory::Boring,
286 let annotation = &self.cx.user_type_annotations[annotation_index];
290 "bad constant user type {:?} vs {:?}: {:?}",
297 if let ConstValue::Unevaluated(def_id, substs) = constant.literal.val {
298 if let Err(terr) = self.cx.fully_perform_op(
299 location.to_locations(),
300 ConstraintCategory::Boring,
301 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
302 constant.ty, def_id, UserSubsts { substs, user_self_ty: None },
308 "bad constant type {:?} ({:?})",
314 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
315 let tcx = self.tcx();
317 let instantiated_predicates = tcx
318 .predicates_of(def_id)
319 .instantiate(tcx, substs);
320 self.cx.normalize_and_prove_instantiated_predicates(
321 instantiated_predicates,
322 location.to_locations(),
328 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
329 self.super_rvalue(rvalue, location);
330 let rval_ty = rvalue.ty(self.body, self.tcx());
331 self.sanitize_type(rvalue, rval_ty);
334 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
335 self.super_local_decl(local, local_decl);
336 self.sanitize_type(local_decl, local_decl.ty);
338 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
339 let ty = if !local_decl.is_nonref_binding() {
340 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
341 // reference so we can check the type annotation for the remaining type.
342 if let ty::Ref(_, rty, _) = local_decl.ty.sty {
345 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
351 if let Err(terr) = self.cx.relate_type_and_user_type(
353 ty::Variance::Invariant,
355 Locations::All(*span),
356 ConstraintCategory::TypeAnnotation,
361 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
371 fn visit_body(&mut self, body: &Body<'tcx>) {
372 self.sanitize_type(&"return type", body.return_ty());
373 for local_decl in &body.local_decls {
374 self.sanitize_type(local_decl, local_decl.ty);
376 if self.errors_reported {
379 self.super_body(body);
383 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
384 fn new(cx: &'a mut TypeChecker<'b, 'tcx>, body: &'b Body<'tcx>) -> Self {
387 mir_def_id: cx.mir_def_id,
389 last_span: body.span,
390 errors_reported: false,
394 fn tcx(&self) -> TyCtxt<'tcx> {
398 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
399 if ty.has_escaping_bound_vars() || ty.references_error() {
400 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
406 /// Checks that the constant's `ty` field matches up with what would be
407 /// expected from its literal. Unevaluated constants and well-formed
408 /// constraints are checked by `visit_constant`.
409 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
411 "sanitize_constant(constant={:?}, location={:?})",
415 let literal = constant.literal;
417 if let ConstValue::Unevaluated(..) = literal.val {
421 debug!("sanitize_constant: expected_ty={:?}", literal.ty);
423 if let Err(terr) = self.cx.eq_types(
426 location.to_locations(),
427 ConstraintCategory::Boring,
432 "constant {:?} should have type {:?} but has {:?} ({:?})",
441 /// Checks that the types internal to the `place` match up with
442 /// what would be expected.
447 context: PlaceContext,
449 debug!("sanitize_place: {:?}", place);
451 place.iterate(|place_base, place_projection| {
452 let mut place_ty = match place_base {
453 PlaceBase::Local(index) =>
454 PlaceTy::from_ty(self.body.local_decls[*index].ty),
455 PlaceBase::Static(box Static { kind, ty: sty }) => {
456 let sty = self.sanitize_type(place, sty);
458 |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
462 if let Err(terr) = verifier.cx.eq_types(
465 location.to_locations(),
466 ConstraintCategory::Boring,
471 "bad promoted type ({:?}: {:?}): {:?}",
479 StaticKind::Promoted(promoted) => {
480 if !self.errors_reported {
481 let promoted_body = &self.body.promoted[*promoted];
482 self.sanitize_promoted(promoted_body, location);
484 let promoted_ty = promoted_body.return_ty();
485 check_err(self, place, promoted_ty, sty);
488 StaticKind::Static(def_id) => {
489 let ty = self.tcx().type_of(*def_id);
490 let ty = self.cx.normalize(ty, location);
492 check_err(self, place, ty, sty);
495 PlaceTy::from_ty(sty)
499 // FIXME use place_projection.is_empty() when is available
500 if place.projection.is_none() {
501 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
502 let is_promoted = match place {
504 base: PlaceBase::Static(box Static {
505 kind: StaticKind::Promoted(_),
514 let tcx = self.tcx();
515 let trait_ref = ty::TraitRef {
516 def_id: tcx.lang_items().copy_trait().unwrap(),
517 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
520 // In order to have a Copy operand, the type T of the
521 // value must be Copy. Note that we prove that T: Copy,
522 // rather than using the `is_copy_modulo_regions`
523 // test. This is important because
524 // `is_copy_modulo_regions` ignores the resulting region
525 // obligations and assumes they pass. This can result in
526 // bounds from Copy impls being unsoundly ignored (e.g.,
527 // #29149). Note that we decide to use Copy before knowing
528 // whether the bounds fully apply: in effect, the rule is
529 // that if a value of some type could implement Copy, then
531 self.cx.prove_trait_ref(
533 location.to_locations(),
534 ConstraintCategory::CopyBound,
540 for proj in place_projection {
541 if place_ty.variant_index.is_none() {
542 if place_ty.ty.references_error() {
543 assert!(self.errors_reported);
544 return PlaceTy::from_ty(self.tcx().types.err);
547 place_ty = self.sanitize_projection(place_ty, &proj.elem, place, location)
554 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
555 // Determine the constraints from the promoted MIR by running the type
556 // checker on the promoted MIR, then transfer the constraints back to
557 // the main MIR, changing the locations to the provided location.
559 let parent_body = mem::replace(&mut self.body, promoted_body);
561 let all_facts = &mut None;
562 let mut constraints = Default::default();
563 let mut closure_bounds = Default::default();
564 // Don't try to add borrow_region facts for the promoted MIR
565 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
567 // Use a new sets of constraints and closure bounds so that we can
568 // modify their locations.
570 &mut self.cx.borrowck_context.constraints.outlives_constraints,
574 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
578 self.visit_body(promoted_body);
580 if !self.errors_reported {
581 // if verifier failed, don't do further checks to avoid ICEs
582 self.cx.typeck_mir(promoted_body);
585 self.body = parent_body;
586 // Merge the outlives constraints back in, at the given location.
587 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
589 &mut self.cx.borrowck_context.constraints.outlives_constraints,
593 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
597 let locations = location.to_locations();
598 for constraint in constraints.outlives().iter() {
599 let mut constraint = *constraint;
600 constraint.locations = locations;
601 if let ConstraintCategory::Return
602 | ConstraintCategory::UseAsConst
603 | ConstraintCategory::UseAsStatic = constraint.category
605 // "Returning" from a promoted is an assigment to a
606 // temporary from the user's point of view.
607 constraint.category = ConstraintCategory::Boring;
609 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
612 if !closure_bounds.is_empty() {
613 let combined_bounds_mapping = closure_bounds
615 .flat_map(|(_, value)| value)
617 let existing = self.cx.borrowck_context
619 .closure_bounds_mapping
620 .insert(location, combined_bounds_mapping);
623 "Multiple promoteds/closures at the same location."
628 fn sanitize_projection(
631 pi: &PlaceElem<'tcx>,
635 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
636 let tcx = self.tcx();
637 let base_ty = base.ty;
639 ProjectionElem::Deref => {
640 let deref_ty = base_ty.builtin_deref(true);
642 deref_ty.map(|t| t.ty).unwrap_or_else(|| {
643 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
647 ProjectionElem::Index(i) => {
648 let index_ty = Place::from(i).ty(self.body, tcx).ty;
649 if index_ty != tcx.types.usize {
651 span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
655 base_ty.builtin_index().unwrap_or_else(|| {
656 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
661 ProjectionElem::ConstantIndex { .. } => {
662 // consider verifying in-bounds
664 base_ty.builtin_index().unwrap_or_else(|| {
665 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
669 ProjectionElem::Subslice { from, to } => PlaceTy::from_ty(
671 ty::Array(inner, size) => {
672 let size = size.unwrap_usize(tcx);
673 let min_size = (from as u64) + (to as u64);
674 if let Some(rest_size) = size.checked_sub(min_size) {
675 tcx.mk_array(inner, rest_size)
677 span_mirbug_and_err!(
680 "taking too-small slice of {:?}",
685 ty::Slice(..) => base_ty,
686 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
689 ProjectionElem::Downcast(maybe_name, index) => match base_ty.sty {
690 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
691 if index.as_usize() >= adt_def.variants.len() {
693 span_mirbug_and_err!(
696 "cast to variant #{:?} but enum only has {:?}",
698 adt_def.variants.len()
704 variant_index: Some(index),
708 // We do not need to handle generators here, because this runs
709 // before the generator transform stage.
711 let ty = if let Some(name) = maybe_name {
712 span_mirbug_and_err!(
715 "can't downcast {:?} as {:?}",
720 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
725 ProjectionElem::Field(field, fty) => {
726 let fty = self.sanitize_type(place, fty);
727 match self.field_ty(place, base, field, location) {
728 Ok(ty) => if let Err(terr) = self.cx.eq_types(
731 location.to_locations(),
732 ConstraintCategory::Boring,
737 "bad field access ({:?}: {:?}): {:?}",
743 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
746 "accessed field #{} but variant only has {}",
751 PlaceTy::from_ty(fty)
756 fn error(&mut self) -> Ty<'tcx> {
757 self.errors_reported = true;
763 parent: &dyn fmt::Debug,
764 base_ty: PlaceTy<'tcx>,
767 ) -> Result<Ty<'tcx>, FieldAccessError> {
768 let tcx = self.tcx();
770 let (variant, substs) = match base_ty {
771 PlaceTy { ty, variant_index: Some(variant_index) } => match ty.sty {
772 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
773 ty::Generator(def_id, substs, _) => {
774 let mut variants = substs.state_tys(def_id, tcx);
775 let mut variant = match variants.nth(variant_index.into()) {
778 bug!("variant_index of generator out of range: {:?}/{:?}",
780 substs.state_tys(def_id, tcx).count())
783 return match variant.nth(field.index()) {
785 None => Err(FieldAccessError::OutOfRange {
786 field_count: variant.count(),
790 _ => bug!("can't have downcast of non-adt non-generator type"),
792 PlaceTy { ty, variant_index: None } => match ty.sty {
793 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
794 (&adt_def.variants[VariantIdx::new(0)], substs),
795 ty::Closure(def_id, substs) => {
796 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
798 None => Err(FieldAccessError::OutOfRange {
799 field_count: substs.upvar_tys(def_id, tcx).count(),
803 ty::Generator(def_id, substs, _) => {
804 // Only prefix fields (upvars and current state) are
805 // accessible without a variant index.
806 return match substs.prefix_tys(def_id, tcx).nth(field.index()) {
808 None => Err(FieldAccessError::OutOfRange {
809 field_count: substs.prefix_tys(def_id, tcx).count(),
814 return match tys.get(field.index()) {
815 Some(&ty) => Ok(ty.expect_ty()),
816 None => Err(FieldAccessError::OutOfRange {
817 field_count: tys.len(),
822 return Ok(span_mirbug_and_err!(
825 "can't project out of {:?}",
832 if let Some(field) = variant.fields.get(field.index()) {
833 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
835 Err(FieldAccessError::OutOfRange {
836 field_count: variant.fields.len(),
842 /// The MIR type checker. Visits the MIR and enforces all the
843 /// constraints needed for it to be valid and well-typed. Along the
844 /// way, it accrues region constraints -- these can later be used by
845 /// NLL region checking.
846 struct TypeChecker<'a, 'tcx> {
847 infcx: &'a InferCtxt<'a, 'tcx>,
848 param_env: ty::ParamEnv<'tcx>,
850 body: &'a Body<'tcx>,
851 /// User type annotations are shared between the main MIR and the MIR of
852 /// all of the promoted items.
853 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
855 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
856 implicit_region_bound: ty::Region<'tcx>,
857 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
858 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
859 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
862 struct BorrowCheckContext<'a, 'tcx> {
863 universal_regions: &'a UniversalRegions<'tcx>,
864 location_table: &'a LocationTable,
865 all_facts: &'a mut Option<AllFacts>,
866 borrow_set: &'a BorrowSet<'tcx>,
867 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
870 crate struct MirTypeckResults<'tcx> {
871 crate constraints: MirTypeckRegionConstraints<'tcx>,
872 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
875 /// A collection of region constraints that must be satisfied for the
876 /// program to be considered well-typed.
877 crate struct MirTypeckRegionConstraints<'tcx> {
878 /// Maps from a `ty::Placeholder` to the corresponding
879 /// `PlaceholderIndex` bit that we will use for it.
881 /// To keep everything in sync, do not insert this set
882 /// directly. Instead, use the `placeholder_region` helper.
883 crate placeholder_indices: PlaceholderIndices,
885 /// Each time we add a placeholder to `placeholder_indices`, we
886 /// also create a corresponding "representative" region vid for
887 /// that wraps it. This vector tracks those. This way, when we
888 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
889 /// the same underlying `RegionVid`.
890 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
892 /// In general, the type-checker is not responsible for enforcing
893 /// liveness constraints; this job falls to the region inferencer,
894 /// which performs a liveness analysis. However, in some limited
895 /// cases, the MIR type-checker creates temporary regions that do
896 /// not otherwise appear in the MIR -- in particular, the
897 /// late-bound regions that it instantiates at call-sites -- and
898 /// hence it must report on their liveness constraints.
899 crate liveness_constraints: LivenessValues<RegionVid>,
901 crate outlives_constraints: OutlivesConstraintSet,
903 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
905 crate closure_bounds_mapping:
906 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
908 crate type_tests: Vec<TypeTest<'tcx>>,
911 impl MirTypeckRegionConstraints<'tcx> {
912 fn placeholder_region(
914 infcx: &InferCtxt<'_, 'tcx>,
915 placeholder: ty::PlaceholderRegion,
916 ) -> ty::Region<'tcx> {
917 let placeholder_index = self.placeholder_indices.insert(placeholder);
918 match self.placeholder_index_to_region.get(placeholder_index) {
921 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
922 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
923 self.placeholder_index_to_region.push(region);
930 /// The `Locations` type summarizes *where* region constraints are
931 /// required to hold. Normally, this is at a particular point which
932 /// created the obligation, but for constraints that the user gave, we
933 /// want the constraint to hold at all points.
934 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
936 /// Indicates that a type constraint should always be true. This
937 /// is particularly important in the new borrowck analysis for
938 /// things like the type of the return slot. Consider this
942 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
944 /// return &y; // error
948 /// Here, we wind up with the signature from the return type being
949 /// something like `&'1 u32` where `'1` is a universal region. But
950 /// the type of the return slot `_0` is something like `&'2 u32`
951 /// where `'2` is an existential region variable. The type checker
952 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
953 /// older NLL analysis, we required this only at the entry point
954 /// to the function. By the nature of the constraints, this wound
955 /// up propagating to all points reachable from start (because
956 /// `'1` -- as a universal region -- is live everywhere). In the
957 /// newer analysis, though, this doesn't work: `_0` is considered
958 /// dead at the start (it has no usable value) and hence this type
959 /// equality is basically a no-op. Then, later on, when we do `_0
960 /// = &'3 y`, that region `'3` never winds up related to the
961 /// universal region `'1` and hence no error occurs. Therefore, we
962 /// use Locations::All instead, which ensures that the `'1` and
963 /// `'2` are equal everything. We also use this for other
964 /// user-given type annotations; e.g., if the user wrote `let mut
965 /// x: &'static u32 = ...`, we would ensure that all values
966 /// assigned to `x` are of `'static` lifetime.
968 /// The span points to the place the constraint arose. For example,
969 /// it points to the type in a user-given type annotation. If
970 /// there's no sensible span then it's DUMMY_SP.
973 /// An outlives constraint that only has to hold at a single location,
974 /// usually it represents a point where references flow from one spot to
975 /// another (e.g., `x = y`)
980 pub fn from_location(&self) -> Option<Location> {
982 Locations::All(_) => None,
983 Locations::Single(from_location) => Some(*from_location),
987 /// Gets a span representing the location.
988 pub fn span(&self, body: &Body<'_>) -> Span {
990 Locations::All(span) => *span,
991 Locations::Single(l) => body.source_info(*l).span,
996 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
998 infcx: &'a InferCtxt<'a, 'tcx>,
999 body: &'a Body<'tcx>,
1001 param_env: ty::ParamEnv<'tcx>,
1002 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1003 implicit_region_bound: ty::Region<'tcx>,
1004 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1005 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
1007 let mut checker = Self {
1009 last_span: DUMMY_SP,
1012 user_type_annotations: &body.user_type_annotations,
1015 implicit_region_bound,
1017 reported_errors: Default::default(),
1018 universal_region_relations,
1020 checker.check_user_type_annotations();
1024 /// Equate the inferred type and the annotated type for user type annotations
1025 fn check_user_type_annotations(&mut self) {
1027 "check_user_type_annotations: user_type_annotations={:?}",
1028 self.user_type_annotations
1030 for user_annotation in self.user_type_annotations {
1031 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1032 let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
1036 UserType::Ty(mut ty) => {
1037 ty = self.normalize(ty, Locations::All(span));
1039 if let Err(terr) = self.eq_types(
1042 Locations::All(span),
1043 ConstraintCategory::BoringNoLocation,
1048 "bad user type ({:?} = {:?}): {:?}",
1055 self.prove_predicate(
1056 ty::Predicate::WellFormed(inferred_ty),
1057 Locations::All(span),
1058 ConstraintCategory::TypeAnnotation,
1061 UserType::TypeOf(def_id, user_substs) => {
1062 if let Err(terr) = self.fully_perform_op(
1063 Locations::All(span),
1064 ConstraintCategory::BoringNoLocation,
1065 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1066 inferred_ty, def_id, user_substs,
1072 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1084 /// Given some operation `op` that manipulates types, proves
1085 /// predicates, or otherwise uses the inference context, executes
1086 /// `op` and then executes all the further obligations that `op`
1087 /// returns. This will yield a set of outlives constraints amongst
1088 /// regions which are extracted and stored as having occurred at
1091 /// **Any `rustc::infer` operations that might generate region
1092 /// constraints should occur within this method so that those
1093 /// constraints can be properly localized!**
1094 fn fully_perform_op<R>(
1096 locations: Locations,
1097 category: ConstraintCategory,
1098 op: impl type_op::TypeOp<'tcx, Output = R>,
1100 let (r, opt_data) = op.fully_perform(self.infcx)?;
1102 if let Some(data) = &opt_data {
1103 self.push_region_constraints(locations, category, data);
1109 fn push_region_constraints(
1111 locations: Locations,
1112 category: ConstraintCategory,
1113 data: &QueryRegionConstraints<'tcx>,
1116 "push_region_constraints: constraints generated at {:?} are {:#?}",
1120 constraint_conversion::ConstraintConversion::new(
1122 self.borrowck_context.universal_regions,
1123 self.region_bound_pairs,
1124 Some(self.implicit_region_bound),
1128 &mut self.borrowck_context.constraints,
1129 ).convert_all(data);
1132 /// Convenient wrapper around `relate_tys::relate_types` -- see
1133 /// that fn for docs.
1139 locations: Locations,
1140 category: ConstraintCategory,
1142 relate_tys::relate_types(
1149 Some(self.borrowck_context),
1157 locations: Locations,
1158 category: ConstraintCategory,
1160 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1163 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1164 /// variables in `sub` with their inferred definitions and try
1165 /// again. This is used for opaque types in places (e.g., `let x:
1166 /// impl Foo = ..`).
1167 fn sub_types_or_anon(
1171 locations: Locations,
1172 category: ConstraintCategory,
1174 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1175 if let ty::Opaque(..) = sup.sty {
1176 // When you have `let x: impl Foo = ...` in a closure,
1177 // the resulting inferend values are stored with the
1178 // def-id of the base function.
1179 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1180 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1192 locations: Locations,
1193 category: ConstraintCategory,
1195 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1198 fn relate_type_and_user_type(
1202 user_ty: &UserTypeProjection,
1203 locations: Locations,
1204 category: ConstraintCategory,
1207 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1208 a, v, user_ty, locations,
1211 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1212 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1214 let tcx = self.infcx.tcx;
1216 for proj in &user_ty.projs {
1217 let projected_ty = curr_projected_ty.projection_ty_core(tcx, proj, |this, field, &()| {
1218 let ty = this.field_ty(tcx, field);
1219 self.normalize(ty, locations)
1221 curr_projected_ty = projected_ty;
1223 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1224 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1226 let ty = curr_projected_ty.ty;
1227 self.relate_types(a, v, ty, locations, category)?;
1232 fn eq_opaque_type_and_type(
1234 revealed_ty: Ty<'tcx>,
1236 anon_owner_def_id: DefId,
1237 locations: Locations,
1238 category: ConstraintCategory,
1241 "eq_opaque_type_and_type( \
1244 revealed_ty, anon_ty
1246 let infcx = self.infcx;
1247 let tcx = infcx.tcx;
1248 let param_env = self.param_env;
1249 let body = self.body;
1250 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1251 let opaque_type_map = self.fully_perform_op(
1256 let mut obligations = ObligationAccumulator::default();
1258 let dummy_body_id = ObligationCause::dummy().body_id;
1259 let (output_ty, opaque_type_map) =
1260 obligations.add(infcx.instantiate_opaque_types(
1265 locations.span(body),
1268 "eq_opaque_type_and_type: \
1269 instantiated output_ty={:?} \
1270 opaque_type_map={:#?} \
1272 output_ty, opaque_type_map, revealed_ty
1274 obligations.add(infcx
1275 .at(&ObligationCause::dummy(), param_env)
1276 .eq(output_ty, revealed_ty)?);
1278 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1279 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1280 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1281 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1282 let concrete_is_opaque = infcx
1283 .resolve_vars_if_possible(&opaque_decl.concrete_ty).is_impl_trait();
1286 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?} \
1287 concrete_is_opaque={}",
1288 opaque_decl.concrete_ty,
1289 infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty),
1294 // concrete_is_opaque is `true` when we're using an existential
1295 // type without 'revealing' it. For example, code like this:
1297 // existential type Foo: Debug;
1298 // fn foo1() -> Foo { ... }
1299 // fn foo2() -> Foo { foo1() }
1301 // In `foo2`, we're not revealing the type of `Foo` - we're
1302 // just treating it as the opaque type.
1304 // When this occurs, we do *not* want to try to equate
1305 // the concrete type with the underlying defining type
1306 // of the existential type - this will always fail, since
1307 // the defining type of an existential type is always
1308 // some other type (e.g. not itself)
1309 // Essentially, none of the normal obligations apply here -
1310 // we're just passing around some unknown opaque type,
1311 // without actually looking at the underlying type it
1312 // gets 'revealed' into
1314 if !concrete_is_opaque {
1315 obligations.add(infcx
1316 .at(&ObligationCause::dummy(), param_env)
1317 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1321 debug!("eq_opaque_type_and_type: equated");
1324 value: Some(opaque_type_map),
1325 obligations: obligations.into_vec(),
1328 || "input_output".to_string(),
1332 let universal_region_relations = self.universal_region_relations;
1334 // Finally, if we instantiated the anon types successfully, we
1335 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1336 // prove that `T: Iterator` where `T` is the type we
1337 // instantiated it with).
1338 if let Some(opaque_type_map) = opaque_type_map {
1339 for (opaque_def_id, opaque_decl) in opaque_type_map {
1340 self.fully_perform_op(
1342 ConstraintCategory::OpaqueType,
1345 infcx.constrain_opaque_type(
1348 universal_region_relations,
1352 obligations: vec![],
1355 || "opaque_type_map".to_string(),
1363 fn tcx(&self) -> TyCtxt<'tcx> {
1367 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1368 debug!("check_stmt: {:?}", stmt);
1369 let tcx = self.tcx();
1371 StatementKind::Assign(ref place, ref rv) => {
1372 // Assignments to temporaries are not "interesting";
1373 // they are not caused by the user, but rather artifacts
1374 // of lowering. Assignments to other sorts of places *are* interesting
1376 let category = match *place {
1378 base: PlaceBase::Local(RETURN_PLACE),
1380 } => if let BorrowCheckContext {
1383 defining_ty: DefiningTy::Const(def_id, _),
1387 } = self.borrowck_context {
1388 if tcx.is_static(*def_id) {
1389 ConstraintCategory::UseAsStatic
1391 ConstraintCategory::UseAsConst
1394 ConstraintCategory::Return
1397 base: PlaceBase::Local(l),
1399 } if !body.local_decls[l].is_user_variable.is_some() => {
1400 ConstraintCategory::Boring
1402 _ => ConstraintCategory::Assignment,
1405 let place_ty = place.ty(body, tcx).ty;
1406 let rv_ty = rv.ty(body, tcx);
1408 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1413 "bad assignment ({:?} = {:?}): {:?}",
1420 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1421 if let Err(terr) = self.relate_type_and_user_type(
1423 ty::Variance::Invariant,
1424 &UserTypeProjection { base: annotation_index, projs: vec![], },
1425 location.to_locations(),
1426 ConstraintCategory::Boring,
1428 let annotation = &self.user_type_annotations[annotation_index];
1432 "bad user type on rvalue ({:?} = {:?}): {:?}",
1440 self.check_rvalue(body, rv, location);
1441 if !self.tcx().features().unsized_locals {
1442 let trait_ref = ty::TraitRef {
1443 def_id: tcx.lang_items().sized_trait().unwrap(),
1444 substs: tcx.mk_substs_trait(place_ty, &[]),
1446 self.prove_trait_ref(
1448 location.to_locations(),
1449 ConstraintCategory::SizedBound,
1453 StatementKind::SetDiscriminant {
1457 let place_type = place.ty(body, tcx).ty;
1458 let adt = match place_type.sty {
1459 ty::Adt(adt, _) if adt.is_enum() => adt,
1462 stmt.source_info.span,
1463 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1469 if variant_index.as_usize() >= adt.variants.len() {
1471 stmt.source_info.span,
1472 "bad set discriminant ({:?} = {:?}): value of of range",
1478 StatementKind::AscribeUserType(ref place, variance, box ref projection) => {
1479 let place_ty = place.ty(body, tcx).ty;
1480 if let Err(terr) = self.relate_type_and_user_type(
1484 Locations::All(stmt.source_info.span),
1485 ConstraintCategory::TypeAnnotation,
1487 let annotation = &self.user_type_annotations[projection.base];
1491 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1499 StatementKind::FakeRead(..)
1500 | StatementKind::StorageLive(..)
1501 | StatementKind::StorageDead(..)
1502 | StatementKind::InlineAsm { .. }
1503 | StatementKind::Retag { .. }
1504 | StatementKind::Nop => {}
1508 fn check_terminator(
1511 term: &Terminator<'tcx>,
1512 term_location: Location,
1514 debug!("check_terminator: {:?}", term);
1515 let tcx = self.tcx();
1517 TerminatorKind::Goto { .. }
1518 | TerminatorKind::Resume
1519 | TerminatorKind::Abort
1520 | TerminatorKind::Return
1521 | TerminatorKind::GeneratorDrop
1522 | TerminatorKind::Unreachable
1523 | TerminatorKind::Drop { .. }
1524 | TerminatorKind::FalseEdges { .. }
1525 | TerminatorKind::FalseUnwind { .. } => {
1526 // no checks needed for these
1529 TerminatorKind::DropAndReplace {
1535 let place_ty = location.ty(body, tcx).ty;
1536 let rv_ty = value.ty(body, tcx);
1538 let locations = term_location.to_locations();
1540 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1545 "bad DropAndReplace ({:?} = {:?}): {:?}",
1552 TerminatorKind::SwitchInt {
1557 let discr_ty = discr.ty(body, tcx);
1558 if let Err(terr) = self.sub_types(
1561 term_location.to_locations(),
1562 ConstraintCategory::Assignment,
1567 "bad SwitchInt ({:?} on {:?}): {:?}",
1573 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1574 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1576 // FIXME: check the values
1578 TerminatorKind::Call {
1585 let func_ty = func.ty(body, tcx);
1586 debug!("check_terminator: call, func_ty={:?}", func_ty);
1587 let sig = match func_ty.sty {
1588 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1590 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1594 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1595 term.source_info.span,
1596 LateBoundRegionConversionTime::FnCall,
1599 let sig = self.normalize(sig, term_location);
1600 self.check_call_dest(body, term, &sig, destination, term_location);
1602 self.prove_predicates(
1603 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1604 term_location.to_locations(),
1605 ConstraintCategory::Boring,
1608 // The ordinary liveness rules will ensure that all
1609 // regions in the type of the callee are live here. We
1610 // then further constrain the late-bound regions that
1611 // were instantiated at the call site to be live as
1612 // well. The resulting is that all the input (and
1613 // output) types in the signature must be live, since
1614 // all the inputs that fed into it were live.
1615 for &late_bound_region in map.values() {
1616 let region_vid = self.borrowck_context
1618 .to_region_vid(late_bound_region);
1619 self.borrowck_context
1621 .liveness_constraints
1622 .add_element(region_vid, term_location);
1625 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1627 TerminatorKind::Assert {
1628 ref cond, ref msg, ..
1630 let cond_ty = cond.ty(body, tcx);
1631 if cond_ty != tcx.types.bool {
1632 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1635 if let PanicMessage::BoundsCheck { ref len, ref index } = *msg {
1636 if len.ty(body, tcx) != tcx.types.usize {
1637 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1639 if index.ty(body, tcx) != tcx.types.usize {
1640 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1644 TerminatorKind::Yield { ref value, .. } => {
1645 let value_ty = value.ty(body, tcx);
1646 match body.yield_ty {
1647 None => span_mirbug!(self, term, "yield in non-generator"),
1649 if let Err(terr) = self.sub_types(
1652 term_location.to_locations(),
1653 ConstraintCategory::Yield,
1658 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1673 term: &Terminator<'tcx>,
1674 sig: &ty::FnSig<'tcx>,
1675 destination: &Option<(Place<'tcx>, BasicBlock)>,
1676 term_location: Location,
1678 let tcx = self.tcx();
1679 match *destination {
1680 Some((ref dest, _target_block)) => {
1681 let dest_ty = dest.ty(body, tcx).ty;
1682 let category = match *dest {
1684 base: PlaceBase::Local(RETURN_PLACE),
1687 if let BorrowCheckContext {
1690 defining_ty: DefiningTy::Const(def_id, _),
1694 } = self.borrowck_context
1696 if tcx.is_static(*def_id) {
1697 ConstraintCategory::UseAsStatic
1699 ConstraintCategory::UseAsConst
1702 ConstraintCategory::Return
1706 base: PlaceBase::Local(l),
1708 } if !body.local_decls[l].is_user_variable.is_some() => {
1709 ConstraintCategory::Boring
1711 _ => ConstraintCategory::Assignment,
1714 let locations = term_location.to_locations();
1717 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1722 "call dest mismatch ({:?} <- {:?}): {:?}",
1729 // When `#![feature(unsized_locals)]` is not enabled,
1730 // this check is done at `check_local`.
1731 if self.tcx().features().unsized_locals {
1732 let span = term.source_info.span;
1733 self.ensure_place_sized(dest_ty, span);
1737 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1738 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1744 fn check_call_inputs(
1747 term: &Terminator<'tcx>,
1748 sig: &ty::FnSig<'tcx>,
1749 args: &[Operand<'tcx>],
1750 term_location: Location,
1751 from_hir_call: bool,
1753 debug!("check_call_inputs({:?}, {:?})", sig, args);
1754 // Do not count the `VaListImpl` argument as a "true" argument to
1755 // a C-variadic function.
1756 let inputs = if sig.c_variadic {
1757 &sig.inputs()[..sig.inputs().len() - 1]
1761 if args.len() < inputs.len() || (args.len() > inputs.len() && !sig.c_variadic) {
1762 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1764 for (n, (fn_arg, op_arg)) in inputs.iter().zip(args).enumerate() {
1765 let op_arg_ty = op_arg.ty(body, self.tcx());
1766 let category = if from_hir_call {
1767 ConstraintCategory::CallArgument
1769 ConstraintCategory::Boring
1772 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1777 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1787 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1788 let is_cleanup = block_data.is_cleanup;
1789 self.last_span = block_data.terminator().source_info.span;
1790 match block_data.terminator().kind {
1791 TerminatorKind::Goto { target } => {
1792 self.assert_iscleanup(body, block_data, target, is_cleanup)
1794 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1795 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1797 TerminatorKind::Resume => if !is_cleanup {
1798 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1800 TerminatorKind::Abort => if !is_cleanup {
1801 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1803 TerminatorKind::Return => if is_cleanup {
1804 span_mirbug!(self, block_data, "return on cleanup block")
1806 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1807 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1809 TerminatorKind::Yield { resume, drop, .. } => {
1811 span_mirbug!(self, block_data, "yield in cleanup block")
1813 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1814 if let Some(drop) = drop {
1815 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1818 TerminatorKind::Unreachable => {}
1819 TerminatorKind::Drop { target, unwind, .. }
1820 | TerminatorKind::DropAndReplace { target, unwind, .. }
1821 | TerminatorKind::Assert {
1826 self.assert_iscleanup(body, block_data, target, is_cleanup);
1827 if let Some(unwind) = unwind {
1829 span_mirbug!(self, block_data, "unwind on cleanup block")
1831 self.assert_iscleanup(body, block_data, unwind, true);
1834 TerminatorKind::Call {
1839 if let &Some((_, target)) = destination {
1840 self.assert_iscleanup(body, block_data, target, is_cleanup);
1842 if let Some(cleanup) = cleanup {
1844 span_mirbug!(self, block_data, "cleanup on cleanup block")
1846 self.assert_iscleanup(body, block_data, cleanup, true);
1849 TerminatorKind::FalseEdges {
1853 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1854 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1856 TerminatorKind::FalseUnwind {
1860 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1861 if let Some(unwind) = unwind {
1866 "cleanup in cleanup block via false unwind"
1869 self.assert_iscleanup(body, block_data, unwind, true);
1875 fn assert_iscleanup(
1878 ctxt: &dyn fmt::Debug,
1882 if body[bb].is_cleanup != iscleanuppad {
1886 "cleanuppad mismatch: {:?} should be {:?}",
1893 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1894 match body.local_kind(local) {
1895 LocalKind::ReturnPointer | LocalKind::Arg => {
1896 // return values of normal functions are required to be
1897 // sized by typeck, but return values of ADT constructors are
1898 // not because we don't include a `Self: Sized` bounds on them.
1900 // Unbound parts of arguments were never required to be Sized
1901 // - maybe we should make that a warning.
1904 LocalKind::Var | LocalKind::Temp => {}
1907 // When `#![feature(unsized_locals)]` is enabled, only function calls
1908 // and nullary ops are checked in `check_call_dest`.
1909 if !self.tcx().features().unsized_locals {
1910 let span = local_decl.source_info.span;
1911 let ty = local_decl.ty;
1912 self.ensure_place_sized(ty, span);
1916 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1917 let tcx = self.tcx();
1919 // Erase the regions from `ty` to get a global type. The
1920 // `Sized` bound in no way depends on precise regions, so this
1921 // shouldn't affect `is_sized`.
1922 let gcx = tcx.global_tcx();
1923 let erased_ty = tcx.erase_regions(&ty);
1924 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1925 // in current MIR construction, all non-control-flow rvalue
1926 // expressions evaluate through `as_temp` or `into` a return
1927 // slot or local, so to find all unsized rvalues it is enough
1928 // to check all temps, return slots and locals.
1929 if let None = self.reported_errors.replace((ty, span)) {
1930 let mut diag = struct_span_err!(
1934 "cannot move a value of type {0}: the size of {0} \
1935 cannot be statically determined",
1939 // While this is located in `nll::typeck` this error is not
1940 // an NLL error, it's a required check to prevent creation
1941 // of unsized rvalues in certain cases:
1942 // * operand of a box expression
1943 // * callee in a call expression
1949 fn aggregate_field_ty(
1951 ak: &AggregateKind<'tcx>,
1954 ) -> Result<Ty<'tcx>, FieldAccessError> {
1955 let tcx = self.tcx();
1958 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1959 let variant = &def.variants[variant_index];
1960 let adj_field_index = active_field_index.unwrap_or(field_index);
1961 if let Some(field) = variant.fields.get(adj_field_index) {
1962 Ok(self.normalize(field.ty(tcx, substs), location))
1964 Err(FieldAccessError::OutOfRange {
1965 field_count: variant.fields.len(),
1969 AggregateKind::Closure(def_id, substs) => {
1970 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1972 None => Err(FieldAccessError::OutOfRange {
1973 field_count: substs.upvar_tys(def_id, tcx).count(),
1977 AggregateKind::Generator(def_id, substs, _) => {
1978 // It doesn't make sense to look at a field beyond the prefix;
1979 // these require a variant index, and are not initialized in
1980 // aggregate rvalues.
1981 match substs.prefix_tys(def_id, tcx).nth(field_index) {
1983 None => Err(FieldAccessError::OutOfRange {
1984 field_count: substs.prefix_tys(def_id, tcx).count(),
1988 AggregateKind::Array(ty) => Ok(ty),
1989 AggregateKind::Tuple => {
1990 unreachable!("This should have been covered in check_rvalues");
1995 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1996 let tcx = self.tcx();
1999 Rvalue::Aggregate(ak, ops) => {
2000 self.check_aggregate_rvalue(body, rvalue, ak, ops, location)
2003 Rvalue::Repeat(operand, len) => if *len > 1 {
2004 if let Operand::Move(_) = operand {
2005 // While this is located in `nll::typeck` this error is not an NLL error, it's
2006 // a required check to make sure that repeated elements implement `Copy`.
2007 let span = body.source_info(location).span;
2008 let ty = operand.ty(body, tcx);
2009 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
2010 self.infcx.report_selection_error(
2011 &traits::Obligation::new(
2012 ObligationCause::new(
2014 self.tcx().hir().def_index_to_hir_id(self.mir_def_id.index),
2015 traits::ObligationCauseCode::RepeatVec,
2018 ty::Predicate::Trait(ty::Binder::bind(ty::TraitPredicate {
2019 trait_ref: ty::TraitRef::new(
2020 self.tcx().lang_items().copy_trait().unwrap(),
2021 tcx.mk_substs_trait(ty, &[]),
2025 &traits::SelectionError::Unimplemented,
2032 Rvalue::NullaryOp(_, ty) => {
2033 // Even with unsized locals cannot box an unsized value.
2034 if self.tcx().features().unsized_locals {
2035 let span = body.source_info(location).span;
2036 self.ensure_place_sized(ty, span);
2039 let trait_ref = ty::TraitRef {
2040 def_id: tcx.lang_items().sized_trait().unwrap(),
2041 substs: tcx.mk_substs_trait(ty, &[]),
2044 self.prove_trait_ref(
2046 location.to_locations(),
2047 ConstraintCategory::SizedBound,
2051 Rvalue::Cast(cast_kind, op, ty) => {
2053 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2054 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2056 // The type that we see in the fcx is like
2057 // `foo::<'a, 'b>`, where `foo` is the path to a
2058 // function definition. When we extract the
2059 // signature, it comes from the `fn_sig` query,
2060 // and hence may contain unnormalized results.
2061 let fn_sig = self.normalize(fn_sig, location);
2063 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2065 if let Err(terr) = self.eq_types(
2068 location.to_locations(),
2069 ConstraintCategory::Cast,
2074 "equating {:?} with {:?} yields {:?}",
2082 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2083 let sig = match op.ty(body, tcx).sty {
2084 ty::Closure(def_id, substs) => {
2085 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
2089 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2091 if let Err(terr) = self.eq_types(
2094 location.to_locations(),
2095 ConstraintCategory::Cast,
2100 "equating {:?} with {:?} yields {:?}",
2108 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2109 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2111 // The type that we see in the fcx is like
2112 // `foo::<'a, 'b>`, where `foo` is the path to a
2113 // function definition. When we extract the
2114 // signature, it comes from the `fn_sig` query,
2115 // and hence may contain unnormalized results.
2116 let fn_sig = self.normalize(fn_sig, location);
2118 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2120 if let Err(terr) = self.eq_types(
2123 location.to_locations(),
2124 ConstraintCategory::Cast,
2129 "equating {:?} with {:?} yields {:?}",
2137 CastKind::Pointer(PointerCast::Unsize) => {
2139 let trait_ref = ty::TraitRef {
2140 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2141 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2144 self.prove_trait_ref(
2146 location.to_locations(),
2147 ConstraintCategory::Cast,
2151 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2152 let ty_from = match op.ty(body, tcx).sty {
2153 ty::RawPtr(ty::TypeAndMut {
2155 mutbl: hir::MutMutable,
2161 "unexpected base type for cast {:?}",
2167 let ty_to = match ty.sty {
2168 ty::RawPtr(ty::TypeAndMut {
2170 mutbl: hir::MutImmutable,
2176 "unexpected target type for cast {:?}",
2182 if let Err(terr) = self.sub_types(
2185 location.to_locations(),
2186 ConstraintCategory::Cast,
2191 "relating {:?} with {:?} yields {:?}",
2200 if let ty::Ref(_, mut ty_from, _) = op.ty(body, tcx).sty {
2201 let (mut ty_to, mutability) = if let ty::RawPtr(ty::TypeAndMut {
2210 "invalid cast types {:?} -> {:?}",
2217 // Handle the direct cast from `&[T; N]` to `*const T` by unwrapping
2218 // any array we find.
2219 while let ty::Array(ty_elem_from, _) = ty_from.sty {
2220 ty_from = ty_elem_from;
2221 if let ty::Array(ty_elem_to, _) = ty_to.sty {
2228 if let hir::MutMutable = mutability {
2229 if let Err(terr) = self.eq_types(
2232 location.to_locations(),
2233 ConstraintCategory::Cast,
2238 "equating {:?} with {:?} yields {:?}",
2245 if let Err(terr) = self.sub_types(
2248 location.to_locations(),
2249 ConstraintCategory::Cast,
2254 "relating {:?} with {:?} yields {:?}",
2266 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2267 self.add_reborrow_constraint(body, location, region, borrowed_place);
2270 Rvalue::BinaryOp(BinOp::Eq, left, right)
2271 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2272 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2273 | Rvalue::BinaryOp(BinOp::Le, left, right)
2274 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2275 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2276 let ty_left = left.ty(body, tcx);
2277 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.sty {
2278 let ty_right = right.ty(body, tcx);
2279 let common_ty = self.infcx.next_ty_var(
2280 TypeVariableOrigin {
2281 kind: TypeVariableOriginKind::MiscVariable,
2282 span: body.source_info(location).span,
2288 location.to_locations(),
2289 ConstraintCategory::Boring
2290 ).unwrap_or_else(|err| {
2291 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2293 if let Err(terr) = self.sub_types(
2296 location.to_locations(),
2297 ConstraintCategory::Boring
2302 "unexpected comparison types {:?} and {:?} yields {:?}",
2313 | Rvalue::BinaryOp(..)
2314 | Rvalue::CheckedBinaryOp(..)
2315 | Rvalue::UnaryOp(..)
2316 | Rvalue::Discriminant(..) => {}
2320 /// If this rvalue supports a user-given type annotation, then
2321 /// extract and return it. This represents the final type of the
2322 /// rvalue and will be unified with the inferred type.
2323 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2326 | Rvalue::Repeat(..)
2330 | Rvalue::BinaryOp(..)
2331 | Rvalue::CheckedBinaryOp(..)
2332 | Rvalue::NullaryOp(..)
2333 | Rvalue::UnaryOp(..)
2334 | Rvalue::Discriminant(..) => None,
2336 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2337 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2338 AggregateKind::Array(_) => None,
2339 AggregateKind::Tuple => None,
2340 AggregateKind::Closure(_, _) => None,
2341 AggregateKind::Generator(_, _, _) => None,
2346 fn check_aggregate_rvalue(
2349 rvalue: &Rvalue<'tcx>,
2350 aggregate_kind: &AggregateKind<'tcx>,
2351 operands: &[Operand<'tcx>],
2354 let tcx = self.tcx();
2356 self.prove_aggregate_predicates(aggregate_kind, location);
2358 if *aggregate_kind == AggregateKind::Tuple {
2359 // tuple rvalue field type is always the type of the op. Nothing to check here.
2363 for (i, operand) in operands.iter().enumerate() {
2364 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2365 Ok(field_ty) => field_ty,
2366 Err(FieldAccessError::OutOfRange { field_count }) => {
2370 "accessed field #{} but variant only has {}",
2377 let operand_ty = operand.ty(body, tcx);
2379 if let Err(terr) = self.sub_types(
2382 location.to_locations(),
2383 ConstraintCategory::Boring,
2388 "{:?} is not a subtype of {:?}: {:?}",
2397 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2401 /// - `location`: the location `L` where the borrow expression occurs
2402 /// - `borrow_region`: the region `'a` associated with the borrow
2403 /// - `borrowed_place`: the place `P` being borrowed
2404 fn add_reborrow_constraint(
2408 borrow_region: ty::Region<'tcx>,
2409 borrowed_place: &Place<'tcx>,
2411 // These constraints are only meaningful during borrowck:
2412 let BorrowCheckContext {
2418 } = self.borrowck_context;
2420 // In Polonius mode, we also push a `borrow_region` fact
2421 // linking the loan to the region (in some cases, though,
2422 // there is no loan associated with this borrow expression --
2423 // that occurs when we are borrowing an unsafe place, for
2425 if let Some(all_facts) = all_facts {
2426 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2427 let region_vid = borrow_region.to_region_vid();
2428 all_facts.borrow_region.push((
2431 location_table.mid_index(location),
2436 // If we are reborrowing the referent of another reference, we
2437 // need to add outlives relationships. In a case like `&mut
2438 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2439 // need to ensure that `'b: 'a`.
2441 let mut borrowed_projection = &borrowed_place.projection;
2444 "add_reborrow_constraint({:?}, {:?}, {:?})",
2445 location, borrow_region, borrowed_place
2447 while let Some(box proj) = borrowed_projection {
2448 debug!("add_reborrow_constraint - iteration {:?}", borrowed_projection);
2451 ProjectionElem::Deref => {
2452 let tcx = self.infcx.tcx;
2453 let base_ty = Place::ty_from(&borrowed_place.base, &proj.base, body, tcx).ty;
2455 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2457 ty::Ref(ref_region, _, mutbl) => {
2458 constraints.outlives_constraints.push(OutlivesConstraint {
2459 sup: ref_region.to_region_vid(),
2460 sub: borrow_region.to_region_vid(),
2461 locations: location.to_locations(),
2462 category: ConstraintCategory::Boring,
2466 hir::Mutability::MutImmutable => {
2467 // Immutable reference. We don't need the base
2468 // to be valid for the entire lifetime of
2472 hir::Mutability::MutMutable => {
2473 // Mutable reference. We *do* need the base
2474 // to be valid, because after the base becomes
2475 // invalid, someone else can use our mutable deref.
2477 // This is in order to make the following function
2480 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2485 // As otherwise you could clone `&mut T` using the
2486 // following function:
2488 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2489 // let my_clone = unsafe_deref(&'a x);
2498 // deref of raw pointer, guaranteed to be valid
2501 ty::Adt(def, _) if def.is_box() => {
2502 // deref of `Box`, need the base to be valid - propagate
2504 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2507 ProjectionElem::Field(..)
2508 | ProjectionElem::Downcast(..)
2509 | ProjectionElem::Index(..)
2510 | ProjectionElem::ConstantIndex { .. }
2511 | ProjectionElem::Subslice { .. } => {
2512 // other field access
2516 // The "propagate" case. We need to check that our base is valid
2517 // for the borrow's lifetime.
2518 borrowed_projection = &proj.base;
2522 fn prove_aggregate_predicates(
2524 aggregate_kind: &AggregateKind<'tcx>,
2527 let tcx = self.tcx();
2530 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2531 aggregate_kind, location
2534 let instantiated_predicates = match aggregate_kind {
2535 AggregateKind::Adt(def, _, substs, _, _) => {
2536 tcx.predicates_of(def.did).instantiate(tcx, substs)
2539 // For closures, we have some **extra requirements** we
2541 // have to check. In particular, in their upvars and
2542 // signatures, closures often reference various regions
2543 // from the surrounding function -- we call those the
2544 // closure's free regions. When we borrow-check (and hence
2545 // region-check) closures, we may find that the closure
2546 // requires certain relationships between those free
2547 // regions. However, because those free regions refer to
2548 // portions of the CFG of their caller, the closure is not
2549 // in a position to verify those relationships. In that
2550 // case, the requirements get "propagated" to us, and so
2551 // we have to solve them here where we instantiate the
2554 // Despite the opacity of the previous parapgrah, this is
2555 // actually relatively easy to understand in terms of the
2556 // desugaring. A closure gets desugared to a struct, and
2557 // these extra requirements are basically like where
2558 // clauses on the struct.
2559 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2560 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2561 self.prove_closure_bounds(tcx, *def_id, substs, location)
2564 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2567 self.normalize_and_prove_instantiated_predicates(
2568 instantiated_predicates,
2569 location.to_locations(),
2573 fn prove_closure_bounds(
2577 substs: SubstsRef<'tcx>,
2579 ) -> ty::InstantiatedPredicates<'tcx> {
2580 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2581 let closure_constraints = QueryRegionConstraints {
2582 outlives: closure_region_requirements.apply_requirements(tcx, def_id, substs),
2584 // Presently, closures never propagate member
2585 // constraints to their parents -- they are enforced
2586 // locally. This is largely a non-issue as member
2587 // constraints only come from `-> impl Trait` and
2588 // friends which don't appear (thus far...) in
2590 member_constraints: vec![],
2593 let bounds_mapping = closure_constraints
2597 .filter_map(|(idx, constraint)| {
2598 let ty::OutlivesPredicate(k1, r2) =
2599 constraint.no_bound_vars().unwrap_or_else(|| {
2600 bug!("query_constraint {:?} contained bound vars", constraint,);
2604 UnpackedKind::Lifetime(r1) => {
2605 // constraint is r1: r2
2606 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2607 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2608 let outlives_requirements =
2609 &closure_region_requirements.outlives_requirements[idx];
2613 outlives_requirements.category,
2614 outlives_requirements.blame_span,
2618 UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2623 let existing = self.borrowck_context
2625 .closure_bounds_mapping
2626 .insert(location, bounds_mapping);
2629 "Multiple closures at the same location."
2632 self.push_region_constraints(
2633 location.to_locations(),
2634 ConstraintCategory::ClosureBounds,
2635 &closure_constraints,
2639 tcx.predicates_of(def_id).instantiate(tcx, substs)
2644 trait_ref: ty::TraitRef<'tcx>,
2645 locations: Locations,
2646 category: ConstraintCategory,
2648 self.prove_predicates(
2649 Some(ty::Predicate::Trait(
2650 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2657 fn normalize_and_prove_instantiated_predicates(
2659 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2660 locations: Locations,
2662 for predicate in instantiated_predicates.predicates {
2663 let predicate = self.normalize(predicate, locations);
2664 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2668 fn prove_predicates(
2670 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2671 locations: Locations,
2672 category: ConstraintCategory,
2674 for predicate in predicates {
2676 "prove_predicates(predicate={:?}, locations={:?})",
2677 predicate, locations,
2680 self.prove_predicate(predicate, locations, category);
2686 predicate: ty::Predicate<'tcx>,
2687 locations: Locations,
2688 category: ConstraintCategory,
2691 "prove_predicate(predicate={:?}, location={:?})",
2692 predicate, locations,
2695 let param_env = self.param_env;
2696 self.fully_perform_op(
2699 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2700 ).unwrap_or_else(|NoSolution| {
2701 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2705 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2706 self.last_span = body.span;
2707 debug!("run_on_mir: {:?}", body.span);
2709 for (local, local_decl) in body.local_decls.iter_enumerated() {
2710 self.check_local(body, local, local_decl);
2713 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2714 let mut location = Location {
2718 for stmt in &block_data.statements {
2719 if !stmt.source_info.span.is_dummy() {
2720 self.last_span = stmt.source_info.span;
2722 self.check_stmt(body, stmt, location);
2723 location.statement_index += 1;
2726 self.check_terminator(body, block_data.terminator(), location);
2727 self.check_iscleanup(body, block_data);
2731 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2733 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2735 debug!("normalize(value={:?}, location={:?})", value, location);
2736 let param_env = self.param_env;
2737 self.fully_perform_op(
2738 location.to_locations(),
2739 ConstraintCategory::Boring,
2740 param_env.and(type_op::normalize::Normalize::new(value)),
2741 ).unwrap_or_else(|NoSolution| {
2742 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2748 trait NormalizeLocation: fmt::Debug + Copy {
2749 fn to_locations(self) -> Locations;
2752 impl NormalizeLocation for Locations {
2753 fn to_locations(self) -> Locations {
2758 impl NormalizeLocation for Location {
2759 fn to_locations(self) -> Locations {
2760 Locations::Single(self)
2764 #[derive(Debug, Default)]
2765 struct ObligationAccumulator<'tcx> {
2766 obligations: PredicateObligations<'tcx>,
2769 impl<'tcx> ObligationAccumulator<'tcx> {
2770 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2771 let InferOk { value, obligations } = value;
2772 self.obligations.extend(obligations);
2776 fn into_vec(self) -> PredicateObligations<'tcx> {