1 //! This pass type-checks the MIR to ensure it is not broken.
3 #![allow(unreachable_code)]
5 use crate::borrow_check::borrow_set::BorrowSet;
6 use crate::borrow_check::location::LocationTable;
7 use crate::borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
8 use crate::borrow_check::nll::facts::AllFacts;
9 use crate::borrow_check::nll::region_infer::values::LivenessValues;
10 use crate::borrow_check::nll::region_infer::values::PlaceholderIndex;
11 use crate::borrow_check::nll::region_infer::values::PlaceholderIndices;
12 use crate::borrow_check::nll::region_infer::values::RegionValueElements;
13 use crate::borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
14 use crate::borrow_check::nll::renumber;
15 use crate::borrow_check::nll::type_check::free_region_relations::{
16 CreateResult, UniversalRegionRelations,
18 use crate::borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
19 use crate::borrow_check::nll::ToRegionVid;
20 use crate::dataflow::move_paths::MoveData;
21 use crate::dataflow::FlowAtLocation;
22 use crate::dataflow::MaybeInitializedPlaces;
25 use rustc::hir::def_id::DefId;
26 use rustc::infer::canonical::QueryRegionConstraint;
27 use rustc::infer::outlives::env::RegionBoundPairs;
28 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
29 use rustc::infer::type_variable::TypeVariableOrigin;
30 use rustc::mir::interpret::{InterpError::BoundsCheck, ConstValue};
31 use rustc::mir::tcx::PlaceTy;
32 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
34 use rustc::traits::query::type_op;
35 use rustc::traits::query::type_op::custom::CustomTypeOp;
36 use rustc::traits::query::{Fallible, NoSolution};
37 use rustc::traits::{ObligationCause, PredicateObligations};
38 use rustc::ty::adjustment::{PointerCast};
39 use rustc::ty::fold::TypeFoldable;
40 use rustc::ty::subst::{Subst, SubstsRef, UnpackedKind, UserSubsts};
42 self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, UserType,
43 CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
44 UserTypeAnnotationIndex,
46 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
47 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
48 use rustc::ty::layout::VariantIdx;
50 use std::{fmt, iter, mem};
51 use syntax_pos::{Span, DUMMY_SP};
53 macro_rules! span_mirbug {
54 ($context:expr, $elem:expr, $($message:tt)*) => ({
55 $crate::borrow_check::nll::type_check::mirbug(
59 "broken MIR in {:?} ({:?}): {}",
62 format_args!($($message)*),
68 macro_rules! span_mirbug_and_err {
69 ($context:expr, $elem:expr, $($message:tt)*) => ({
71 span_mirbug!($context, $elem, $($message)*);
77 mod constraint_conversion;
78 pub mod free_region_relations;
83 /// Type checks the given `mir` in the context of the inference
84 /// context `infcx`. Returns any region constraints that have yet to
85 /// be proven. This result is includes liveness constraints that
86 /// ensure that regions appearing in the types of all local variables
87 /// are live at all points where that local variable may later be
90 /// This phase of type-check ought to be infallible -- this is because
91 /// the original, HIR-based type-check succeeded. So if any errors
92 /// occur here, we will get a `bug!` reported.
96 /// - `infcx` -- inference context to use
97 /// - `param_env` -- parameter environment to use for trait solving
98 /// - `mir` -- MIR to type-check
99 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
100 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
101 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
102 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
103 /// to outlive; should represent the fn body
104 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
105 /// the types of the input parameters found in the MIR itself will be equated with these
106 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
107 /// the type for the RETURN_PLACE will be equated with this
108 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
109 /// constraints for the regions in the types of variables
110 /// - `flow_inits` -- results of a maybe-init dataflow analysis
111 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
112 pub(crate) fn type_check<'gcx, 'tcx>(
113 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
114 param_env: ty::ParamEnv<'gcx>,
117 universal_regions: &Rc<UniversalRegions<'tcx>>,
118 location_table: &LocationTable,
119 borrow_set: &BorrowSet<'tcx>,
120 all_facts: &mut Option<AllFacts>,
121 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
122 move_data: &MoveData<'tcx>,
123 elements: &Rc<RegionValueElements>,
124 ) -> MirTypeckResults<'tcx> {
125 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
126 let mut constraints = MirTypeckRegionConstraints {
127 placeholder_indices: PlaceholderIndices::default(),
128 placeholder_index_to_region: IndexVec::default(),
129 liveness_constraints: LivenessValues::new(elements.clone()),
130 outlives_constraints: ConstraintSet::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(mir, universal_regions, &normalized_inputs_and_output);
166 liveness::generate(&mut cx, mir, elements, flow_inits, move_data, location_table);
168 translate_outlives_facts(cx.borrowck_context);
174 universal_region_relations,
178 fn type_check_internal<'a, 'gcx, 'tcx, R>(
179 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
181 param_env: ty::ParamEnv<'gcx>,
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, 'gcx, '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, mir);
201 verifier.visit_mir(mir);
202 verifier.errors_reported
205 if !errors_reported {
206 // if verifier failed, don't do further checks to avoid ICEs
207 checker.typeck_mir(mir);
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.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: 'a, 'gcx: 'tcx, 'tcx: 'b> {
255 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
259 errors_reported: bool,
262 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, '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.mir, 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_mir(&mut self, mir: &Mir<'tcx>) {
372 self.sanitize_type(&"return type", mir.return_ty());
373 for local_decl in &mir.local_decls {
374 self.sanitize_type(local_decl, local_decl.ty);
376 if self.errors_reported {
383 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
384 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'b Mir<'tcx>) -> Self {
387 mir_def_id: cx.mir_def_id,
390 errors_reported: false,
394 fn tcx(&self) -> TyCtxt<'a, 'gcx, '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);
450 let place_ty = match place {
451 Place::Base(PlaceBase::Local(index)) =>
452 PlaceTy::from_ty(self.mir.local_decls[*index].ty),
453 Place::Base(PlaceBase::Static(box Static { kind, ty: sty })) => {
454 let sty = self.sanitize_type(place, sty);
456 |verifier: &mut TypeVerifier<'a, 'b, 'gcx, 'tcx>,
460 if let Err(terr) = verifier.cx.eq_types(
463 location.to_locations(),
464 ConstraintCategory::Boring,
469 "bad promoted type ({:?}: {:?}): {:?}",
477 StaticKind::Promoted(promoted) => {
478 if !self.errors_reported {
479 let promoted_mir = &self.mir.promoted[*promoted];
480 self.sanitize_promoted(promoted_mir, location);
482 let promoted_ty = promoted_mir.return_ty();
483 check_err(self, place, promoted_ty, sty);
486 StaticKind::Static(def_id) => {
487 let ty = self.tcx().type_of(*def_id);
488 let ty = self.cx.normalize(ty, location);
490 check_err(self, place, ty, sty);
493 PlaceTy::from_ty(sty)
495 Place::Projection(ref proj) => {
496 let base_context = if context.is_mutating_use() {
497 PlaceContext::MutatingUse(MutatingUseContext::Projection)
499 PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
501 let base_ty = self.sanitize_place(&proj.base, location, base_context);
502 if base_ty.variant_index.is_none() {
503 if base_ty.ty.references_error() {
504 assert!(self.errors_reported);
505 return PlaceTy::from_ty(self.tcx().types.err);
508 self.sanitize_projection(base_ty, &proj.elem, place, location)
511 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
512 let tcx = self.tcx();
513 let trait_ref = ty::TraitRef {
514 def_id: tcx.lang_items().copy_trait().unwrap(),
515 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
518 // In order to have a Copy operand, the type T of the
519 // value must be Copy. Note that we prove that T: Copy,
520 // rather than using the `is_copy_modulo_regions`
521 // test. This is important because
522 // `is_copy_modulo_regions` ignores the resulting region
523 // obligations and assumes they pass. This can result in
524 // bounds from Copy impls being unsoundly ignored (e.g.,
525 // #29149). Note that we decide to use Copy before knowing
526 // whether the bounds fully apply: in effect, the rule is
527 // that if a value of some type could implement Copy, then
529 self.cx.prove_trait_ref(
531 location.to_locations(),
532 ConstraintCategory::CopyBound,
538 fn sanitize_promoted(&mut self, promoted_mir: &'b Mir<'tcx>, location: Location) {
539 // Determine the constraints from the promoted MIR by running the type
540 // checker on the promoted MIR, then transfer the constraints back to
541 // the main MIR, changing the locations to the provided location.
543 let parent_mir = mem::replace(&mut self.mir, promoted_mir);
545 let all_facts = &mut None;
546 let mut constraints = Default::default();
547 let mut closure_bounds = Default::default();
548 // Don't try to add borrow_region facts for the promoted MIR
549 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
551 // Use a new sets of constraints and closure bounds so that we can
552 // modify their locations.
554 &mut self.cx.borrowck_context.constraints.outlives_constraints,
558 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
562 self.visit_mir(promoted_mir);
564 if !self.errors_reported {
565 // if verifier failed, don't do further checks to avoid ICEs
566 self.cx.typeck_mir(promoted_mir);
569 self.mir = parent_mir;
570 // Merge the outlives constraints back in, at the given location.
571 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
573 &mut self.cx.borrowck_context.constraints.outlives_constraints,
577 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
581 let locations = location.to_locations();
582 for constraint in constraints.iter() {
583 let mut constraint = *constraint;
584 constraint.locations = locations;
585 if let ConstraintCategory::Return
586 | ConstraintCategory::UseAsConst
587 | ConstraintCategory::UseAsStatic = constraint.category
589 // "Returning" from a promoted is an assigment to a
590 // temporary from the user's point of view.
591 constraint.category = ConstraintCategory::Boring;
593 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
596 if !closure_bounds.is_empty() {
597 let combined_bounds_mapping = closure_bounds
599 .flat_map(|(_, value)| value)
601 let existing = self.cx.borrowck_context
603 .closure_bounds_mapping
604 .insert(location, combined_bounds_mapping);
607 "Multiple promoteds/closures at the same location."
612 fn sanitize_projection(
615 pi: &PlaceElem<'tcx>,
619 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
620 let tcx = self.tcx();
621 let base_ty = base.ty;
623 ProjectionElem::Deref => {
624 let deref_ty = base_ty.builtin_deref(true);
626 deref_ty.map(|t| t.ty).unwrap_or_else(|| {
627 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
631 ProjectionElem::Index(i) => {
632 let index_ty = Place::Base(PlaceBase::Local(i)).ty(self.mir, tcx).ty;
633 if index_ty != tcx.types.usize {
635 span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
639 base_ty.builtin_index().unwrap_or_else(|| {
640 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
645 ProjectionElem::ConstantIndex { .. } => {
646 // consider verifying in-bounds
648 base_ty.builtin_index().unwrap_or_else(|| {
649 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
653 ProjectionElem::Subslice { from, to } => PlaceTy::from_ty(
655 ty::Array(inner, size) => {
656 let size = size.unwrap_usize(tcx);
657 let min_size = (from as u64) + (to as u64);
658 if let Some(rest_size) = size.checked_sub(min_size) {
659 tcx.mk_array(inner, rest_size)
661 span_mirbug_and_err!(
664 "taking too-small slice of {:?}",
669 ty::Slice(..) => base_ty,
670 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
673 ProjectionElem::Downcast(maybe_name, index) => match base_ty.sty {
674 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
675 if index.as_usize() >= adt_def.variants.len() {
677 span_mirbug_and_err!(
680 "cast to variant #{:?} but enum only has {:?}",
682 adt_def.variants.len()
688 variant_index: Some(index),
692 // We do not need to handle generators here, because this runs
693 // before the generator transform stage.
695 let ty = if let Some(name) = maybe_name {
696 span_mirbug_and_err!(
699 "can't downcast {:?} as {:?}",
704 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
709 ProjectionElem::Field(field, fty) => {
710 let fty = self.sanitize_type(place, fty);
711 match self.field_ty(place, base, field, location) {
712 Ok(ty) => if let Err(terr) = self.cx.eq_types(
715 location.to_locations(),
716 ConstraintCategory::Boring,
721 "bad field access ({:?}: {:?}): {:?}",
727 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
730 "accessed field #{} but variant only has {}",
735 PlaceTy::from_ty(fty)
740 fn error(&mut self) -> Ty<'tcx> {
741 self.errors_reported = true;
747 parent: &dyn fmt::Debug,
748 base_ty: PlaceTy<'tcx>,
751 ) -> Result<Ty<'tcx>, FieldAccessError> {
752 let tcx = self.tcx();
754 let (variant, substs) = match base_ty {
755 PlaceTy { ty, variant_index: Some(variant_index) } => match ty.sty {
756 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
757 ty::Generator(def_id, substs, _) => {
758 let mut variants = substs.state_tys(def_id, tcx);
759 let mut variant = match variants.nth(variant_index.into()) {
762 bug!("variant_index of generator out of range: {:?}/{:?}",
764 substs.state_tys(def_id, tcx).count())
767 return match variant.nth(field.index()) {
769 None => Err(FieldAccessError::OutOfRange {
770 field_count: variant.count(),
774 _ => bug!("can't have downcast of non-adt non-generator type"),
776 PlaceTy { ty, variant_index: None } => match ty.sty {
777 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
778 (&adt_def.variants[VariantIdx::new(0)], substs),
779 ty::Closure(def_id, substs) => {
780 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
782 None => Err(FieldAccessError::OutOfRange {
783 field_count: substs.upvar_tys(def_id, tcx).count(),
787 ty::Generator(def_id, substs, _) => {
788 // Only prefix fields (upvars and current state) are
789 // accessible without a variant index.
790 return match substs.prefix_tys(def_id, tcx).nth(field.index()) {
792 None => Err(FieldAccessError::OutOfRange {
793 field_count: substs.prefix_tys(def_id, tcx).count(),
798 return match tys.get(field.index()) {
799 Some(&ty) => Ok(ty.expect_ty()),
800 None => Err(FieldAccessError::OutOfRange {
801 field_count: tys.len(),
806 return Ok(span_mirbug_and_err!(
809 "can't project out of {:?}",
816 if let Some(field) = variant.fields.get(field.index()) {
817 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
819 Err(FieldAccessError::OutOfRange {
820 field_count: variant.fields.len(),
826 /// The MIR type checker. Visits the MIR and enforces all the
827 /// constraints needed for it to be valid and well-typed. Along the
828 /// way, it accrues region constraints -- these can later be used by
829 /// NLL region checking.
830 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
831 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
832 param_env: ty::ParamEnv<'gcx>,
834 /// User type annotations are shared between the main MIR and the MIR of
835 /// all of the promoted items.
836 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
838 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
839 implicit_region_bound: ty::Region<'tcx>,
840 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
841 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
842 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
845 struct BorrowCheckContext<'a, 'tcx: 'a> {
846 universal_regions: &'a UniversalRegions<'tcx>,
847 location_table: &'a LocationTable,
848 all_facts: &'a mut Option<AllFacts>,
849 borrow_set: &'a BorrowSet<'tcx>,
850 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
853 crate struct MirTypeckResults<'tcx> {
854 crate constraints: MirTypeckRegionConstraints<'tcx>,
855 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
858 /// A collection of region constraints that must be satisfied for the
859 /// program to be considered well-typed.
860 crate struct MirTypeckRegionConstraints<'tcx> {
861 /// Maps from a `ty::Placeholder` to the corresponding
862 /// `PlaceholderIndex` bit that we will use for it.
864 /// To keep everything in sync, do not insert this set
865 /// directly. Instead, use the `placeholder_region` helper.
866 crate placeholder_indices: PlaceholderIndices,
868 /// Each time we add a placeholder to `placeholder_indices`, we
869 /// also create a corresponding "representative" region vid for
870 /// that wraps it. This vector tracks those. This way, when we
871 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
872 /// the same underlying `RegionVid`.
873 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
875 /// In general, the type-checker is not responsible for enforcing
876 /// liveness constraints; this job falls to the region inferencer,
877 /// which performs a liveness analysis. However, in some limited
878 /// cases, the MIR type-checker creates temporary regions that do
879 /// not otherwise appear in the MIR -- in particular, the
880 /// late-bound regions that it instantiates at call-sites -- and
881 /// hence it must report on their liveness constraints.
882 crate liveness_constraints: LivenessValues<RegionVid>,
884 crate outlives_constraints: ConstraintSet,
886 crate closure_bounds_mapping:
887 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
889 crate type_tests: Vec<TypeTest<'tcx>>,
892 impl MirTypeckRegionConstraints<'tcx> {
893 fn placeholder_region(
895 infcx: &InferCtxt<'_, '_, 'tcx>,
896 placeholder: ty::PlaceholderRegion,
897 ) -> ty::Region<'tcx> {
898 let placeholder_index = self.placeholder_indices.insert(placeholder);
899 match self.placeholder_index_to_region.get(placeholder_index) {
902 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
903 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
904 self.placeholder_index_to_region.push(region);
911 /// The `Locations` type summarizes *where* region constraints are
912 /// required to hold. Normally, this is at a particular point which
913 /// created the obligation, but for constraints that the user gave, we
914 /// want the constraint to hold at all points.
915 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
917 /// Indicates that a type constraint should always be true. This
918 /// is particularly important in the new borrowck analysis for
919 /// things like the type of the return slot. Consider this
923 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
925 /// return &y; // error
929 /// Here, we wind up with the signature from the return type being
930 /// something like `&'1 u32` where `'1` is a universal region. But
931 /// the type of the return slot `_0` is something like `&'2 u32`
932 /// where `'2` is an existential region variable. The type checker
933 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
934 /// older NLL analysis, we required this only at the entry point
935 /// to the function. By the nature of the constraints, this wound
936 /// up propagating to all points reachable from start (because
937 /// `'1` -- as a universal region -- is live everywhere). In the
938 /// newer analysis, though, this doesn't work: `_0` is considered
939 /// dead at the start (it has no usable value) and hence this type
940 /// equality is basically a no-op. Then, later on, when we do `_0
941 /// = &'3 y`, that region `'3` never winds up related to the
942 /// universal region `'1` and hence no error occurs. Therefore, we
943 /// use Locations::All instead, which ensures that the `'1` and
944 /// `'2` are equal everything. We also use this for other
945 /// user-given type annotations; e.g., if the user wrote `let mut
946 /// x: &'static u32 = ...`, we would ensure that all values
947 /// assigned to `x` are of `'static` lifetime.
949 /// The span points to the place the constraint arose. For example,
950 /// it points to the type in a user-given type annotation. If
951 /// there's no sensible span then it's DUMMY_SP.
954 /// An outlives constraint that only has to hold at a single location,
955 /// usually it represents a point where references flow from one spot to
956 /// another (e.g., `x = y`)
961 pub fn from_location(&self) -> Option<Location> {
963 Locations::All(_) => None,
964 Locations::Single(from_location) => Some(*from_location),
968 /// Gets a span representing the location.
969 pub fn span(&self, mir: &Mir<'_>) -> Span {
971 Locations::All(span) => *span,
972 Locations::Single(l) => mir.source_info(*l).span,
977 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
979 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
982 param_env: ty::ParamEnv<'gcx>,
983 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
984 implicit_region_bound: ty::Region<'tcx>,
985 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
986 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
988 let mut checker = Self {
992 user_type_annotations: &mir.user_type_annotations,
995 implicit_region_bound,
997 reported_errors: Default::default(),
998 universal_region_relations,
1000 checker.check_user_type_annotations();
1004 /// Equate the inferred type and the annotated type for user type annotations
1005 fn check_user_type_annotations(&mut self) {
1007 "check_user_type_annotations: user_type_annotations={:?}",
1008 self.user_type_annotations
1010 for user_annotation in self.user_type_annotations {
1011 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1012 let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
1016 UserType::Ty(mut ty) => {
1017 ty = self.normalize(ty, Locations::All(span));
1019 if let Err(terr) = self.eq_types(
1022 Locations::All(span),
1023 ConstraintCategory::BoringNoLocation,
1028 "bad user type ({:?} = {:?}): {:?}",
1035 self.prove_predicate(
1036 ty::Predicate::WellFormed(inferred_ty),
1037 Locations::All(span),
1038 ConstraintCategory::TypeAnnotation,
1041 UserType::TypeOf(def_id, user_substs) => {
1042 if let Err(terr) = self.fully_perform_op(
1043 Locations::All(span),
1044 ConstraintCategory::BoringNoLocation,
1045 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1046 inferred_ty, def_id, user_substs,
1052 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1064 /// Given some operation `op` that manipulates types, proves
1065 /// predicates, or otherwise uses the inference context, executes
1066 /// `op` and then executes all the further obligations that `op`
1067 /// returns. This will yield a set of outlives constraints amongst
1068 /// regions which are extracted and stored as having occurred at
1071 /// **Any `rustc::infer` operations that might generate region
1072 /// constraints should occur within this method so that those
1073 /// constraints can be properly localized!**
1074 fn fully_perform_op<R>(
1076 locations: Locations,
1077 category: ConstraintCategory,
1078 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
1080 let (r, opt_data) = op.fully_perform(self.infcx)?;
1082 if let Some(data) = &opt_data {
1083 self.push_region_constraints(locations, category, data);
1089 fn push_region_constraints(
1091 locations: Locations,
1092 category: ConstraintCategory,
1093 data: &[QueryRegionConstraint<'tcx>],
1096 "push_region_constraints: constraints generated at {:?} are {:#?}",
1100 constraint_conversion::ConstraintConversion::new(
1102 self.borrowck_context.universal_regions,
1103 self.region_bound_pairs,
1104 Some(self.implicit_region_bound),
1108 &mut self.borrowck_context.constraints,
1109 ).convert_all(&data);
1112 /// Convenient wrapper around `relate_tys::relate_types` -- see
1113 /// that fn for docs.
1119 locations: Locations,
1120 category: ConstraintCategory,
1122 relate_tys::relate_types(
1129 Some(self.borrowck_context),
1137 locations: Locations,
1138 category: ConstraintCategory,
1140 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1143 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1144 /// variables in `sub` with their inferred definitions and try
1145 /// again. This is used for opaque types in places (e.g., `let x:
1146 /// impl Foo = ..`).
1147 fn sub_types_or_anon(
1151 locations: Locations,
1152 category: ConstraintCategory,
1154 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1155 if let ty::Opaque(..) = sup.sty {
1156 // When you have `let x: impl Foo = ...` in a closure,
1157 // the resulting inferend values are stored with the
1158 // def-id of the base function.
1159 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1160 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1172 locations: Locations,
1173 category: ConstraintCategory,
1175 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1178 fn relate_type_and_user_type(
1182 user_ty: &UserTypeProjection,
1183 locations: Locations,
1184 category: ConstraintCategory,
1187 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1188 a, v, user_ty, locations,
1191 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1192 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1194 let tcx = self.infcx.tcx;
1196 for proj in &user_ty.projs {
1197 let projected_ty = curr_projected_ty.projection_ty_core(tcx, proj, |this, field, &()| {
1198 let ty = this.field_ty(tcx, field);
1199 self.normalize(ty, locations)
1201 curr_projected_ty = projected_ty;
1203 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1204 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1206 let ty = curr_projected_ty.ty;
1207 self.relate_types(a, v, ty, locations, category)?;
1212 fn eq_opaque_type_and_type(
1214 revealed_ty: Ty<'tcx>,
1216 anon_owner_def_id: DefId,
1217 locations: Locations,
1218 category: ConstraintCategory,
1221 "eq_opaque_type_and_type( \
1224 revealed_ty, anon_ty
1226 let infcx = self.infcx;
1227 let tcx = infcx.tcx;
1228 let param_env = self.param_env;
1229 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1230 let opaque_type_map = self.fully_perform_op(
1235 let mut obligations = ObligationAccumulator::default();
1237 let dummy_body_id = ObligationCause::dummy().body_id;
1238 let (output_ty, opaque_type_map) =
1239 obligations.add(infcx.instantiate_opaque_types(
1246 "eq_opaque_type_and_type: \
1247 instantiated output_ty={:?} \
1248 opaque_type_map={:#?} \
1250 output_ty, opaque_type_map, revealed_ty
1252 obligations.add(infcx
1253 .at(&ObligationCause::dummy(), param_env)
1254 .eq(output_ty, revealed_ty)?);
1256 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1257 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1258 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1259 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1261 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1262 opaque_decl.concrete_ty,
1263 infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1266 obligations.add(infcx
1267 .at(&ObligationCause::dummy(), param_env)
1268 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1271 debug!("eq_opaque_type_and_type: equated");
1274 value: Some(opaque_type_map),
1275 obligations: obligations.into_vec(),
1278 || "input_output".to_string(),
1282 let universal_region_relations = self.universal_region_relations;
1284 // Finally, if we instantiated the anon types successfully, we
1285 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1286 // prove that `T: Iterator` where `T` is the type we
1287 // instantiated it with).
1288 if let Some(opaque_type_map) = opaque_type_map {
1289 for (opaque_def_id, opaque_decl) in opaque_type_map {
1290 self.fully_perform_op(
1292 ConstraintCategory::OpaqueType,
1295 infcx.constrain_opaque_type(
1298 universal_region_relations,
1302 obligations: vec![],
1305 || "opaque_type_map".to_string(),
1313 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1317 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1318 debug!("check_stmt: {:?}", stmt);
1319 let tcx = self.tcx();
1321 StatementKind::Assign(ref place, ref rv) => {
1322 // Assignments to temporaries are not "interesting";
1323 // they are not caused by the user, but rather artifacts
1324 // of lowering. Assignments to other sorts of places *are* interesting
1326 let category = match *place {
1327 Place::Base(PlaceBase::Local(RETURN_PLACE)) => if let BorrowCheckContext {
1330 defining_ty: DefiningTy::Const(def_id, _),
1334 } = self.borrowck_context
1336 if tcx.is_static(*def_id) {
1337 ConstraintCategory::UseAsStatic
1339 ConstraintCategory::UseAsConst
1342 ConstraintCategory::Return
1344 Place::Base(PlaceBase::Local(l))
1345 if !mir.local_decls[l].is_user_variable.is_some() => {
1346 ConstraintCategory::Boring
1348 _ => ConstraintCategory::Assignment,
1351 let place_ty = place.ty(mir, tcx).ty;
1352 let rv_ty = rv.ty(mir, tcx);
1354 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1359 "bad assignment ({:?} = {:?}): {:?}",
1366 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1367 if let Err(terr) = self.relate_type_and_user_type(
1369 ty::Variance::Invariant,
1370 &UserTypeProjection { base: annotation_index, projs: vec![], },
1371 location.to_locations(),
1372 ConstraintCategory::Boring,
1374 let annotation = &self.user_type_annotations[annotation_index];
1378 "bad user type on rvalue ({:?} = {:?}): {:?}",
1386 self.check_rvalue(mir, rv, location);
1387 if !self.tcx().features().unsized_locals {
1388 let trait_ref = ty::TraitRef {
1389 def_id: tcx.lang_items().sized_trait().unwrap(),
1390 substs: tcx.mk_substs_trait(place_ty, &[]),
1392 self.prove_trait_ref(
1394 location.to_locations(),
1395 ConstraintCategory::SizedBound,
1399 StatementKind::SetDiscriminant {
1403 let place_type = place.ty(mir, tcx).ty;
1404 let adt = match place_type.sty {
1405 ty::Adt(adt, _) if adt.is_enum() => adt,
1408 stmt.source_info.span,
1409 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1415 if variant_index.as_usize() >= adt.variants.len() {
1417 stmt.source_info.span,
1418 "bad set discriminant ({:?} = {:?}): value of of range",
1424 StatementKind::AscribeUserType(ref place, variance, box ref projection) => {
1425 let place_ty = place.ty(mir, tcx).ty;
1426 if let Err(terr) = self.relate_type_and_user_type(
1430 Locations::All(stmt.source_info.span),
1431 ConstraintCategory::TypeAnnotation,
1433 let annotation = &self.user_type_annotations[projection.base];
1437 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1445 StatementKind::FakeRead(..)
1446 | StatementKind::StorageLive(..)
1447 | StatementKind::StorageDead(..)
1448 | StatementKind::InlineAsm { .. }
1449 | StatementKind::Retag { .. }
1450 | StatementKind::Nop => {}
1454 fn check_terminator(
1457 term: &Terminator<'tcx>,
1458 term_location: Location,
1460 debug!("check_terminator: {:?}", term);
1461 let tcx = self.tcx();
1463 TerminatorKind::Goto { .. }
1464 | TerminatorKind::Resume
1465 | TerminatorKind::Abort
1466 | TerminatorKind::Return
1467 | TerminatorKind::GeneratorDrop
1468 | TerminatorKind::Unreachable
1469 | TerminatorKind::Drop { .. }
1470 | TerminatorKind::FalseEdges { .. }
1471 | TerminatorKind::FalseUnwind { .. } => {
1472 // no checks needed for these
1475 TerminatorKind::DropAndReplace {
1481 let place_ty = location.ty(mir, tcx).ty;
1482 let rv_ty = value.ty(mir, tcx);
1484 let locations = term_location.to_locations();
1486 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1491 "bad DropAndReplace ({:?} = {:?}): {:?}",
1498 TerminatorKind::SwitchInt {
1503 let discr_ty = discr.ty(mir, tcx);
1504 if let Err(terr) = self.sub_types(
1507 term_location.to_locations(),
1508 ConstraintCategory::Assignment,
1513 "bad SwitchInt ({:?} on {:?}): {:?}",
1519 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1520 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1522 // FIXME: check the values
1524 TerminatorKind::Call {
1531 let func_ty = func.ty(mir, tcx);
1532 debug!("check_terminator: call, func_ty={:?}", func_ty);
1533 let sig = match func_ty.sty {
1534 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1536 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1540 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1541 term.source_info.span,
1542 LateBoundRegionConversionTime::FnCall,
1545 let sig = self.normalize(sig, term_location);
1546 self.check_call_dest(mir, term, &sig, destination, term_location);
1548 self.prove_predicates(
1549 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1550 term_location.to_locations(),
1551 ConstraintCategory::Boring,
1554 // The ordinary liveness rules will ensure that all
1555 // regions in the type of the callee are live here. We
1556 // then further constrain the late-bound regions that
1557 // were instantiated at the call site to be live as
1558 // well. The resulting is that all the input (and
1559 // output) types in the signature must be live, since
1560 // all the inputs that fed into it were live.
1561 for &late_bound_region in map.values() {
1562 let region_vid = self.borrowck_context
1564 .to_region_vid(late_bound_region);
1565 self.borrowck_context
1567 .liveness_constraints
1568 .add_element(region_vid, term_location);
1571 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1573 TerminatorKind::Assert {
1574 ref cond, ref msg, ..
1576 let cond_ty = cond.ty(mir, tcx);
1577 if cond_ty != tcx.types.bool {
1578 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1581 if let BoundsCheck { ref len, ref index } = *msg {
1582 if len.ty(mir, tcx) != tcx.types.usize {
1583 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1585 if index.ty(mir, tcx) != tcx.types.usize {
1586 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1590 TerminatorKind::Yield { ref value, .. } => {
1591 let value_ty = value.ty(mir, tcx);
1592 match mir.yield_ty {
1593 None => span_mirbug!(self, term, "yield in non-generator"),
1595 if let Err(terr) = self.sub_types(
1598 term_location.to_locations(),
1599 ConstraintCategory::Yield,
1604 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1619 term: &Terminator<'tcx>,
1620 sig: &ty::FnSig<'tcx>,
1621 destination: &Option<(Place<'tcx>, BasicBlock)>,
1622 term_location: Location,
1624 let tcx = self.tcx();
1625 match *destination {
1626 Some((ref dest, _target_block)) => {
1627 let dest_ty = dest.ty(mir, tcx).ty;
1628 let category = match *dest {
1629 Place::Base(PlaceBase::Local(RETURN_PLACE)) => {
1630 if let BorrowCheckContext {
1633 defining_ty: DefiningTy::Const(def_id, _),
1637 } = self.borrowck_context
1639 if tcx.is_static(*def_id) {
1640 ConstraintCategory::UseAsStatic
1642 ConstraintCategory::UseAsConst
1645 ConstraintCategory::Return
1648 Place::Base(PlaceBase::Local(l))
1649 if !mir.local_decls[l].is_user_variable.is_some() => {
1650 ConstraintCategory::Boring
1652 _ => ConstraintCategory::Assignment,
1655 let locations = term_location.to_locations();
1658 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1663 "call dest mismatch ({:?} <- {:?}): {:?}",
1670 // When `#![feature(unsized_locals)]` is not enabled,
1671 // this check is done at `check_local`.
1672 if self.tcx().features().unsized_locals {
1673 let span = term.source_info.span;
1674 self.ensure_place_sized(dest_ty, span);
1678 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1679 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1685 fn check_call_inputs(
1688 term: &Terminator<'tcx>,
1689 sig: &ty::FnSig<'tcx>,
1690 args: &[Operand<'tcx>],
1691 term_location: Location,
1692 from_hir_call: bool,
1694 debug!("check_call_inputs({:?}, {:?})", sig, args);
1695 // Do not count the `VaList` argument as a "true" argument to
1696 // a C-variadic function.
1697 let inputs = if sig.c_variadic {
1698 &sig.inputs()[..sig.inputs().len() - 1]
1702 if args.len() < inputs.len() || (args.len() > inputs.len() && !sig.c_variadic) {
1703 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1705 for (n, (fn_arg, op_arg)) in inputs.iter().zip(args).enumerate() {
1706 let op_arg_ty = op_arg.ty(mir, self.tcx());
1707 let category = if from_hir_call {
1708 ConstraintCategory::CallArgument
1710 ConstraintCategory::Boring
1713 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1718 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1728 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1729 let is_cleanup = block_data.is_cleanup;
1730 self.last_span = block_data.terminator().source_info.span;
1731 match block_data.terminator().kind {
1732 TerminatorKind::Goto { target } => {
1733 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1735 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1736 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1738 TerminatorKind::Resume => if !is_cleanup {
1739 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1741 TerminatorKind::Abort => if !is_cleanup {
1742 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1744 TerminatorKind::Return => if is_cleanup {
1745 span_mirbug!(self, block_data, "return on cleanup block")
1747 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1748 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1750 TerminatorKind::Yield { resume, drop, .. } => {
1752 span_mirbug!(self, block_data, "yield in cleanup block")
1754 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1755 if let Some(drop) = drop {
1756 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1759 TerminatorKind::Unreachable => {}
1760 TerminatorKind::Drop { target, unwind, .. }
1761 | TerminatorKind::DropAndReplace { target, unwind, .. }
1762 | TerminatorKind::Assert {
1767 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1768 if let Some(unwind) = unwind {
1770 span_mirbug!(self, block_data, "unwind on cleanup block")
1772 self.assert_iscleanup(mir, block_data, unwind, true);
1775 TerminatorKind::Call {
1780 if let &Some((_, target)) = destination {
1781 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1783 if let Some(cleanup) = cleanup {
1785 span_mirbug!(self, block_data, "cleanup on cleanup block")
1787 self.assert_iscleanup(mir, block_data, cleanup, true);
1790 TerminatorKind::FalseEdges {
1792 ref imaginary_targets,
1794 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1795 for target in imaginary_targets {
1796 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1799 TerminatorKind::FalseUnwind {
1803 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1804 if let Some(unwind) = unwind {
1809 "cleanup in cleanup block via false unwind"
1812 self.assert_iscleanup(mir, block_data, unwind, true);
1818 fn assert_iscleanup(
1821 ctxt: &dyn fmt::Debug,
1825 if mir[bb].is_cleanup != iscleanuppad {
1829 "cleanuppad mismatch: {:?} should be {:?}",
1836 fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1837 match mir.local_kind(local) {
1838 LocalKind::ReturnPointer | LocalKind::Arg => {
1839 // return values of normal functions are required to be
1840 // sized by typeck, but return values of ADT constructors are
1841 // not because we don't include a `Self: Sized` bounds on them.
1843 // Unbound parts of arguments were never required to be Sized
1844 // - maybe we should make that a warning.
1847 LocalKind::Var | LocalKind::Temp => {}
1850 // When `#![feature(unsized_locals)]` is enabled, only function calls
1851 // and nullary ops are checked in `check_call_dest`.
1852 if !self.tcx().features().unsized_locals {
1853 let span = local_decl.source_info.span;
1854 let ty = local_decl.ty;
1855 self.ensure_place_sized(ty, span);
1859 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1860 let tcx = self.tcx();
1862 // Erase the regions from `ty` to get a global type. The
1863 // `Sized` bound in no way depends on precise regions, so this
1864 // shouldn't affect `is_sized`.
1865 let gcx = tcx.global_tcx();
1866 let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1867 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1868 // in current MIR construction, all non-control-flow rvalue
1869 // expressions evaluate through `as_temp` or `into` a return
1870 // slot or local, so to find all unsized rvalues it is enough
1871 // to check all temps, return slots and locals.
1872 if let None = self.reported_errors.replace((ty, span)) {
1873 let mut diag = struct_span_err!(
1877 "cannot move a value of type {0}: the size of {0} \
1878 cannot be statically determined",
1882 // While this is located in `nll::typeck` this error is not
1883 // an NLL error, it's a required check to prevent creation
1884 // of unsized rvalues in certain cases:
1885 // * operand of a box expression
1886 // * callee in a call expression
1892 fn aggregate_field_ty(
1894 ak: &AggregateKind<'tcx>,
1897 ) -> Result<Ty<'tcx>, FieldAccessError> {
1898 let tcx = self.tcx();
1901 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1902 let variant = &def.variants[variant_index];
1903 let adj_field_index = active_field_index.unwrap_or(field_index);
1904 if let Some(field) = variant.fields.get(adj_field_index) {
1905 Ok(self.normalize(field.ty(tcx, substs), location))
1907 Err(FieldAccessError::OutOfRange {
1908 field_count: variant.fields.len(),
1912 AggregateKind::Closure(def_id, substs) => {
1913 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1915 None => Err(FieldAccessError::OutOfRange {
1916 field_count: substs.upvar_tys(def_id, tcx).count(),
1920 AggregateKind::Generator(def_id, substs, _) => {
1921 // It doesn't make sense to look at a field beyond the prefix;
1922 // these require a variant index, and are not initialized in
1923 // aggregate rvalues.
1924 match substs.prefix_tys(def_id, tcx).nth(field_index) {
1926 None => Err(FieldAccessError::OutOfRange {
1927 field_count: substs.prefix_tys(def_id, tcx).count(),
1931 AggregateKind::Array(ty) => Ok(ty),
1932 AggregateKind::Tuple => {
1933 unreachable!("This should have been covered in check_rvalues");
1938 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1939 let tcx = self.tcx();
1942 Rvalue::Aggregate(ak, ops) => {
1943 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1946 Rvalue::Repeat(operand, len) => if *len > 1 {
1947 let operand_ty = operand.ty(mir, tcx);
1949 let trait_ref = ty::TraitRef {
1950 def_id: tcx.lang_items().copy_trait().unwrap(),
1951 substs: tcx.mk_substs_trait(operand_ty, &[]),
1954 self.prove_trait_ref(
1956 location.to_locations(),
1957 ConstraintCategory::CopyBound,
1961 Rvalue::NullaryOp(_, ty) => {
1962 // Even with unsized locals cannot box an unsized value.
1963 if self.tcx().features().unsized_locals {
1964 let span = mir.source_info(location).span;
1965 self.ensure_place_sized(ty, span);
1968 let trait_ref = ty::TraitRef {
1969 def_id: tcx.lang_items().sized_trait().unwrap(),
1970 substs: tcx.mk_substs_trait(ty, &[]),
1973 self.prove_trait_ref(
1975 location.to_locations(),
1976 ConstraintCategory::SizedBound,
1980 Rvalue::Cast(cast_kind, op, ty) => {
1982 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1983 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1985 // The type that we see in the fcx is like
1986 // `foo::<'a, 'b>`, where `foo` is the path to a
1987 // function definition. When we extract the
1988 // signature, it comes from the `fn_sig` query,
1989 // and hence may contain unnormalized results.
1990 let fn_sig = self.normalize(fn_sig, location);
1992 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1994 if let Err(terr) = self.eq_types(
1997 location.to_locations(),
1998 ConstraintCategory::Cast,
2003 "equating {:?} with {:?} yields {:?}",
2011 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2012 let sig = match op.ty(mir, tcx).sty {
2013 ty::Closure(def_id, substs) => {
2014 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
2018 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2020 if let Err(terr) = self.eq_types(
2023 location.to_locations(),
2024 ConstraintCategory::Cast,
2029 "equating {:?} with {:?} yields {:?}",
2037 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2038 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
2040 // The type that we see in the fcx is like
2041 // `foo::<'a, 'b>`, where `foo` is the path to a
2042 // function definition. When we extract the
2043 // signature, it comes from the `fn_sig` query,
2044 // and hence may contain unnormalized results.
2045 let fn_sig = self.normalize(fn_sig, location);
2047 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2049 if let Err(terr) = self.eq_types(
2052 location.to_locations(),
2053 ConstraintCategory::Cast,
2058 "equating {:?} with {:?} yields {:?}",
2066 CastKind::Pointer(PointerCast::Unsize) => {
2068 let trait_ref = ty::TraitRef {
2069 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2070 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
2073 self.prove_trait_ref(
2075 location.to_locations(),
2076 ConstraintCategory::Cast,
2080 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2081 let ty_from = match op.ty(mir, tcx).sty {
2082 ty::RawPtr(ty::TypeAndMut {
2084 mutbl: hir::MutMutable,
2090 "unexpected base type for cast {:?}",
2096 let ty_to = match ty.sty {
2097 ty::RawPtr(ty::TypeAndMut {
2099 mutbl: hir::MutImmutable,
2105 "unexpected target type for cast {:?}",
2111 if let Err(terr) = self.sub_types(
2114 location.to_locations(),
2115 ConstraintCategory::Cast,
2120 "relating {:?} with {:?} yields {:?}",
2129 if let ty::Ref(_, mut ty_from, _) = op.ty(mir, tcx).sty {
2130 let (mut ty_to, mutability) = if let ty::RawPtr(ty::TypeAndMut {
2139 "invalid cast types {:?} -> {:?}",
2146 // Handle the direct cast from `&[T; N]` to `*const T` by unwrapping
2147 // any array we find.
2148 while let ty::Array(ty_elem_from, _) = ty_from.sty {
2149 ty_from = ty_elem_from;
2150 if let ty::Array(ty_elem_to, _) = ty_to.sty {
2157 if let hir::MutMutable = mutability {
2158 if let Err(terr) = self.eq_types(
2161 location.to_locations(),
2162 ConstraintCategory::Cast,
2167 "equating {:?} with {:?} yields {:?}",
2174 if let Err(terr) = self.sub_types(
2177 location.to_locations(),
2178 ConstraintCategory::Cast,
2183 "relating {:?} with {:?} yields {:?}",
2195 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2196 self.add_reborrow_constraint(mir, location, region, borrowed_place);
2199 Rvalue::BinaryOp(BinOp::Eq, left, right)
2200 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2201 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2202 | Rvalue::BinaryOp(BinOp::Le, left, right)
2203 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2204 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2205 let ty_left = left.ty(mir, tcx);
2206 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.sty {
2207 let ty_right = right.ty(mir, tcx);
2208 let common_ty = self.infcx.next_ty_var(
2209 TypeVariableOrigin::MiscVariable(mir.source_info(location).span),
2214 location.to_locations(),
2215 ConstraintCategory::Boring
2216 ).unwrap_or_else(|err| {
2217 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2219 if let Err(terr) = self.sub_types(
2222 location.to_locations(),
2223 ConstraintCategory::Boring
2228 "unexpected comparison types {:?} and {:?} yields {:?}",
2239 | Rvalue::BinaryOp(..)
2240 | Rvalue::CheckedBinaryOp(..)
2241 | Rvalue::UnaryOp(..)
2242 | Rvalue::Discriminant(..) => {}
2246 /// If this rvalue supports a user-given type annotation, then
2247 /// extract and return it. This represents the final type of the
2248 /// rvalue and will be unified with the inferred type.
2249 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2252 | Rvalue::Repeat(..)
2256 | Rvalue::BinaryOp(..)
2257 | Rvalue::CheckedBinaryOp(..)
2258 | Rvalue::NullaryOp(..)
2259 | Rvalue::UnaryOp(..)
2260 | Rvalue::Discriminant(..) => None,
2262 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2263 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2264 AggregateKind::Array(_) => None,
2265 AggregateKind::Tuple => None,
2266 AggregateKind::Closure(_, _) => None,
2267 AggregateKind::Generator(_, _, _) => None,
2272 fn check_aggregate_rvalue(
2275 rvalue: &Rvalue<'tcx>,
2276 aggregate_kind: &AggregateKind<'tcx>,
2277 operands: &[Operand<'tcx>],
2280 let tcx = self.tcx();
2282 self.prove_aggregate_predicates(aggregate_kind, location);
2284 if *aggregate_kind == AggregateKind::Tuple {
2285 // tuple rvalue field type is always the type of the op. Nothing to check here.
2289 for (i, operand) in operands.iter().enumerate() {
2290 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2291 Ok(field_ty) => field_ty,
2292 Err(FieldAccessError::OutOfRange { field_count }) => {
2296 "accessed field #{} but variant only has {}",
2303 let operand_ty = operand.ty(mir, tcx);
2305 if let Err(terr) = self.sub_types(
2308 location.to_locations(),
2309 ConstraintCategory::Boring,
2314 "{:?} is not a subtype of {:?}: {:?}",
2323 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2327 /// - `location`: the location `L` where the borrow expression occurs
2328 /// - `borrow_region`: the region `'a` associated with the borrow
2329 /// - `borrowed_place`: the place `P` being borrowed
2330 fn add_reborrow_constraint(
2334 borrow_region: ty::Region<'tcx>,
2335 borrowed_place: &Place<'tcx>,
2337 // These constraints are only meaningful during borrowck:
2338 let BorrowCheckContext {
2344 } = self.borrowck_context;
2346 // In Polonius mode, we also push a `borrow_region` fact
2347 // linking the loan to the region (in some cases, though,
2348 // there is no loan associated with this borrow expression --
2349 // that occurs when we are borrowing an unsafe place, for
2351 if let Some(all_facts) = all_facts {
2352 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2353 let region_vid = borrow_region.to_region_vid();
2354 all_facts.borrow_region.push((
2357 location_table.mid_index(location),
2362 // If we are reborrowing the referent of another reference, we
2363 // need to add outlives relationships. In a case like `&mut
2364 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2365 // need to ensure that `'b: 'a`.
2367 let mut borrowed_place = borrowed_place;
2370 "add_reborrow_constraint({:?}, {:?}, {:?})",
2371 location, borrow_region, borrowed_place
2373 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2374 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2377 ProjectionElem::Deref => {
2378 let tcx = self.infcx.tcx;
2379 let base_ty = base.ty(mir, tcx).ty;
2381 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2383 ty::Ref(ref_region, _, mutbl) => {
2384 constraints.outlives_constraints.push(OutlivesConstraint {
2385 sup: ref_region.to_region_vid(),
2386 sub: borrow_region.to_region_vid(),
2387 locations: location.to_locations(),
2388 category: ConstraintCategory::Boring,
2392 hir::Mutability::MutImmutable => {
2393 // Immutable reference. We don't need the base
2394 // to be valid for the entire lifetime of
2398 hir::Mutability::MutMutable => {
2399 // Mutable reference. We *do* need the base
2400 // to be valid, because after the base becomes
2401 // invalid, someone else can use our mutable deref.
2403 // This is in order to make the following function
2406 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2411 // As otherwise you could clone `&mut T` using the
2412 // following function:
2414 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2415 // let my_clone = unsafe_deref(&'a x);
2424 // deref of raw pointer, guaranteed to be valid
2427 ty::Adt(def, _) if def.is_box() => {
2428 // deref of `Box`, need the base to be valid - propagate
2430 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2433 ProjectionElem::Field(..)
2434 | ProjectionElem::Downcast(..)
2435 | ProjectionElem::Index(..)
2436 | ProjectionElem::ConstantIndex { .. }
2437 | ProjectionElem::Subslice { .. } => {
2438 // other field access
2442 // The "propagate" case. We need to check that our base is valid
2443 // for the borrow's lifetime.
2444 borrowed_place = base;
2448 fn prove_aggregate_predicates(
2450 aggregate_kind: &AggregateKind<'tcx>,
2453 let tcx = self.tcx();
2456 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2457 aggregate_kind, location
2460 let instantiated_predicates = match aggregate_kind {
2461 AggregateKind::Adt(def, _, substs, _, _) => {
2462 tcx.predicates_of(def.did).instantiate(tcx, substs)
2465 // For closures, we have some **extra requirements** we
2467 // have to check. In particular, in their upvars and
2468 // signatures, closures often reference various regions
2469 // from the surrounding function -- we call those the
2470 // closure's free regions. When we borrow-check (and hence
2471 // region-check) closures, we may find that the closure
2472 // requires certain relationships between those free
2473 // regions. However, because those free regions refer to
2474 // portions of the CFG of their caller, the closure is not
2475 // in a position to verify those relationships. In that
2476 // case, the requirements get "propagated" to us, and so
2477 // we have to solve them here where we instantiate the
2480 // Despite the opacity of the previous parapgrah, this is
2481 // actually relatively easy to understand in terms of the
2482 // desugaring. A closure gets desugared to a struct, and
2483 // these extra requirements are basically like where
2484 // clauses on the struct.
2485 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2486 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2487 self.prove_closure_bounds(tcx, *def_id, substs, location)
2490 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2493 self.normalize_and_prove_instantiated_predicates(
2494 instantiated_predicates,
2495 location.to_locations(),
2499 fn prove_closure_bounds(
2501 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2503 substs: SubstsRef<'tcx>,
2505 ) -> ty::InstantiatedPredicates<'tcx> {
2506 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2507 let closure_constraints =
2508 closure_region_requirements.apply_requirements(tcx, def_id, substs);
2510 let bounds_mapping = closure_constraints
2513 .filter_map(|(idx, constraint)| {
2514 let ty::OutlivesPredicate(k1, r2) =
2515 constraint.no_bound_vars().unwrap_or_else(|| {
2516 bug!("query_constraint {:?} contained bound vars", constraint,);
2520 UnpackedKind::Lifetime(r1) => {
2521 // constraint is r1: r2
2522 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2523 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2524 let outlives_requirements =
2525 &closure_region_requirements.outlives_requirements[idx];
2529 outlives_requirements.category,
2530 outlives_requirements.blame_span,
2534 UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2539 let existing = self.borrowck_context
2541 .closure_bounds_mapping
2542 .insert(location, bounds_mapping);
2545 "Multiple closures at the same location."
2548 self.push_region_constraints(
2549 location.to_locations(),
2550 ConstraintCategory::ClosureBounds,
2551 &closure_constraints,
2555 tcx.predicates_of(def_id).instantiate(tcx, substs)
2560 trait_ref: ty::TraitRef<'tcx>,
2561 locations: Locations,
2562 category: ConstraintCategory,
2564 self.prove_predicates(
2565 Some(ty::Predicate::Trait(
2566 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2573 fn normalize_and_prove_instantiated_predicates(
2575 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2576 locations: Locations,
2578 for predicate in instantiated_predicates.predicates {
2579 let predicate = self.normalize(predicate, locations);
2580 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2584 fn prove_predicates(
2586 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2587 locations: Locations,
2588 category: ConstraintCategory,
2590 for predicate in predicates {
2592 "prove_predicates(predicate={:?}, locations={:?})",
2593 predicate, locations,
2596 self.prove_predicate(predicate, locations, category);
2602 predicate: ty::Predicate<'tcx>,
2603 locations: Locations,
2604 category: ConstraintCategory,
2607 "prove_predicate(predicate={:?}, location={:?})",
2608 predicate, locations,
2611 let param_env = self.param_env;
2612 self.fully_perform_op(
2615 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2616 ).unwrap_or_else(|NoSolution| {
2617 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2621 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2622 self.last_span = mir.span;
2623 debug!("run_on_mir: {:?}", mir.span);
2625 for (local, local_decl) in mir.local_decls.iter_enumerated() {
2626 self.check_local(mir, local, local_decl);
2629 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2630 let mut location = Location {
2634 for stmt in &block_data.statements {
2635 if !stmt.source_info.span.is_dummy() {
2636 self.last_span = stmt.source_info.span;
2638 self.check_stmt(mir, stmt, location);
2639 location.statement_index += 1;
2642 self.check_terminator(mir, block_data.terminator(), location);
2643 self.check_iscleanup(mir, block_data);
2647 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2649 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2651 debug!("normalize(value={:?}, location={:?})", value, location);
2652 let param_env = self.param_env;
2653 self.fully_perform_op(
2654 location.to_locations(),
2655 ConstraintCategory::Boring,
2656 param_env.and(type_op::normalize::Normalize::new(value)),
2657 ).unwrap_or_else(|NoSolution| {
2658 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2664 trait NormalizeLocation: fmt::Debug + Copy {
2665 fn to_locations(self) -> Locations;
2668 impl NormalizeLocation for Locations {
2669 fn to_locations(self) -> Locations {
2674 impl NormalizeLocation for Location {
2675 fn to_locations(self) -> Locations {
2676 Locations::Single(self)
2680 #[derive(Debug, Default)]
2681 struct ObligationAccumulator<'tcx> {
2682 obligations: PredicateObligations<'tcx>,
2685 impl<'tcx> ObligationAccumulator<'tcx> {
2686 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2687 let InferOk { value, obligations } = value;
2688 self.obligations.extend(obligations);
2692 fn into_vec(self) -> PredicateObligations<'tcx> {