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_type(constant, constant.literal.ty);
277 if let Some(annotation_index) = constant.user_ty {
278 if let Err(terr) = self.cx.relate_type_and_user_type(
280 ty::Variance::Invariant,
281 &UserTypeProjection { base: annotation_index, projs: vec![], },
282 location.to_locations(),
283 ConstraintCategory::Boring,
285 let annotation = &self.cx.user_type_annotations[annotation_index];
289 "bad constant user type {:?} vs {:?}: {:?}",
296 if let ConstValue::Unevaluated(def_id, substs) = constant.literal.val {
297 if let Err(terr) = self.cx.fully_perform_op(
298 location.to_locations(),
299 ConstraintCategory::Boring,
300 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
301 constant.literal.ty, def_id, UserSubsts { substs, user_self_ty: None },
307 "bad constant type {:?} ({:?})",
313 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
314 let tcx = self.tcx();
316 let instantiated_predicates = tcx
317 .predicates_of(def_id)
318 .instantiate(tcx, substs);
319 self.cx.normalize_and_prove_instantiated_predicates(
320 instantiated_predicates,
321 location.to_locations(),
327 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
328 self.super_rvalue(rvalue, location);
329 let rval_ty = rvalue.ty(self.body, self.tcx());
330 self.sanitize_type(rvalue, rval_ty);
333 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
334 self.super_local_decl(local, local_decl);
335 self.sanitize_type(local_decl, local_decl.ty);
337 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
338 let ty = if !local_decl.is_nonref_binding() {
339 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
340 // reference so we can check the type annotation for the remaining type.
341 if let ty::Ref(_, rty, _) = local_decl.ty.sty {
344 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
350 if let Err(terr) = self.cx.relate_type_and_user_type(
352 ty::Variance::Invariant,
354 Locations::All(*span),
355 ConstraintCategory::TypeAnnotation,
360 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
370 fn visit_body(&mut self, body: &Body<'tcx>) {
371 self.sanitize_type(&"return type", body.return_ty());
372 for local_decl in &body.local_decls {
373 self.sanitize_type(local_decl, local_decl.ty);
375 if self.errors_reported {
378 self.super_body(body);
382 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
383 fn new(cx: &'a mut TypeChecker<'b, 'tcx>, body: &'b Body<'tcx>) -> Self {
386 mir_def_id: cx.mir_def_id,
388 last_span: body.span,
389 errors_reported: false,
393 fn tcx(&self) -> TyCtxt<'tcx> {
397 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
398 if ty.has_escaping_bound_vars() || ty.references_error() {
399 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
405 /// Checks that the types internal to the `place` match up with
406 /// what would be expected.
411 context: PlaceContext,
413 debug!("sanitize_place: {:?}", place);
415 place.iterate(|place_base, place_projection| {
416 let mut place_ty = match place_base {
417 PlaceBase::Local(index) =>
418 PlaceTy::from_ty(self.body.local_decls[*index].ty),
419 PlaceBase::Static(box Static { kind, ty: sty }) => {
420 let sty = self.sanitize_type(place, sty);
422 |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
426 if let Err(terr) = verifier.cx.eq_types(
429 location.to_locations(),
430 ConstraintCategory::Boring,
435 "bad promoted type ({:?}: {:?}): {:?}",
443 StaticKind::Promoted(promoted) => {
444 if !self.errors_reported {
445 let promoted_body = &self.body.promoted[*promoted];
446 self.sanitize_promoted(promoted_body, location);
448 let promoted_ty = promoted_body.return_ty();
449 check_err(self, place, promoted_ty, sty);
452 StaticKind::Static(def_id) => {
453 let ty = self.tcx().type_of(*def_id);
454 let ty = self.cx.normalize(ty, location);
456 check_err(self, place, ty, sty);
459 PlaceTy::from_ty(sty)
463 // FIXME use place_projection.is_empty() when is available
464 if place.projection.is_none() {
465 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
466 let is_promoted = match place {
468 base: PlaceBase::Static(box Static {
469 kind: StaticKind::Promoted(_),
478 let tcx = self.tcx();
479 let trait_ref = ty::TraitRef {
480 def_id: tcx.lang_items().copy_trait().unwrap(),
481 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
484 // In order to have a Copy operand, the type T of the
485 // value must be Copy. Note that we prove that T: Copy,
486 // rather than using the `is_copy_modulo_regions`
487 // test. This is important because
488 // `is_copy_modulo_regions` ignores the resulting region
489 // obligations and assumes they pass. This can result in
490 // bounds from Copy impls being unsoundly ignored (e.g.,
491 // #29149). Note that we decide to use Copy before knowing
492 // whether the bounds fully apply: in effect, the rule is
493 // that if a value of some type could implement Copy, then
495 self.cx.prove_trait_ref(
497 location.to_locations(),
498 ConstraintCategory::CopyBound,
504 for proj in place_projection {
505 if place_ty.variant_index.is_none() {
506 if place_ty.ty.references_error() {
507 assert!(self.errors_reported);
508 return PlaceTy::from_ty(self.tcx().types.err);
511 place_ty = self.sanitize_projection(place_ty, &proj.elem, place, location)
518 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
519 // Determine the constraints from the promoted MIR by running the type
520 // checker on the promoted MIR, then transfer the constraints back to
521 // the main MIR, changing the locations to the provided location.
523 let parent_body = mem::replace(&mut self.body, promoted_body);
525 let all_facts = &mut None;
526 let mut constraints = Default::default();
527 let mut closure_bounds = Default::default();
528 // Don't try to add borrow_region facts for the promoted MIR
529 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
531 // Use a new sets of constraints and closure bounds so that we can
532 // modify their locations.
534 &mut self.cx.borrowck_context.constraints.outlives_constraints,
538 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
542 self.visit_body(promoted_body);
544 if !self.errors_reported {
545 // if verifier failed, don't do further checks to avoid ICEs
546 self.cx.typeck_mir(promoted_body);
549 self.body = parent_body;
550 // Merge the outlives constraints back in, at the given location.
551 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
553 &mut self.cx.borrowck_context.constraints.outlives_constraints,
557 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
561 let locations = location.to_locations();
562 for constraint in constraints.outlives().iter() {
563 let mut constraint = *constraint;
564 constraint.locations = locations;
565 if let ConstraintCategory::Return
566 | ConstraintCategory::UseAsConst
567 | ConstraintCategory::UseAsStatic = constraint.category
569 // "Returning" from a promoted is an assigment to a
570 // temporary from the user's point of view.
571 constraint.category = ConstraintCategory::Boring;
573 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
576 if !closure_bounds.is_empty() {
577 let combined_bounds_mapping = closure_bounds
579 .flat_map(|(_, value)| value)
581 let existing = self.cx.borrowck_context
583 .closure_bounds_mapping
584 .insert(location, combined_bounds_mapping);
587 "Multiple promoteds/closures at the same location."
592 fn sanitize_projection(
595 pi: &PlaceElem<'tcx>,
599 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
600 let tcx = self.tcx();
601 let base_ty = base.ty;
603 ProjectionElem::Deref => {
604 let deref_ty = base_ty.builtin_deref(true);
606 deref_ty.map(|t| t.ty).unwrap_or_else(|| {
607 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
611 ProjectionElem::Index(i) => {
612 let index_ty = Place::from(i).ty(self.body, tcx).ty;
613 if index_ty != tcx.types.usize {
615 span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
619 base_ty.builtin_index().unwrap_or_else(|| {
620 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
625 ProjectionElem::ConstantIndex { .. } => {
626 // consider verifying in-bounds
628 base_ty.builtin_index().unwrap_or_else(|| {
629 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
633 ProjectionElem::Subslice { from, to } => PlaceTy::from_ty(
635 ty::Array(inner, size) => {
636 let size = size.eval_usize(tcx, self.cx.param_env);
637 let min_size = (from as u64) + (to as u64);
638 if let Some(rest_size) = size.checked_sub(min_size) {
639 tcx.mk_array(inner, rest_size)
641 span_mirbug_and_err!(
644 "taking too-small slice of {:?}",
649 ty::Slice(..) => base_ty,
650 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
653 ProjectionElem::Downcast(maybe_name, index) => match base_ty.sty {
654 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
655 if index.as_usize() >= adt_def.variants.len() {
657 span_mirbug_and_err!(
660 "cast to variant #{:?} but enum only has {:?}",
662 adt_def.variants.len()
668 variant_index: Some(index),
672 // We do not need to handle generators here, because this runs
673 // before the generator transform stage.
675 let ty = if let Some(name) = maybe_name {
676 span_mirbug_and_err!(
679 "can't downcast {:?} as {:?}",
684 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
689 ProjectionElem::Field(field, fty) => {
690 let fty = self.sanitize_type(place, fty);
691 match self.field_ty(place, base, field, location) {
692 Ok(ty) => if let Err(terr) = self.cx.eq_types(
695 location.to_locations(),
696 ConstraintCategory::Boring,
701 "bad field access ({:?}: {:?}): {:?}",
707 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
710 "accessed field #{} but variant only has {}",
715 PlaceTy::from_ty(fty)
720 fn error(&mut self) -> Ty<'tcx> {
721 self.errors_reported = true;
727 parent: &dyn fmt::Debug,
728 base_ty: PlaceTy<'tcx>,
731 ) -> Result<Ty<'tcx>, FieldAccessError> {
732 let tcx = self.tcx();
734 let (variant, substs) = match base_ty {
735 PlaceTy { ty, variant_index: Some(variant_index) } => match ty.sty {
736 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
737 ty::Generator(def_id, substs, _) => {
738 let mut variants = substs.state_tys(def_id, tcx);
739 let mut variant = match variants.nth(variant_index.into()) {
742 bug!("variant_index of generator out of range: {:?}/{:?}",
744 substs.state_tys(def_id, tcx).count())
747 return match variant.nth(field.index()) {
749 None => Err(FieldAccessError::OutOfRange {
750 field_count: variant.count(),
754 _ => bug!("can't have downcast of non-adt non-generator type"),
756 PlaceTy { ty, variant_index: None } => match ty.sty {
757 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
758 (&adt_def.variants[VariantIdx::new(0)], substs),
759 ty::Closure(def_id, substs) => {
760 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
762 None => Err(FieldAccessError::OutOfRange {
763 field_count: substs.upvar_tys(def_id, tcx).count(),
767 ty::Generator(def_id, substs, _) => {
768 // Only prefix fields (upvars and current state) are
769 // accessible without a variant index.
770 return match substs.prefix_tys(def_id, tcx).nth(field.index()) {
772 None => Err(FieldAccessError::OutOfRange {
773 field_count: substs.prefix_tys(def_id, tcx).count(),
778 return match tys.get(field.index()) {
779 Some(&ty) => Ok(ty.expect_ty()),
780 None => Err(FieldAccessError::OutOfRange {
781 field_count: tys.len(),
786 return Ok(span_mirbug_and_err!(
789 "can't project out of {:?}",
796 if let Some(field) = variant.fields.get(field.index()) {
797 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
799 Err(FieldAccessError::OutOfRange {
800 field_count: variant.fields.len(),
806 /// The MIR type checker. Visits the MIR and enforces all the
807 /// constraints needed for it to be valid and well-typed. Along the
808 /// way, it accrues region constraints -- these can later be used by
809 /// NLL region checking.
810 struct TypeChecker<'a, 'tcx> {
811 infcx: &'a InferCtxt<'a, 'tcx>,
812 param_env: ty::ParamEnv<'tcx>,
814 body: &'a Body<'tcx>,
815 /// User type annotations are shared between the main MIR and the MIR of
816 /// all of the promoted items.
817 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
819 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
820 implicit_region_bound: ty::Region<'tcx>,
821 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
822 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
823 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
826 struct BorrowCheckContext<'a, 'tcx> {
827 universal_regions: &'a UniversalRegions<'tcx>,
828 location_table: &'a LocationTable,
829 all_facts: &'a mut Option<AllFacts>,
830 borrow_set: &'a BorrowSet<'tcx>,
831 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
834 crate struct MirTypeckResults<'tcx> {
835 crate constraints: MirTypeckRegionConstraints<'tcx>,
836 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
839 /// A collection of region constraints that must be satisfied for the
840 /// program to be considered well-typed.
841 crate struct MirTypeckRegionConstraints<'tcx> {
842 /// Maps from a `ty::Placeholder` to the corresponding
843 /// `PlaceholderIndex` bit that we will use for it.
845 /// To keep everything in sync, do not insert this set
846 /// directly. Instead, use the `placeholder_region` helper.
847 crate placeholder_indices: PlaceholderIndices,
849 /// Each time we add a placeholder to `placeholder_indices`, we
850 /// also create a corresponding "representative" region vid for
851 /// that wraps it. This vector tracks those. This way, when we
852 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
853 /// the same underlying `RegionVid`.
854 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
856 /// In general, the type-checker is not responsible for enforcing
857 /// liveness constraints; this job falls to the region inferencer,
858 /// which performs a liveness analysis. However, in some limited
859 /// cases, the MIR type-checker creates temporary regions that do
860 /// not otherwise appear in the MIR -- in particular, the
861 /// late-bound regions that it instantiates at call-sites -- and
862 /// hence it must report on their liveness constraints.
863 crate liveness_constraints: LivenessValues<RegionVid>,
865 crate outlives_constraints: OutlivesConstraintSet,
867 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
869 crate closure_bounds_mapping:
870 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
872 crate type_tests: Vec<TypeTest<'tcx>>,
875 impl MirTypeckRegionConstraints<'tcx> {
876 fn placeholder_region(
878 infcx: &InferCtxt<'_, 'tcx>,
879 placeholder: ty::PlaceholderRegion,
880 ) -> ty::Region<'tcx> {
881 let placeholder_index = self.placeholder_indices.insert(placeholder);
882 match self.placeholder_index_to_region.get(placeholder_index) {
885 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
886 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
887 self.placeholder_index_to_region.push(region);
894 /// The `Locations` type summarizes *where* region constraints are
895 /// required to hold. Normally, this is at a particular point which
896 /// created the obligation, but for constraints that the user gave, we
897 /// want the constraint to hold at all points.
898 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
900 /// Indicates that a type constraint should always be true. This
901 /// is particularly important in the new borrowck analysis for
902 /// things like the type of the return slot. Consider this
906 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
908 /// return &y; // error
912 /// Here, we wind up with the signature from the return type being
913 /// something like `&'1 u32` where `'1` is a universal region. But
914 /// the type of the return slot `_0` is something like `&'2 u32`
915 /// where `'2` is an existential region variable. The type checker
916 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
917 /// older NLL analysis, we required this only at the entry point
918 /// to the function. By the nature of the constraints, this wound
919 /// up propagating to all points reachable from start (because
920 /// `'1` -- as a universal region -- is live everywhere). In the
921 /// newer analysis, though, this doesn't work: `_0` is considered
922 /// dead at the start (it has no usable value) and hence this type
923 /// equality is basically a no-op. Then, later on, when we do `_0
924 /// = &'3 y`, that region `'3` never winds up related to the
925 /// universal region `'1` and hence no error occurs. Therefore, we
926 /// use Locations::All instead, which ensures that the `'1` and
927 /// `'2` are equal everything. We also use this for other
928 /// user-given type annotations; e.g., if the user wrote `let mut
929 /// x: &'static u32 = ...`, we would ensure that all values
930 /// assigned to `x` are of `'static` lifetime.
932 /// The span points to the place the constraint arose. For example,
933 /// it points to the type in a user-given type annotation. If
934 /// there's no sensible span then it's DUMMY_SP.
937 /// An outlives constraint that only has to hold at a single location,
938 /// usually it represents a point where references flow from one spot to
939 /// another (e.g., `x = y`)
944 pub fn from_location(&self) -> Option<Location> {
946 Locations::All(_) => None,
947 Locations::Single(from_location) => Some(*from_location),
951 /// Gets a span representing the location.
952 pub fn span(&self, body: &Body<'_>) -> Span {
954 Locations::All(span) => *span,
955 Locations::Single(l) => body.source_info(*l).span,
960 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
962 infcx: &'a InferCtxt<'a, 'tcx>,
963 body: &'a Body<'tcx>,
965 param_env: ty::ParamEnv<'tcx>,
966 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
967 implicit_region_bound: ty::Region<'tcx>,
968 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
969 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
971 let mut checker = Self {
976 user_type_annotations: &body.user_type_annotations,
979 implicit_region_bound,
981 reported_errors: Default::default(),
982 universal_region_relations,
984 checker.check_user_type_annotations();
988 /// Equate the inferred type and the annotated type for user type annotations
989 fn check_user_type_annotations(&mut self) {
991 "check_user_type_annotations: user_type_annotations={:?}",
992 self.user_type_annotations
994 for user_annotation in self.user_type_annotations {
995 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
996 let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
1000 UserType::Ty(mut ty) => {
1001 ty = self.normalize(ty, Locations::All(span));
1003 if let Err(terr) = self.eq_types(
1006 Locations::All(span),
1007 ConstraintCategory::BoringNoLocation,
1012 "bad user type ({:?} = {:?}): {:?}",
1019 self.prove_predicate(
1020 ty::Predicate::WellFormed(inferred_ty),
1021 Locations::All(span),
1022 ConstraintCategory::TypeAnnotation,
1025 UserType::TypeOf(def_id, user_substs) => {
1026 if let Err(terr) = self.fully_perform_op(
1027 Locations::All(span),
1028 ConstraintCategory::BoringNoLocation,
1029 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1030 inferred_ty, def_id, user_substs,
1036 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1048 /// Given some operation `op` that manipulates types, proves
1049 /// predicates, or otherwise uses the inference context, executes
1050 /// `op` and then executes all the further obligations that `op`
1051 /// returns. This will yield a set of outlives constraints amongst
1052 /// regions which are extracted and stored as having occurred at
1055 /// **Any `rustc::infer` operations that might generate region
1056 /// constraints should occur within this method so that those
1057 /// constraints can be properly localized!**
1058 fn fully_perform_op<R>(
1060 locations: Locations,
1061 category: ConstraintCategory,
1062 op: impl type_op::TypeOp<'tcx, Output = R>,
1064 let (r, opt_data) = op.fully_perform(self.infcx)?;
1066 if let Some(data) = &opt_data {
1067 self.push_region_constraints(locations, category, data);
1073 fn push_region_constraints(
1075 locations: Locations,
1076 category: ConstraintCategory,
1077 data: &QueryRegionConstraints<'tcx>,
1080 "push_region_constraints: constraints generated at {:?} are {:#?}",
1084 constraint_conversion::ConstraintConversion::new(
1086 self.borrowck_context.universal_regions,
1087 self.region_bound_pairs,
1088 Some(self.implicit_region_bound),
1092 &mut self.borrowck_context.constraints,
1093 ).convert_all(data);
1096 /// Convenient wrapper around `relate_tys::relate_types` -- see
1097 /// that fn for docs.
1103 locations: Locations,
1104 category: ConstraintCategory,
1106 relate_tys::relate_types(
1113 Some(self.borrowck_context),
1121 locations: Locations,
1122 category: ConstraintCategory,
1124 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1127 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1128 /// variables in `sub` with their inferred definitions and try
1129 /// again. This is used for opaque types in places (e.g., `let x:
1130 /// impl Foo = ..`).
1131 fn sub_types_or_anon(
1135 locations: Locations,
1136 category: ConstraintCategory,
1138 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1139 if let ty::Opaque(..) = sup.sty {
1140 // When you have `let x: impl Foo = ...` in a closure,
1141 // the resulting inferend values are stored with the
1142 // def-id of the base function.
1143 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1144 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1156 locations: Locations,
1157 category: ConstraintCategory,
1159 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1162 fn relate_type_and_user_type(
1166 user_ty: &UserTypeProjection,
1167 locations: Locations,
1168 category: ConstraintCategory,
1171 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1172 a, v, user_ty, locations,
1175 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1176 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1178 let tcx = self.infcx.tcx;
1180 for proj in &user_ty.projs {
1181 let projected_ty = curr_projected_ty.projection_ty_core(
1185 |this, field, &()| {
1186 let ty = this.field_ty(tcx, field);
1187 self.normalize(ty, locations)
1190 curr_projected_ty = projected_ty;
1192 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1193 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1195 let ty = curr_projected_ty.ty;
1196 self.relate_types(a, v, ty, locations, category)?;
1201 fn eq_opaque_type_and_type(
1203 revealed_ty: Ty<'tcx>,
1205 anon_owner_def_id: DefId,
1206 locations: Locations,
1207 category: ConstraintCategory,
1210 "eq_opaque_type_and_type( \
1213 revealed_ty, anon_ty
1215 let infcx = self.infcx;
1216 let tcx = infcx.tcx;
1217 let param_env = self.param_env;
1218 let body = self.body;
1219 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1220 let opaque_type_map = self.fully_perform_op(
1225 let mut obligations = ObligationAccumulator::default();
1227 let dummy_body_id = ObligationCause::dummy().body_id;
1228 let (output_ty, opaque_type_map) =
1229 obligations.add(infcx.instantiate_opaque_types(
1234 locations.span(body),
1237 "eq_opaque_type_and_type: \
1238 instantiated output_ty={:?} \
1239 opaque_type_map={:#?} \
1241 output_ty, opaque_type_map, revealed_ty
1243 obligations.add(infcx
1244 .at(&ObligationCause::dummy(), param_env)
1245 .eq(output_ty, revealed_ty)?);
1247 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1248 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1249 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1250 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1251 let concrete_is_opaque = infcx
1252 .resolve_vars_if_possible(&opaque_decl.concrete_ty).is_impl_trait();
1255 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?} \
1256 concrete_is_opaque={}",
1257 opaque_decl.concrete_ty,
1258 infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty),
1263 // concrete_is_opaque is `true` when we're using an opaque `impl Trait`
1264 // type without 'revealing' it. For example, code like this:
1266 // type Foo = impl Debug;
1267 // fn foo1() -> Foo { ... }
1268 // fn foo2() -> Foo { foo1() }
1270 // In `foo2`, we're not revealing the type of `Foo` - we're
1271 // just treating it as the opaque type.
1273 // When this occurs, we do *not* want to try to equate
1274 // the concrete type with the underlying defining type
1275 // of the opaque type - this will always fail, since
1276 // the defining type of an opaque type is always
1277 // some other type (e.g. not itself)
1278 // Essentially, none of the normal obligations apply here -
1279 // we're just passing around some unknown opaque type,
1280 // without actually looking at the underlying type it
1281 // gets 'revealed' into
1283 if !concrete_is_opaque {
1284 obligations.add(infcx
1285 .at(&ObligationCause::dummy(), param_env)
1286 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1290 debug!("eq_opaque_type_and_type: equated");
1293 value: Some(opaque_type_map),
1294 obligations: obligations.into_vec(),
1297 || "input_output".to_string(),
1301 let universal_region_relations = self.universal_region_relations;
1303 // Finally, if we instantiated the anon types successfully, we
1304 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1305 // prove that `T: Iterator` where `T` is the type we
1306 // instantiated it with).
1307 if let Some(opaque_type_map) = opaque_type_map {
1308 for (opaque_def_id, opaque_decl) in opaque_type_map {
1309 self.fully_perform_op(
1311 ConstraintCategory::OpaqueType,
1314 infcx.constrain_opaque_type(
1317 universal_region_relations,
1321 obligations: vec![],
1324 || "opaque_type_map".to_string(),
1332 fn tcx(&self) -> TyCtxt<'tcx> {
1336 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1337 debug!("check_stmt: {:?}", stmt);
1338 let tcx = self.tcx();
1340 StatementKind::Assign(ref place, ref rv) => {
1341 // Assignments to temporaries are not "interesting";
1342 // they are not caused by the user, but rather artifacts
1343 // of lowering. Assignments to other sorts of places *are* interesting
1345 let category = match *place {
1347 base: PlaceBase::Local(RETURN_PLACE),
1349 } => if let BorrowCheckContext {
1352 defining_ty: DefiningTy::Const(def_id, _),
1356 } = self.borrowck_context {
1357 if tcx.is_static(*def_id) {
1358 ConstraintCategory::UseAsStatic
1360 ConstraintCategory::UseAsConst
1363 ConstraintCategory::Return
1366 base: PlaceBase::Local(l),
1368 } if !body.local_decls[l].is_user_variable.is_some() => {
1369 ConstraintCategory::Boring
1371 _ => ConstraintCategory::Assignment,
1374 let place_ty = place.ty(body, tcx).ty;
1375 let rv_ty = rv.ty(body, tcx);
1377 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1382 "bad assignment ({:?} = {:?}): {:?}",
1389 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1390 if let Err(terr) = self.relate_type_and_user_type(
1392 ty::Variance::Invariant,
1393 &UserTypeProjection { base: annotation_index, projs: vec![], },
1394 location.to_locations(),
1395 ConstraintCategory::Boring,
1397 let annotation = &self.user_type_annotations[annotation_index];
1401 "bad user type on rvalue ({:?} = {:?}): {:?}",
1409 self.check_rvalue(body, rv, location);
1410 if !self.tcx().features().unsized_locals {
1411 let trait_ref = ty::TraitRef {
1412 def_id: tcx.lang_items().sized_trait().unwrap(),
1413 substs: tcx.mk_substs_trait(place_ty, &[]),
1415 self.prove_trait_ref(
1417 location.to_locations(),
1418 ConstraintCategory::SizedBound,
1422 StatementKind::SetDiscriminant {
1426 let place_type = place.ty(body, tcx).ty;
1427 let adt = match place_type.sty {
1428 ty::Adt(adt, _) if adt.is_enum() => adt,
1431 stmt.source_info.span,
1432 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1438 if variant_index.as_usize() >= adt.variants.len() {
1440 stmt.source_info.span,
1441 "bad set discriminant ({:?} = {:?}): value of of range",
1447 StatementKind::AscribeUserType(ref place, variance, box ref projection) => {
1448 let place_ty = place.ty(body, tcx).ty;
1449 if let Err(terr) = self.relate_type_and_user_type(
1453 Locations::All(stmt.source_info.span),
1454 ConstraintCategory::TypeAnnotation,
1456 let annotation = &self.user_type_annotations[projection.base];
1460 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1468 StatementKind::FakeRead(..)
1469 | StatementKind::StorageLive(..)
1470 | StatementKind::StorageDead(..)
1471 | StatementKind::InlineAsm { .. }
1472 | StatementKind::Retag { .. }
1473 | StatementKind::Nop => {}
1477 fn check_terminator(
1480 term: &Terminator<'tcx>,
1481 term_location: Location,
1483 debug!("check_terminator: {:?}", term);
1484 let tcx = self.tcx();
1486 TerminatorKind::Goto { .. }
1487 | TerminatorKind::Resume
1488 | TerminatorKind::Abort
1489 | TerminatorKind::Return
1490 | TerminatorKind::GeneratorDrop
1491 | TerminatorKind::Unreachable
1492 | TerminatorKind::Drop { .. }
1493 | TerminatorKind::FalseEdges { .. }
1494 | TerminatorKind::FalseUnwind { .. } => {
1495 // no checks needed for these
1498 TerminatorKind::DropAndReplace {
1504 let place_ty = location.ty(body, tcx).ty;
1505 let rv_ty = value.ty(body, tcx);
1507 let locations = term_location.to_locations();
1509 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1514 "bad DropAndReplace ({:?} = {:?}): {:?}",
1521 TerminatorKind::SwitchInt {
1526 let discr_ty = discr.ty(body, tcx);
1527 if let Err(terr) = self.sub_types(
1530 term_location.to_locations(),
1531 ConstraintCategory::Assignment,
1536 "bad SwitchInt ({:?} on {:?}): {:?}",
1542 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1543 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1545 // FIXME: check the values
1547 TerminatorKind::Call {
1554 let func_ty = func.ty(body, tcx);
1555 debug!("check_terminator: call, func_ty={:?}", func_ty);
1556 let sig = match func_ty.sty {
1557 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1559 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1563 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1564 term.source_info.span,
1565 LateBoundRegionConversionTime::FnCall,
1568 let sig = self.normalize(sig, term_location);
1569 self.check_call_dest(body, term, &sig, destination, term_location);
1571 self.prove_predicates(
1572 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1573 term_location.to_locations(),
1574 ConstraintCategory::Boring,
1577 // The ordinary liveness rules will ensure that all
1578 // regions in the type of the callee are live here. We
1579 // then further constrain the late-bound regions that
1580 // were instantiated at the call site to be live as
1581 // well. The resulting is that all the input (and
1582 // output) types in the signature must be live, since
1583 // all the inputs that fed into it were live.
1584 for &late_bound_region in map.values() {
1585 let region_vid = self.borrowck_context
1587 .to_region_vid(late_bound_region);
1588 self.borrowck_context
1590 .liveness_constraints
1591 .add_element(region_vid, term_location);
1594 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1596 TerminatorKind::Assert {
1597 ref cond, ref msg, ..
1599 let cond_ty = cond.ty(body, tcx);
1600 if cond_ty != tcx.types.bool {
1601 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1604 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
1605 if len.ty(body, tcx) != tcx.types.usize {
1606 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1608 if index.ty(body, tcx) != tcx.types.usize {
1609 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1613 TerminatorKind::Yield { ref value, .. } => {
1614 let value_ty = value.ty(body, tcx);
1615 match body.yield_ty {
1616 None => span_mirbug!(self, term, "yield in non-generator"),
1618 if let Err(terr) = self.sub_types(
1621 term_location.to_locations(),
1622 ConstraintCategory::Yield,
1627 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1642 term: &Terminator<'tcx>,
1643 sig: &ty::FnSig<'tcx>,
1644 destination: &Option<(Place<'tcx>, BasicBlock)>,
1645 term_location: Location,
1647 let tcx = self.tcx();
1648 match *destination {
1649 Some((ref dest, _target_block)) => {
1650 let dest_ty = dest.ty(body, tcx).ty;
1651 let category = match *dest {
1653 base: PlaceBase::Local(RETURN_PLACE),
1656 if let BorrowCheckContext {
1659 defining_ty: DefiningTy::Const(def_id, _),
1663 } = self.borrowck_context
1665 if tcx.is_static(*def_id) {
1666 ConstraintCategory::UseAsStatic
1668 ConstraintCategory::UseAsConst
1671 ConstraintCategory::Return
1675 base: PlaceBase::Local(l),
1677 } if !body.local_decls[l].is_user_variable.is_some() => {
1678 ConstraintCategory::Boring
1680 _ => ConstraintCategory::Assignment,
1683 let locations = term_location.to_locations();
1686 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1691 "call dest mismatch ({:?} <- {:?}): {:?}",
1698 // When `#![feature(unsized_locals)]` is not enabled,
1699 // this check is done at `check_local`.
1700 if self.tcx().features().unsized_locals {
1701 let span = term.source_info.span;
1702 self.ensure_place_sized(dest_ty, span);
1706 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1707 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1713 fn check_call_inputs(
1716 term: &Terminator<'tcx>,
1717 sig: &ty::FnSig<'tcx>,
1718 args: &[Operand<'tcx>],
1719 term_location: Location,
1720 from_hir_call: bool,
1722 debug!("check_call_inputs({:?}, {:?})", sig, args);
1723 // Do not count the `VaListImpl` argument as a "true" argument to
1724 // a C-variadic function.
1725 let inputs = if sig.c_variadic {
1726 &sig.inputs()[..sig.inputs().len() - 1]
1730 if args.len() < inputs.len() || (args.len() > inputs.len() && !sig.c_variadic) {
1731 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1733 for (n, (fn_arg, op_arg)) in inputs.iter().zip(args).enumerate() {
1734 let op_arg_ty = op_arg.ty(body, self.tcx());
1735 let category = if from_hir_call {
1736 ConstraintCategory::CallArgument
1738 ConstraintCategory::Boring
1741 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1746 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1756 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1757 let is_cleanup = block_data.is_cleanup;
1758 self.last_span = block_data.terminator().source_info.span;
1759 match block_data.terminator().kind {
1760 TerminatorKind::Goto { target } => {
1761 self.assert_iscleanup(body, block_data, target, is_cleanup)
1763 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1764 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1766 TerminatorKind::Resume => if !is_cleanup {
1767 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1769 TerminatorKind::Abort => if !is_cleanup {
1770 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1772 TerminatorKind::Return => if is_cleanup {
1773 span_mirbug!(self, block_data, "return on cleanup block")
1775 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1776 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1778 TerminatorKind::Yield { resume, drop, .. } => {
1780 span_mirbug!(self, block_data, "yield in cleanup block")
1782 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1783 if let Some(drop) = drop {
1784 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1787 TerminatorKind::Unreachable => {}
1788 TerminatorKind::Drop { target, unwind, .. }
1789 | TerminatorKind::DropAndReplace { target, unwind, .. }
1790 | TerminatorKind::Assert {
1795 self.assert_iscleanup(body, block_data, target, is_cleanup);
1796 if let Some(unwind) = unwind {
1798 span_mirbug!(self, block_data, "unwind on cleanup block")
1800 self.assert_iscleanup(body, block_data, unwind, true);
1803 TerminatorKind::Call {
1808 if let &Some((_, target)) = destination {
1809 self.assert_iscleanup(body, block_data, target, is_cleanup);
1811 if let Some(cleanup) = cleanup {
1813 span_mirbug!(self, block_data, "cleanup on cleanup block")
1815 self.assert_iscleanup(body, block_data, cleanup, true);
1818 TerminatorKind::FalseEdges {
1822 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1823 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1825 TerminatorKind::FalseUnwind {
1829 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1830 if let Some(unwind) = unwind {
1835 "cleanup in cleanup block via false unwind"
1838 self.assert_iscleanup(body, block_data, unwind, true);
1844 fn assert_iscleanup(
1847 ctxt: &dyn fmt::Debug,
1851 if body[bb].is_cleanup != iscleanuppad {
1855 "cleanuppad mismatch: {:?} should be {:?}",
1862 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1863 match body.local_kind(local) {
1864 LocalKind::ReturnPointer | LocalKind::Arg => {
1865 // return values of normal functions are required to be
1866 // sized by typeck, but return values of ADT constructors are
1867 // not because we don't include a `Self: Sized` bounds on them.
1869 // Unbound parts of arguments were never required to be Sized
1870 // - maybe we should make that a warning.
1873 LocalKind::Var | LocalKind::Temp => {}
1876 // When `#![feature(unsized_locals)]` is enabled, only function calls
1877 // and nullary ops are checked in `check_call_dest`.
1878 if !self.tcx().features().unsized_locals {
1879 let span = local_decl.source_info.span;
1880 let ty = local_decl.ty;
1881 self.ensure_place_sized(ty, span);
1885 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1886 let tcx = self.tcx();
1888 // Erase the regions from `ty` to get a global type. The
1889 // `Sized` bound in no way depends on precise regions, so this
1890 // shouldn't affect `is_sized`.
1891 let gcx = tcx.global_tcx();
1892 let erased_ty = tcx.erase_regions(&ty);
1893 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1894 // in current MIR construction, all non-control-flow rvalue
1895 // expressions evaluate through `as_temp` or `into` a return
1896 // slot or local, so to find all unsized rvalues it is enough
1897 // to check all temps, return slots and locals.
1898 if let None = self.reported_errors.replace((ty, span)) {
1899 let mut diag = struct_span_err!(
1903 "cannot move a value of type {0}: the size of {0} \
1904 cannot be statically determined",
1908 // While this is located in `nll::typeck` this error is not
1909 // an NLL error, it's a required check to prevent creation
1910 // of unsized rvalues in certain cases:
1911 // * operand of a box expression
1912 // * callee in a call expression
1918 fn aggregate_field_ty(
1920 ak: &AggregateKind<'tcx>,
1923 ) -> Result<Ty<'tcx>, FieldAccessError> {
1924 let tcx = self.tcx();
1927 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1928 let variant = &def.variants[variant_index];
1929 let adj_field_index = active_field_index.unwrap_or(field_index);
1930 if let Some(field) = variant.fields.get(adj_field_index) {
1931 Ok(self.normalize(field.ty(tcx, substs), location))
1933 Err(FieldAccessError::OutOfRange {
1934 field_count: variant.fields.len(),
1938 AggregateKind::Closure(def_id, substs) => {
1939 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1941 None => Err(FieldAccessError::OutOfRange {
1942 field_count: substs.upvar_tys(def_id, tcx).count(),
1946 AggregateKind::Generator(def_id, substs, _) => {
1947 // It doesn't make sense to look at a field beyond the prefix;
1948 // these require a variant index, and are not initialized in
1949 // aggregate rvalues.
1950 match substs.prefix_tys(def_id, tcx).nth(field_index) {
1952 None => Err(FieldAccessError::OutOfRange {
1953 field_count: substs.prefix_tys(def_id, tcx).count(),
1957 AggregateKind::Array(ty) => Ok(ty),
1958 AggregateKind::Tuple => {
1959 unreachable!("This should have been covered in check_rvalues");
1964 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1965 let tcx = self.tcx();
1968 Rvalue::Aggregate(ak, ops) => {
1969 self.check_aggregate_rvalue(body, rvalue, ak, ops, location)
1972 Rvalue::Repeat(operand, len) => if *len > 1 {
1973 if let Operand::Move(_) = operand {
1974 // While this is located in `nll::typeck` this error is not an NLL error, it's
1975 // a required check to make sure that repeated elements implement `Copy`.
1976 let span = body.source_info(location).span;
1977 let ty = operand.ty(body, tcx);
1978 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1979 self.infcx.report_selection_error(
1980 &traits::Obligation::new(
1981 ObligationCause::new(
1983 self.tcx().hir().def_index_to_hir_id(self.mir_def_id.index),
1984 traits::ObligationCauseCode::RepeatVec,
1987 ty::Predicate::Trait(ty::Binder::bind(ty::TraitPredicate {
1988 trait_ref: ty::TraitRef::new(
1989 self.tcx().lang_items().copy_trait().unwrap(),
1990 tcx.mk_substs_trait(ty, &[]),
1994 &traits::SelectionError::Unimplemented,
2001 Rvalue::NullaryOp(_, ty) => {
2002 // Even with unsized locals cannot box an unsized value.
2003 if self.tcx().features().unsized_locals {
2004 let span = body.source_info(location).span;
2005 self.ensure_place_sized(ty, span);
2008 let trait_ref = ty::TraitRef {
2009 def_id: tcx.lang_items().sized_trait().unwrap(),
2010 substs: tcx.mk_substs_trait(ty, &[]),
2013 self.prove_trait_ref(
2015 location.to_locations(),
2016 ConstraintCategory::SizedBound,
2020 Rvalue::Cast(cast_kind, op, ty) => {
2022 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2023 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2025 // The type that we see in the fcx is like
2026 // `foo::<'a, 'b>`, where `foo` is the path to a
2027 // function definition. When we extract the
2028 // signature, it comes from the `fn_sig` query,
2029 // and hence may contain unnormalized results.
2030 let fn_sig = self.normalize(fn_sig, location);
2032 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2034 if let Err(terr) = self.eq_types(
2037 location.to_locations(),
2038 ConstraintCategory::Cast,
2043 "equating {:?} with {:?} yields {:?}",
2051 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2052 let sig = match op.ty(body, tcx).sty {
2053 ty::Closure(def_id, substs) => {
2054 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
2058 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2060 if let Err(terr) = self.eq_types(
2063 location.to_locations(),
2064 ConstraintCategory::Cast,
2069 "equating {:?} with {:?} yields {:?}",
2077 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2078 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2080 // The type that we see in the fcx is like
2081 // `foo::<'a, 'b>`, where `foo` is the path to a
2082 // function definition. When we extract the
2083 // signature, it comes from the `fn_sig` query,
2084 // and hence may contain unnormalized results.
2085 let fn_sig = self.normalize(fn_sig, location);
2087 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2089 if let Err(terr) = self.eq_types(
2092 location.to_locations(),
2093 ConstraintCategory::Cast,
2098 "equating {:?} with {:?} yields {:?}",
2106 CastKind::Pointer(PointerCast::Unsize) => {
2108 let trait_ref = ty::TraitRef {
2109 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2110 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2113 self.prove_trait_ref(
2115 location.to_locations(),
2116 ConstraintCategory::Cast,
2120 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2121 let ty_from = match op.ty(body, tcx).sty {
2122 ty::RawPtr(ty::TypeAndMut {
2124 mutbl: hir::MutMutable,
2130 "unexpected base type for cast {:?}",
2136 let ty_to = match ty.sty {
2137 ty::RawPtr(ty::TypeAndMut {
2139 mutbl: hir::MutImmutable,
2145 "unexpected target type for cast {:?}",
2151 if let Err(terr) = self.sub_types(
2154 location.to_locations(),
2155 ConstraintCategory::Cast,
2160 "relating {:?} with {:?} yields {:?}",
2169 if let ty::Ref(_, mut ty_from, _) = op.ty(body, tcx).sty {
2170 let (mut ty_to, mutability) = if let ty::RawPtr(ty::TypeAndMut {
2179 "invalid cast types {:?} -> {:?}",
2186 // Handle the direct cast from `&[T; N]` to `*const T` by unwrapping
2187 // any array we find.
2188 while let ty::Array(ty_elem_from, _) = ty_from.sty {
2189 ty_from = ty_elem_from;
2190 if let ty::Array(ty_elem_to, _) = ty_to.sty {
2197 if let hir::MutMutable = mutability {
2198 if let Err(terr) = self.eq_types(
2201 location.to_locations(),
2202 ConstraintCategory::Cast,
2207 "equating {:?} with {:?} yields {:?}",
2214 if let Err(terr) = self.sub_types(
2217 location.to_locations(),
2218 ConstraintCategory::Cast,
2223 "relating {:?} with {:?} yields {:?}",
2235 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2236 self.add_reborrow_constraint(body, location, region, borrowed_place);
2239 Rvalue::BinaryOp(BinOp::Eq, left, right)
2240 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2241 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2242 | Rvalue::BinaryOp(BinOp::Le, left, right)
2243 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2244 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2245 let ty_left = left.ty(body, tcx);
2246 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.sty {
2247 let ty_right = right.ty(body, tcx);
2248 let common_ty = self.infcx.next_ty_var(
2249 TypeVariableOrigin {
2250 kind: TypeVariableOriginKind::MiscVariable,
2251 span: body.source_info(location).span,
2257 location.to_locations(),
2258 ConstraintCategory::Boring
2259 ).unwrap_or_else(|err| {
2260 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2262 if let Err(terr) = self.sub_types(
2265 location.to_locations(),
2266 ConstraintCategory::Boring
2271 "unexpected comparison types {:?} and {:?} yields {:?}",
2282 | Rvalue::BinaryOp(..)
2283 | Rvalue::CheckedBinaryOp(..)
2284 | Rvalue::UnaryOp(..)
2285 | Rvalue::Discriminant(..) => {}
2289 /// If this rvalue supports a user-given type annotation, then
2290 /// extract and return it. This represents the final type of the
2291 /// rvalue and will be unified with the inferred type.
2292 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2295 | Rvalue::Repeat(..)
2299 | Rvalue::BinaryOp(..)
2300 | Rvalue::CheckedBinaryOp(..)
2301 | Rvalue::NullaryOp(..)
2302 | Rvalue::UnaryOp(..)
2303 | Rvalue::Discriminant(..) => None,
2305 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2306 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2307 AggregateKind::Array(_) => None,
2308 AggregateKind::Tuple => None,
2309 AggregateKind::Closure(_, _) => None,
2310 AggregateKind::Generator(_, _, _) => None,
2315 fn check_aggregate_rvalue(
2318 rvalue: &Rvalue<'tcx>,
2319 aggregate_kind: &AggregateKind<'tcx>,
2320 operands: &[Operand<'tcx>],
2323 let tcx = self.tcx();
2325 self.prove_aggregate_predicates(aggregate_kind, location);
2327 if *aggregate_kind == AggregateKind::Tuple {
2328 // tuple rvalue field type is always the type of the op. Nothing to check here.
2332 for (i, operand) in operands.iter().enumerate() {
2333 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2334 Ok(field_ty) => field_ty,
2335 Err(FieldAccessError::OutOfRange { field_count }) => {
2339 "accessed field #{} but variant only has {}",
2346 let operand_ty = operand.ty(body, tcx);
2348 if let Err(terr) = self.sub_types(
2351 location.to_locations(),
2352 ConstraintCategory::Boring,
2357 "{:?} is not a subtype of {:?}: {:?}",
2366 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2370 /// - `location`: the location `L` where the borrow expression occurs
2371 /// - `borrow_region`: the region `'a` associated with the borrow
2372 /// - `borrowed_place`: the place `P` being borrowed
2373 fn add_reborrow_constraint(
2377 borrow_region: ty::Region<'tcx>,
2378 borrowed_place: &Place<'tcx>,
2380 // These constraints are only meaningful during borrowck:
2381 let BorrowCheckContext {
2387 } = self.borrowck_context;
2389 // In Polonius mode, we also push a `borrow_region` fact
2390 // linking the loan to the region (in some cases, though,
2391 // there is no loan associated with this borrow expression --
2392 // that occurs when we are borrowing an unsafe place, for
2394 if let Some(all_facts) = all_facts {
2395 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2396 let region_vid = borrow_region.to_region_vid();
2397 all_facts.borrow_region.push((
2400 location_table.mid_index(location),
2405 // If we are reborrowing the referent of another reference, we
2406 // need to add outlives relationships. In a case like `&mut
2407 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2408 // need to ensure that `'b: 'a`.
2410 let mut borrowed_projection = &borrowed_place.projection;
2413 "add_reborrow_constraint({:?}, {:?}, {:?})",
2414 location, borrow_region, borrowed_place
2416 while let Some(box proj) = borrowed_projection {
2417 debug!("add_reborrow_constraint - iteration {:?}", borrowed_projection);
2420 ProjectionElem::Deref => {
2421 let tcx = self.infcx.tcx;
2422 let base_ty = Place::ty_from(&borrowed_place.base, &proj.base, body, tcx).ty;
2424 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2426 ty::Ref(ref_region, _, mutbl) => {
2427 constraints.outlives_constraints.push(OutlivesConstraint {
2428 sup: ref_region.to_region_vid(),
2429 sub: borrow_region.to_region_vid(),
2430 locations: location.to_locations(),
2431 category: ConstraintCategory::Boring,
2435 hir::Mutability::MutImmutable => {
2436 // Immutable reference. We don't need the base
2437 // to be valid for the entire lifetime of
2441 hir::Mutability::MutMutable => {
2442 // Mutable reference. We *do* need the base
2443 // to be valid, because after the base becomes
2444 // invalid, someone else can use our mutable deref.
2446 // This is in order to make the following function
2449 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2454 // As otherwise you could clone `&mut T` using the
2455 // following function:
2457 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2458 // let my_clone = unsafe_deref(&'a x);
2467 // deref of raw pointer, guaranteed to be valid
2470 ty::Adt(def, _) if def.is_box() => {
2471 // deref of `Box`, need the base to be valid - propagate
2473 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2476 ProjectionElem::Field(..)
2477 | ProjectionElem::Downcast(..)
2478 | ProjectionElem::Index(..)
2479 | ProjectionElem::ConstantIndex { .. }
2480 | ProjectionElem::Subslice { .. } => {
2481 // other field access
2485 // The "propagate" case. We need to check that our base is valid
2486 // for the borrow's lifetime.
2487 borrowed_projection = &proj.base;
2491 fn prove_aggregate_predicates(
2493 aggregate_kind: &AggregateKind<'tcx>,
2496 let tcx = self.tcx();
2499 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2500 aggregate_kind, location
2503 let instantiated_predicates = match aggregate_kind {
2504 AggregateKind::Adt(def, _, substs, _, _) => {
2505 tcx.predicates_of(def.did).instantiate(tcx, substs)
2508 // For closures, we have some **extra requirements** we
2510 // have to check. In particular, in their upvars and
2511 // signatures, closures often reference various regions
2512 // from the surrounding function -- we call those the
2513 // closure's free regions. When we borrow-check (and hence
2514 // region-check) closures, we may find that the closure
2515 // requires certain relationships between those free
2516 // regions. However, because those free regions refer to
2517 // portions of the CFG of their caller, the closure is not
2518 // in a position to verify those relationships. In that
2519 // case, the requirements get "propagated" to us, and so
2520 // we have to solve them here where we instantiate the
2523 // Despite the opacity of the previous parapgrah, this is
2524 // actually relatively easy to understand in terms of the
2525 // desugaring. A closure gets desugared to a struct, and
2526 // these extra requirements are basically like where
2527 // clauses on the struct.
2528 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2529 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2530 self.prove_closure_bounds(tcx, *def_id, substs, location)
2533 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2536 self.normalize_and_prove_instantiated_predicates(
2537 instantiated_predicates,
2538 location.to_locations(),
2542 fn prove_closure_bounds(
2546 substs: SubstsRef<'tcx>,
2548 ) -> ty::InstantiatedPredicates<'tcx> {
2549 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2550 let closure_constraints = QueryRegionConstraints {
2551 outlives: closure_region_requirements.apply_requirements(tcx, def_id, substs),
2553 // Presently, closures never propagate member
2554 // constraints to their parents -- they are enforced
2555 // locally. This is largely a non-issue as member
2556 // constraints only come from `-> impl Trait` and
2557 // friends which don't appear (thus far...) in
2559 member_constraints: vec![],
2562 let bounds_mapping = closure_constraints
2566 .filter_map(|(idx, constraint)| {
2567 let ty::OutlivesPredicate(k1, r2) =
2568 constraint.no_bound_vars().unwrap_or_else(|| {
2569 bug!("query_constraint {:?} contained bound vars", constraint,);
2573 UnpackedKind::Lifetime(r1) => {
2574 // constraint is r1: r2
2575 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2576 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2577 let outlives_requirements =
2578 &closure_region_requirements.outlives_requirements[idx];
2582 outlives_requirements.category,
2583 outlives_requirements.blame_span,
2587 UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2592 let existing = self.borrowck_context
2594 .closure_bounds_mapping
2595 .insert(location, bounds_mapping);
2598 "Multiple closures at the same location."
2601 self.push_region_constraints(
2602 location.to_locations(),
2603 ConstraintCategory::ClosureBounds,
2604 &closure_constraints,
2608 tcx.predicates_of(def_id).instantiate(tcx, substs)
2613 trait_ref: ty::TraitRef<'tcx>,
2614 locations: Locations,
2615 category: ConstraintCategory,
2617 self.prove_predicates(
2618 Some(ty::Predicate::Trait(
2619 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2626 fn normalize_and_prove_instantiated_predicates(
2628 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2629 locations: Locations,
2631 for predicate in instantiated_predicates.predicates {
2632 let predicate = self.normalize(predicate, locations);
2633 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2637 fn prove_predicates(
2639 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2640 locations: Locations,
2641 category: ConstraintCategory,
2643 for predicate in predicates {
2645 "prove_predicates(predicate={:?}, locations={:?})",
2646 predicate, locations,
2649 self.prove_predicate(predicate, locations, category);
2655 predicate: ty::Predicate<'tcx>,
2656 locations: Locations,
2657 category: ConstraintCategory,
2660 "prove_predicate(predicate={:?}, location={:?})",
2661 predicate, locations,
2664 let param_env = self.param_env;
2665 self.fully_perform_op(
2668 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2669 ).unwrap_or_else(|NoSolution| {
2670 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2674 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2675 self.last_span = body.span;
2676 debug!("run_on_mir: {:?}", body.span);
2678 for (local, local_decl) in body.local_decls.iter_enumerated() {
2679 self.check_local(body, local, local_decl);
2682 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2683 let mut location = Location {
2687 for stmt in &block_data.statements {
2688 if !stmt.source_info.span.is_dummy() {
2689 self.last_span = stmt.source_info.span;
2691 self.check_stmt(body, stmt, location);
2692 location.statement_index += 1;
2695 self.check_terminator(body, block_data.terminator(), location);
2696 self.check_iscleanup(body, block_data);
2700 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2702 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2704 debug!("normalize(value={:?}, location={:?})", value, location);
2705 let param_env = self.param_env;
2706 self.fully_perform_op(
2707 location.to_locations(),
2708 ConstraintCategory::Boring,
2709 param_env.and(type_op::normalize::Normalize::new(value)),
2710 ).unwrap_or_else(|NoSolution| {
2711 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2717 trait NormalizeLocation: fmt::Debug + Copy {
2718 fn to_locations(self) -> Locations;
2721 impl NormalizeLocation for Locations {
2722 fn to_locations(self) -> Locations {
2727 impl NormalizeLocation for Location {
2728 fn to_locations(self) -> Locations {
2729 Locations::Single(self)
2733 #[derive(Debug, Default)]
2734 struct ObligationAccumulator<'tcx> {
2735 obligations: PredicateObligations<'tcx>,
2738 impl<'tcx> ObligationAccumulator<'tcx> {
2739 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2740 let InferOk { value, obligations } = value;
2741 self.obligations.extend(obligations);
2745 fn into_vec(self) -> PredicateObligations<'tcx> {