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, PanicInfo};
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.eval_usize(tcx, self.cx.param_env);
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(
1221 |this, field, &()| {
1222 let ty = this.field_ty(tcx, field);
1223 self.normalize(ty, locations)
1226 curr_projected_ty = projected_ty;
1228 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1229 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1231 let ty = curr_projected_ty.ty;
1232 self.relate_types(a, v, ty, locations, category)?;
1237 fn eq_opaque_type_and_type(
1239 revealed_ty: Ty<'tcx>,
1241 anon_owner_def_id: DefId,
1242 locations: Locations,
1243 category: ConstraintCategory,
1246 "eq_opaque_type_and_type( \
1249 revealed_ty, anon_ty
1251 let infcx = self.infcx;
1252 let tcx = infcx.tcx;
1253 let param_env = self.param_env;
1254 let body = self.body;
1255 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1256 let opaque_type_map = self.fully_perform_op(
1261 let mut obligations = ObligationAccumulator::default();
1263 let dummy_body_id = ObligationCause::dummy().body_id;
1264 let (output_ty, opaque_type_map) =
1265 obligations.add(infcx.instantiate_opaque_types(
1270 locations.span(body),
1273 "eq_opaque_type_and_type: \
1274 instantiated output_ty={:?} \
1275 opaque_type_map={:#?} \
1277 output_ty, opaque_type_map, revealed_ty
1279 obligations.add(infcx
1280 .at(&ObligationCause::dummy(), param_env)
1281 .eq(output_ty, revealed_ty)?);
1283 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1284 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1285 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1286 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1287 let concrete_is_opaque = infcx
1288 .resolve_vars_if_possible(&opaque_decl.concrete_ty).is_impl_trait();
1291 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?} \
1292 concrete_is_opaque={}",
1293 opaque_decl.concrete_ty,
1294 infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty),
1299 // concrete_is_opaque is `true` when we're using an opaque `impl Trait`
1300 // type without 'revealing' it. For example, code like this:
1302 // type Foo = impl Debug;
1303 // fn foo1() -> Foo { ... }
1304 // fn foo2() -> Foo { foo1() }
1306 // In `foo2`, we're not revealing the type of `Foo` - we're
1307 // just treating it as the opaque type.
1309 // When this occurs, we do *not* want to try to equate
1310 // the concrete type with the underlying defining type
1311 // of the opaque type - this will always fail, since
1312 // the defining type of an opaque type is always
1313 // some other type (e.g. not itself)
1314 // Essentially, none of the normal obligations apply here -
1315 // we're just passing around some unknown opaque type,
1316 // without actually looking at the underlying type it
1317 // gets 'revealed' into
1319 if !concrete_is_opaque {
1320 obligations.add(infcx
1321 .at(&ObligationCause::dummy(), param_env)
1322 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1326 debug!("eq_opaque_type_and_type: equated");
1329 value: Some(opaque_type_map),
1330 obligations: obligations.into_vec(),
1333 || "input_output".to_string(),
1337 let universal_region_relations = self.universal_region_relations;
1339 // Finally, if we instantiated the anon types successfully, we
1340 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1341 // prove that `T: Iterator` where `T` is the type we
1342 // instantiated it with).
1343 if let Some(opaque_type_map) = opaque_type_map {
1344 for (opaque_def_id, opaque_decl) in opaque_type_map {
1345 self.fully_perform_op(
1347 ConstraintCategory::OpaqueType,
1350 infcx.constrain_opaque_type(
1353 universal_region_relations,
1357 obligations: vec![],
1360 || "opaque_type_map".to_string(),
1368 fn tcx(&self) -> TyCtxt<'tcx> {
1372 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1373 debug!("check_stmt: {:?}", stmt);
1374 let tcx = self.tcx();
1376 StatementKind::Assign(ref place, ref rv) => {
1377 // Assignments to temporaries are not "interesting";
1378 // they are not caused by the user, but rather artifacts
1379 // of lowering. Assignments to other sorts of places *are* interesting
1381 let category = match *place {
1383 base: PlaceBase::Local(RETURN_PLACE),
1385 } => if let BorrowCheckContext {
1388 defining_ty: DefiningTy::Const(def_id, _),
1392 } = self.borrowck_context {
1393 if tcx.is_static(*def_id) {
1394 ConstraintCategory::UseAsStatic
1396 ConstraintCategory::UseAsConst
1399 ConstraintCategory::Return
1402 base: PlaceBase::Local(l),
1404 } if !body.local_decls[l].is_user_variable.is_some() => {
1405 ConstraintCategory::Boring
1407 _ => ConstraintCategory::Assignment,
1410 let place_ty = place.ty(body, tcx).ty;
1411 let rv_ty = rv.ty(body, tcx);
1413 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1418 "bad assignment ({:?} = {:?}): {:?}",
1425 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1426 if let Err(terr) = self.relate_type_and_user_type(
1428 ty::Variance::Invariant,
1429 &UserTypeProjection { base: annotation_index, projs: vec![], },
1430 location.to_locations(),
1431 ConstraintCategory::Boring,
1433 let annotation = &self.user_type_annotations[annotation_index];
1437 "bad user type on rvalue ({:?} = {:?}): {:?}",
1445 self.check_rvalue(body, rv, location);
1446 if !self.tcx().features().unsized_locals {
1447 let trait_ref = ty::TraitRef {
1448 def_id: tcx.lang_items().sized_trait().unwrap(),
1449 substs: tcx.mk_substs_trait(place_ty, &[]),
1451 self.prove_trait_ref(
1453 location.to_locations(),
1454 ConstraintCategory::SizedBound,
1458 StatementKind::SetDiscriminant {
1462 let place_type = place.ty(body, tcx).ty;
1463 let adt = match place_type.sty {
1464 ty::Adt(adt, _) if adt.is_enum() => adt,
1467 stmt.source_info.span,
1468 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1474 if variant_index.as_usize() >= adt.variants.len() {
1476 stmt.source_info.span,
1477 "bad set discriminant ({:?} = {:?}): value of of range",
1483 StatementKind::AscribeUserType(ref place, variance, box ref projection) => {
1484 let place_ty = place.ty(body, tcx).ty;
1485 if let Err(terr) = self.relate_type_and_user_type(
1489 Locations::All(stmt.source_info.span),
1490 ConstraintCategory::TypeAnnotation,
1492 let annotation = &self.user_type_annotations[projection.base];
1496 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1504 StatementKind::FakeRead(..)
1505 | StatementKind::StorageLive(..)
1506 | StatementKind::StorageDead(..)
1507 | StatementKind::InlineAsm { .. }
1508 | StatementKind::Retag { .. }
1509 | StatementKind::Nop => {}
1513 fn check_terminator(
1516 term: &Terminator<'tcx>,
1517 term_location: Location,
1519 debug!("check_terminator: {:?}", term);
1520 let tcx = self.tcx();
1522 TerminatorKind::Goto { .. }
1523 | TerminatorKind::Resume
1524 | TerminatorKind::Abort
1525 | TerminatorKind::Return
1526 | TerminatorKind::GeneratorDrop
1527 | TerminatorKind::Unreachable
1528 | TerminatorKind::Drop { .. }
1529 | TerminatorKind::FalseEdges { .. }
1530 | TerminatorKind::FalseUnwind { .. } => {
1531 // no checks needed for these
1534 TerminatorKind::DropAndReplace {
1540 let place_ty = location.ty(body, tcx).ty;
1541 let rv_ty = value.ty(body, tcx);
1543 let locations = term_location.to_locations();
1545 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1550 "bad DropAndReplace ({:?} = {:?}): {:?}",
1557 TerminatorKind::SwitchInt {
1562 let discr_ty = discr.ty(body, tcx);
1563 if let Err(terr) = self.sub_types(
1566 term_location.to_locations(),
1567 ConstraintCategory::Assignment,
1572 "bad SwitchInt ({:?} on {:?}): {:?}",
1578 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1579 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1581 // FIXME: check the values
1583 TerminatorKind::Call {
1590 let func_ty = func.ty(body, tcx);
1591 debug!("check_terminator: call, func_ty={:?}", func_ty);
1592 let sig = match func_ty.sty {
1593 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1595 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1599 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1600 term.source_info.span,
1601 LateBoundRegionConversionTime::FnCall,
1604 let sig = self.normalize(sig, term_location);
1605 self.check_call_dest(body, term, &sig, destination, term_location);
1607 self.prove_predicates(
1608 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1609 term_location.to_locations(),
1610 ConstraintCategory::Boring,
1613 // The ordinary liveness rules will ensure that all
1614 // regions in the type of the callee are live here. We
1615 // then further constrain the late-bound regions that
1616 // were instantiated at the call site to be live as
1617 // well. The resulting is that all the input (and
1618 // output) types in the signature must be live, since
1619 // all the inputs that fed into it were live.
1620 for &late_bound_region in map.values() {
1621 let region_vid = self.borrowck_context
1623 .to_region_vid(late_bound_region);
1624 self.borrowck_context
1626 .liveness_constraints
1627 .add_element(region_vid, term_location);
1630 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1632 TerminatorKind::Assert {
1633 ref cond, ref msg, ..
1635 let cond_ty = cond.ty(body, tcx);
1636 if cond_ty != tcx.types.bool {
1637 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1640 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
1641 if len.ty(body, tcx) != tcx.types.usize {
1642 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1644 if index.ty(body, tcx) != tcx.types.usize {
1645 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1649 TerminatorKind::Yield { ref value, .. } => {
1650 let value_ty = value.ty(body, tcx);
1651 match body.yield_ty {
1652 None => span_mirbug!(self, term, "yield in non-generator"),
1654 if let Err(terr) = self.sub_types(
1657 term_location.to_locations(),
1658 ConstraintCategory::Yield,
1663 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1678 term: &Terminator<'tcx>,
1679 sig: &ty::FnSig<'tcx>,
1680 destination: &Option<(Place<'tcx>, BasicBlock)>,
1681 term_location: Location,
1683 let tcx = self.tcx();
1684 match *destination {
1685 Some((ref dest, _target_block)) => {
1686 let dest_ty = dest.ty(body, tcx).ty;
1687 let category = match *dest {
1689 base: PlaceBase::Local(RETURN_PLACE),
1692 if let BorrowCheckContext {
1695 defining_ty: DefiningTy::Const(def_id, _),
1699 } = self.borrowck_context
1701 if tcx.is_static(*def_id) {
1702 ConstraintCategory::UseAsStatic
1704 ConstraintCategory::UseAsConst
1707 ConstraintCategory::Return
1711 base: PlaceBase::Local(l),
1713 } if !body.local_decls[l].is_user_variable.is_some() => {
1714 ConstraintCategory::Boring
1716 _ => ConstraintCategory::Assignment,
1719 let locations = term_location.to_locations();
1722 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1727 "call dest mismatch ({:?} <- {:?}): {:?}",
1734 // When `#![feature(unsized_locals)]` is not enabled,
1735 // this check is done at `check_local`.
1736 if self.tcx().features().unsized_locals {
1737 let span = term.source_info.span;
1738 self.ensure_place_sized(dest_ty, span);
1742 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1743 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1749 fn check_call_inputs(
1752 term: &Terminator<'tcx>,
1753 sig: &ty::FnSig<'tcx>,
1754 args: &[Operand<'tcx>],
1755 term_location: Location,
1756 from_hir_call: bool,
1758 debug!("check_call_inputs({:?}, {:?})", sig, args);
1759 // Do not count the `VaListImpl` argument as a "true" argument to
1760 // a C-variadic function.
1761 let inputs = if sig.c_variadic {
1762 &sig.inputs()[..sig.inputs().len() - 1]
1766 if args.len() < inputs.len() || (args.len() > inputs.len() && !sig.c_variadic) {
1767 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1769 for (n, (fn_arg, op_arg)) in inputs.iter().zip(args).enumerate() {
1770 let op_arg_ty = op_arg.ty(body, self.tcx());
1771 let category = if from_hir_call {
1772 ConstraintCategory::CallArgument
1774 ConstraintCategory::Boring
1777 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1782 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1792 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1793 let is_cleanup = block_data.is_cleanup;
1794 self.last_span = block_data.terminator().source_info.span;
1795 match block_data.terminator().kind {
1796 TerminatorKind::Goto { target } => {
1797 self.assert_iscleanup(body, block_data, target, is_cleanup)
1799 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1800 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1802 TerminatorKind::Resume => if !is_cleanup {
1803 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1805 TerminatorKind::Abort => if !is_cleanup {
1806 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1808 TerminatorKind::Return => if is_cleanup {
1809 span_mirbug!(self, block_data, "return on cleanup block")
1811 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1812 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1814 TerminatorKind::Yield { resume, drop, .. } => {
1816 span_mirbug!(self, block_data, "yield in cleanup block")
1818 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1819 if let Some(drop) = drop {
1820 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1823 TerminatorKind::Unreachable => {}
1824 TerminatorKind::Drop { target, unwind, .. }
1825 | TerminatorKind::DropAndReplace { target, unwind, .. }
1826 | TerminatorKind::Assert {
1831 self.assert_iscleanup(body, block_data, target, is_cleanup);
1832 if let Some(unwind) = unwind {
1834 span_mirbug!(self, block_data, "unwind on cleanup block")
1836 self.assert_iscleanup(body, block_data, unwind, true);
1839 TerminatorKind::Call {
1844 if let &Some((_, target)) = destination {
1845 self.assert_iscleanup(body, block_data, target, is_cleanup);
1847 if let Some(cleanup) = cleanup {
1849 span_mirbug!(self, block_data, "cleanup on cleanup block")
1851 self.assert_iscleanup(body, block_data, cleanup, true);
1854 TerminatorKind::FalseEdges {
1858 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1859 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1861 TerminatorKind::FalseUnwind {
1865 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1866 if let Some(unwind) = unwind {
1871 "cleanup in cleanup block via false unwind"
1874 self.assert_iscleanup(body, block_data, unwind, true);
1880 fn assert_iscleanup(
1883 ctxt: &dyn fmt::Debug,
1887 if body[bb].is_cleanup != iscleanuppad {
1891 "cleanuppad mismatch: {:?} should be {:?}",
1898 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1899 match body.local_kind(local) {
1900 LocalKind::ReturnPointer | LocalKind::Arg => {
1901 // return values of normal functions are required to be
1902 // sized by typeck, but return values of ADT constructors are
1903 // not because we don't include a `Self: Sized` bounds on them.
1905 // Unbound parts of arguments were never required to be Sized
1906 // - maybe we should make that a warning.
1909 LocalKind::Var | LocalKind::Temp => {}
1912 // When `#![feature(unsized_locals)]` is enabled, only function calls
1913 // and nullary ops are checked in `check_call_dest`.
1914 if !self.tcx().features().unsized_locals {
1915 let span = local_decl.source_info.span;
1916 let ty = local_decl.ty;
1917 self.ensure_place_sized(ty, span);
1921 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1922 let tcx = self.tcx();
1924 // Erase the regions from `ty` to get a global type. The
1925 // `Sized` bound in no way depends on precise regions, so this
1926 // shouldn't affect `is_sized`.
1927 let gcx = tcx.global_tcx();
1928 let erased_ty = tcx.erase_regions(&ty);
1929 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1930 // in current MIR construction, all non-control-flow rvalue
1931 // expressions evaluate through `as_temp` or `into` a return
1932 // slot or local, so to find all unsized rvalues it is enough
1933 // to check all temps, return slots and locals.
1934 if let None = self.reported_errors.replace((ty, span)) {
1935 let mut diag = struct_span_err!(
1939 "cannot move a value of type {0}: the size of {0} \
1940 cannot be statically determined",
1944 // While this is located in `nll::typeck` this error is not
1945 // an NLL error, it's a required check to prevent creation
1946 // of unsized rvalues in certain cases:
1947 // * operand of a box expression
1948 // * callee in a call expression
1954 fn aggregate_field_ty(
1956 ak: &AggregateKind<'tcx>,
1959 ) -> Result<Ty<'tcx>, FieldAccessError> {
1960 let tcx = self.tcx();
1963 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1964 let variant = &def.variants[variant_index];
1965 let adj_field_index = active_field_index.unwrap_or(field_index);
1966 if let Some(field) = variant.fields.get(adj_field_index) {
1967 Ok(self.normalize(field.ty(tcx, substs), location))
1969 Err(FieldAccessError::OutOfRange {
1970 field_count: variant.fields.len(),
1974 AggregateKind::Closure(def_id, substs) => {
1975 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1977 None => Err(FieldAccessError::OutOfRange {
1978 field_count: substs.upvar_tys(def_id, tcx).count(),
1982 AggregateKind::Generator(def_id, substs, _) => {
1983 // It doesn't make sense to look at a field beyond the prefix;
1984 // these require a variant index, and are not initialized in
1985 // aggregate rvalues.
1986 match substs.prefix_tys(def_id, tcx).nth(field_index) {
1988 None => Err(FieldAccessError::OutOfRange {
1989 field_count: substs.prefix_tys(def_id, tcx).count(),
1993 AggregateKind::Array(ty) => Ok(ty),
1994 AggregateKind::Tuple => {
1995 unreachable!("This should have been covered in check_rvalues");
2000 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
2001 let tcx = self.tcx();
2004 Rvalue::Aggregate(ak, ops) => {
2005 self.check_aggregate_rvalue(body, rvalue, ak, ops, location)
2008 Rvalue::Repeat(operand, len) => if *len > 1 {
2009 if let Operand::Move(_) = operand {
2010 // While this is located in `nll::typeck` this error is not an NLL error, it's
2011 // a required check to make sure that repeated elements implement `Copy`.
2012 let span = body.source_info(location).span;
2013 let ty = operand.ty(body, tcx);
2014 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
2015 self.infcx.report_selection_error(
2016 &traits::Obligation::new(
2017 ObligationCause::new(
2019 self.tcx().hir().def_index_to_hir_id(self.mir_def_id.index),
2020 traits::ObligationCauseCode::RepeatVec,
2023 ty::Predicate::Trait(ty::Binder::bind(ty::TraitPredicate {
2024 trait_ref: ty::TraitRef::new(
2025 self.tcx().lang_items().copy_trait().unwrap(),
2026 tcx.mk_substs_trait(ty, &[]),
2030 &traits::SelectionError::Unimplemented,
2037 Rvalue::NullaryOp(_, ty) => {
2038 // Even with unsized locals cannot box an unsized value.
2039 if self.tcx().features().unsized_locals {
2040 let span = body.source_info(location).span;
2041 self.ensure_place_sized(ty, span);
2044 let trait_ref = ty::TraitRef {
2045 def_id: tcx.lang_items().sized_trait().unwrap(),
2046 substs: tcx.mk_substs_trait(ty, &[]),
2049 self.prove_trait_ref(
2051 location.to_locations(),
2052 ConstraintCategory::SizedBound,
2056 Rvalue::Cast(cast_kind, op, ty) => {
2058 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2059 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2061 // The type that we see in the fcx is like
2062 // `foo::<'a, 'b>`, where `foo` is the path to a
2063 // function definition. When we extract the
2064 // signature, it comes from the `fn_sig` query,
2065 // and hence may contain unnormalized results.
2066 let fn_sig = self.normalize(fn_sig, location);
2068 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2070 if let Err(terr) = self.eq_types(
2073 location.to_locations(),
2074 ConstraintCategory::Cast,
2079 "equating {:?} with {:?} yields {:?}",
2087 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2088 let sig = match op.ty(body, tcx).sty {
2089 ty::Closure(def_id, substs) => {
2090 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
2094 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2096 if let Err(terr) = self.eq_types(
2099 location.to_locations(),
2100 ConstraintCategory::Cast,
2105 "equating {:?} with {:?} yields {:?}",
2113 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2114 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2116 // The type that we see in the fcx is like
2117 // `foo::<'a, 'b>`, where `foo` is the path to a
2118 // function definition. When we extract the
2119 // signature, it comes from the `fn_sig` query,
2120 // and hence may contain unnormalized results.
2121 let fn_sig = self.normalize(fn_sig, location);
2123 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2125 if let Err(terr) = self.eq_types(
2128 location.to_locations(),
2129 ConstraintCategory::Cast,
2134 "equating {:?} with {:?} yields {:?}",
2142 CastKind::Pointer(PointerCast::Unsize) => {
2144 let trait_ref = ty::TraitRef {
2145 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2146 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2149 self.prove_trait_ref(
2151 location.to_locations(),
2152 ConstraintCategory::Cast,
2156 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2157 let ty_from = match op.ty(body, tcx).sty {
2158 ty::RawPtr(ty::TypeAndMut {
2160 mutbl: hir::MutMutable,
2166 "unexpected base type for cast {:?}",
2172 let ty_to = match ty.sty {
2173 ty::RawPtr(ty::TypeAndMut {
2175 mutbl: hir::MutImmutable,
2181 "unexpected target type for cast {:?}",
2187 if let Err(terr) = self.sub_types(
2190 location.to_locations(),
2191 ConstraintCategory::Cast,
2196 "relating {:?} with {:?} yields {:?}",
2205 if let ty::Ref(_, mut ty_from, _) = op.ty(body, tcx).sty {
2206 let (mut ty_to, mutability) = if let ty::RawPtr(ty::TypeAndMut {
2215 "invalid cast types {:?} -> {:?}",
2222 // Handle the direct cast from `&[T; N]` to `*const T` by unwrapping
2223 // any array we find.
2224 while let ty::Array(ty_elem_from, _) = ty_from.sty {
2225 ty_from = ty_elem_from;
2226 if let ty::Array(ty_elem_to, _) = ty_to.sty {
2233 if let hir::MutMutable = mutability {
2234 if let Err(terr) = self.eq_types(
2237 location.to_locations(),
2238 ConstraintCategory::Cast,
2243 "equating {:?} with {:?} yields {:?}",
2250 if let Err(terr) = self.sub_types(
2253 location.to_locations(),
2254 ConstraintCategory::Cast,
2259 "relating {:?} with {:?} yields {:?}",
2271 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2272 self.add_reborrow_constraint(body, location, region, borrowed_place);
2275 Rvalue::BinaryOp(BinOp::Eq, left, right)
2276 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2277 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2278 | Rvalue::BinaryOp(BinOp::Le, left, right)
2279 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2280 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2281 let ty_left = left.ty(body, tcx);
2282 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.sty {
2283 let ty_right = right.ty(body, tcx);
2284 let common_ty = self.infcx.next_ty_var(
2285 TypeVariableOrigin {
2286 kind: TypeVariableOriginKind::MiscVariable,
2287 span: body.source_info(location).span,
2293 location.to_locations(),
2294 ConstraintCategory::Boring
2295 ).unwrap_or_else(|err| {
2296 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2298 if let Err(terr) = self.sub_types(
2301 location.to_locations(),
2302 ConstraintCategory::Boring
2307 "unexpected comparison types {:?} and {:?} yields {:?}",
2318 | Rvalue::BinaryOp(..)
2319 | Rvalue::CheckedBinaryOp(..)
2320 | Rvalue::UnaryOp(..)
2321 | Rvalue::Discriminant(..) => {}
2325 /// If this rvalue supports a user-given type annotation, then
2326 /// extract and return it. This represents the final type of the
2327 /// rvalue and will be unified with the inferred type.
2328 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2331 | Rvalue::Repeat(..)
2335 | Rvalue::BinaryOp(..)
2336 | Rvalue::CheckedBinaryOp(..)
2337 | Rvalue::NullaryOp(..)
2338 | Rvalue::UnaryOp(..)
2339 | Rvalue::Discriminant(..) => None,
2341 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2342 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2343 AggregateKind::Array(_) => None,
2344 AggregateKind::Tuple => None,
2345 AggregateKind::Closure(_, _) => None,
2346 AggregateKind::Generator(_, _, _) => None,
2351 fn check_aggregate_rvalue(
2354 rvalue: &Rvalue<'tcx>,
2355 aggregate_kind: &AggregateKind<'tcx>,
2356 operands: &[Operand<'tcx>],
2359 let tcx = self.tcx();
2361 self.prove_aggregate_predicates(aggregate_kind, location);
2363 if *aggregate_kind == AggregateKind::Tuple {
2364 // tuple rvalue field type is always the type of the op. Nothing to check here.
2368 for (i, operand) in operands.iter().enumerate() {
2369 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2370 Ok(field_ty) => field_ty,
2371 Err(FieldAccessError::OutOfRange { field_count }) => {
2375 "accessed field #{} but variant only has {}",
2382 let operand_ty = operand.ty(body, tcx);
2384 if let Err(terr) = self.sub_types(
2387 location.to_locations(),
2388 ConstraintCategory::Boring,
2393 "{:?} is not a subtype of {:?}: {:?}",
2402 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2406 /// - `location`: the location `L` where the borrow expression occurs
2407 /// - `borrow_region`: the region `'a` associated with the borrow
2408 /// - `borrowed_place`: the place `P` being borrowed
2409 fn add_reborrow_constraint(
2413 borrow_region: ty::Region<'tcx>,
2414 borrowed_place: &Place<'tcx>,
2416 // These constraints are only meaningful during borrowck:
2417 let BorrowCheckContext {
2423 } = self.borrowck_context;
2425 // In Polonius mode, we also push a `borrow_region` fact
2426 // linking the loan to the region (in some cases, though,
2427 // there is no loan associated with this borrow expression --
2428 // that occurs when we are borrowing an unsafe place, for
2430 if let Some(all_facts) = all_facts {
2431 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2432 let region_vid = borrow_region.to_region_vid();
2433 all_facts.borrow_region.push((
2436 location_table.mid_index(location),
2441 // If we are reborrowing the referent of another reference, we
2442 // need to add outlives relationships. In a case like `&mut
2443 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2444 // need to ensure that `'b: 'a`.
2446 let mut borrowed_projection = &borrowed_place.projection;
2449 "add_reborrow_constraint({:?}, {:?}, {:?})",
2450 location, borrow_region, borrowed_place
2452 while let Some(box proj) = borrowed_projection {
2453 debug!("add_reborrow_constraint - iteration {:?}", borrowed_projection);
2456 ProjectionElem::Deref => {
2457 let tcx = self.infcx.tcx;
2458 let base_ty = Place::ty_from(&borrowed_place.base, &proj.base, body, tcx).ty;
2460 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2462 ty::Ref(ref_region, _, mutbl) => {
2463 constraints.outlives_constraints.push(OutlivesConstraint {
2464 sup: ref_region.to_region_vid(),
2465 sub: borrow_region.to_region_vid(),
2466 locations: location.to_locations(),
2467 category: ConstraintCategory::Boring,
2471 hir::Mutability::MutImmutable => {
2472 // Immutable reference. We don't need the base
2473 // to be valid for the entire lifetime of
2477 hir::Mutability::MutMutable => {
2478 // Mutable reference. We *do* need the base
2479 // to be valid, because after the base becomes
2480 // invalid, someone else can use our mutable deref.
2482 // This is in order to make the following function
2485 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2490 // As otherwise you could clone `&mut T` using the
2491 // following function:
2493 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2494 // let my_clone = unsafe_deref(&'a x);
2503 // deref of raw pointer, guaranteed to be valid
2506 ty::Adt(def, _) if def.is_box() => {
2507 // deref of `Box`, need the base to be valid - propagate
2509 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2512 ProjectionElem::Field(..)
2513 | ProjectionElem::Downcast(..)
2514 | ProjectionElem::Index(..)
2515 | ProjectionElem::ConstantIndex { .. }
2516 | ProjectionElem::Subslice { .. } => {
2517 // other field access
2521 // The "propagate" case. We need to check that our base is valid
2522 // for the borrow's lifetime.
2523 borrowed_projection = &proj.base;
2527 fn prove_aggregate_predicates(
2529 aggregate_kind: &AggregateKind<'tcx>,
2532 let tcx = self.tcx();
2535 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2536 aggregate_kind, location
2539 let instantiated_predicates = match aggregate_kind {
2540 AggregateKind::Adt(def, _, substs, _, _) => {
2541 tcx.predicates_of(def.did).instantiate(tcx, substs)
2544 // For closures, we have some **extra requirements** we
2546 // have to check. In particular, in their upvars and
2547 // signatures, closures often reference various regions
2548 // from the surrounding function -- we call those the
2549 // closure's free regions. When we borrow-check (and hence
2550 // region-check) closures, we may find that the closure
2551 // requires certain relationships between those free
2552 // regions. However, because those free regions refer to
2553 // portions of the CFG of their caller, the closure is not
2554 // in a position to verify those relationships. In that
2555 // case, the requirements get "propagated" to us, and so
2556 // we have to solve them here where we instantiate the
2559 // Despite the opacity of the previous parapgrah, this is
2560 // actually relatively easy to understand in terms of the
2561 // desugaring. A closure gets desugared to a struct, and
2562 // these extra requirements are basically like where
2563 // clauses on the struct.
2564 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2565 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2566 self.prove_closure_bounds(tcx, *def_id, substs, location)
2569 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2572 self.normalize_and_prove_instantiated_predicates(
2573 instantiated_predicates,
2574 location.to_locations(),
2578 fn prove_closure_bounds(
2582 substs: SubstsRef<'tcx>,
2584 ) -> ty::InstantiatedPredicates<'tcx> {
2585 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2586 let closure_constraints = QueryRegionConstraints {
2587 outlives: closure_region_requirements.apply_requirements(tcx, def_id, substs),
2589 // Presently, closures never propagate member
2590 // constraints to their parents -- they are enforced
2591 // locally. This is largely a non-issue as member
2592 // constraints only come from `-> impl Trait` and
2593 // friends which don't appear (thus far...) in
2595 member_constraints: vec![],
2598 let bounds_mapping = closure_constraints
2602 .filter_map(|(idx, constraint)| {
2603 let ty::OutlivesPredicate(k1, r2) =
2604 constraint.no_bound_vars().unwrap_or_else(|| {
2605 bug!("query_constraint {:?} contained bound vars", constraint,);
2609 UnpackedKind::Lifetime(r1) => {
2610 // constraint is r1: r2
2611 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2612 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2613 let outlives_requirements =
2614 &closure_region_requirements.outlives_requirements[idx];
2618 outlives_requirements.category,
2619 outlives_requirements.blame_span,
2623 UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2628 let existing = self.borrowck_context
2630 .closure_bounds_mapping
2631 .insert(location, bounds_mapping);
2634 "Multiple closures at the same location."
2637 self.push_region_constraints(
2638 location.to_locations(),
2639 ConstraintCategory::ClosureBounds,
2640 &closure_constraints,
2644 tcx.predicates_of(def_id).instantiate(tcx, substs)
2649 trait_ref: ty::TraitRef<'tcx>,
2650 locations: Locations,
2651 category: ConstraintCategory,
2653 self.prove_predicates(
2654 Some(ty::Predicate::Trait(
2655 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2662 fn normalize_and_prove_instantiated_predicates(
2664 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2665 locations: Locations,
2667 for predicate in instantiated_predicates.predicates {
2668 let predicate = self.normalize(predicate, locations);
2669 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2673 fn prove_predicates(
2675 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2676 locations: Locations,
2677 category: ConstraintCategory,
2679 for predicate in predicates {
2681 "prove_predicates(predicate={:?}, locations={:?})",
2682 predicate, locations,
2685 self.prove_predicate(predicate, locations, category);
2691 predicate: ty::Predicate<'tcx>,
2692 locations: Locations,
2693 category: ConstraintCategory,
2696 "prove_predicate(predicate={:?}, location={:?})",
2697 predicate, locations,
2700 let param_env = self.param_env;
2701 self.fully_perform_op(
2704 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2705 ).unwrap_or_else(|NoSolution| {
2706 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2710 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2711 self.last_span = body.span;
2712 debug!("run_on_mir: {:?}", body.span);
2714 for (local, local_decl) in body.local_decls.iter_enumerated() {
2715 self.check_local(body, local, local_decl);
2718 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2719 let mut location = Location {
2723 for stmt in &block_data.statements {
2724 if !stmt.source_info.span.is_dummy() {
2725 self.last_span = stmt.source_info.span;
2727 self.check_stmt(body, stmt, location);
2728 location.statement_index += 1;
2731 self.check_terminator(body, block_data.terminator(), location);
2732 self.check_iscleanup(body, block_data);
2736 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2738 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2740 debug!("normalize(value={:?}, location={:?})", value, location);
2741 let param_env = self.param_env;
2742 self.fully_perform_op(
2743 location.to_locations(),
2744 ConstraintCategory::Boring,
2745 param_env.and(type_op::normalize::Normalize::new(value)),
2746 ).unwrap_or_else(|NoSolution| {
2747 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2753 trait NormalizeLocation: fmt::Debug + Copy {
2754 fn to_locations(self) -> Locations;
2757 impl NormalizeLocation for Locations {
2758 fn to_locations(self) -> Locations {
2763 impl NormalizeLocation for Location {
2764 fn to_locations(self) -> Locations {
2765 Locations::Single(self)
2769 #[derive(Debug, Default)]
2770 struct ObligationAccumulator<'tcx> {
2771 obligations: PredicateObligations<'tcx>,
2774 impl<'tcx> ObligationAccumulator<'tcx> {
2775 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2776 let InferOk { value, obligations } = value;
2777 self.obligations.extend(obligations);
2781 fn into_vec(self) -> PredicateObligations<'tcx> {