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>,
115 promoted: &IndexVec<Promoted, Body<'tcx>>,
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<'_, '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: OutlivesConstraintSet::default(),
131 member_constraints: MemberConstraintSet::default(),
132 closure_bounds_mapping: Default::default(),
133 type_tests: Vec::default(),
137 universal_region_relations,
139 normalized_inputs_and_output,
140 } = free_region_relations::create(
143 Some(implicit_region_bound),
148 let mut borrowck_context = BorrowCheckContext {
153 constraints: &mut constraints,
163 implicit_region_bound,
164 &mut borrowck_context,
165 &universal_region_relations,
167 cx.equate_inputs_and_outputs(body, universal_regions, &normalized_inputs_and_output);
168 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
170 translate_outlives_facts(cx.borrowck_context);
176 universal_region_relations,
180 fn type_check_internal<'a, 'tcx, R>(
181 infcx: &'a InferCtxt<'a, 'tcx>,
183 param_env: ty::ParamEnv<'tcx>,
184 body: &'a Body<'tcx>,
185 promoted: &'a IndexVec<Promoted, Body<'tcx>>,
186 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
187 implicit_region_bound: ty::Region<'tcx>,
188 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
189 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
190 mut extra: impl FnMut(&mut TypeChecker<'a, 'tcx>) -> R,
192 let mut checker = TypeChecker::new(
198 implicit_region_bound,
200 universal_region_relations,
202 let errors_reported = {
203 let mut verifier = TypeVerifier::new(&mut checker, body, promoted);
204 verifier.visit_body(body);
205 verifier.errors_reported
208 if !errors_reported {
209 // if verifier failed, don't do further checks to avoid ICEs
210 checker.typeck_mir(body);
216 fn translate_outlives_facts(cx: &mut BorrowCheckContext<'_, '_>) {
217 if let Some(facts) = cx.all_facts {
218 let location_table = cx.location_table;
221 .extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
222 |constraint: &OutlivesConstraint| {
223 if let Some(from_location) = constraint.locations.from_location() {
224 Either::Left(iter::once((
227 location_table.mid_index(from_location),
233 .map(move |location| (constraint.sup, constraint.sub, location)),
241 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
242 // We sometimes see MIR failures (notably predicate failures) due to
243 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
244 // to avoid reporting bugs in those cases.
245 tcx.sess.diagnostic().delay_span_bug(span, msg);
248 enum FieldAccessError {
249 OutOfRange { field_count: usize },
252 /// Verifies that MIR types are sane to not crash further checks.
254 /// The sanitize_XYZ methods here take an MIR object and compute its
255 /// type, calling `span_mirbug` and returning an error type if there
257 struct TypeVerifier<'a, 'b, 'tcx> {
258 cx: &'a mut TypeChecker<'b, 'tcx>,
259 body: &'b Body<'tcx>,
260 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
263 errors_reported: bool,
266 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
267 fn visit_span(&mut self, span: &Span) {
268 if !span.is_dummy() {
269 self.last_span = *span;
273 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
274 self.sanitize_place(place, location, context);
277 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
278 self.super_constant(constant, location);
279 self.sanitize_type(constant, constant.literal.ty);
281 if let Some(annotation_index) = constant.user_ty {
282 if let Err(terr) = self.cx.relate_type_and_user_type(
284 ty::Variance::Invariant,
285 &UserTypeProjection { base: annotation_index, projs: vec![], },
286 location.to_locations(),
287 ConstraintCategory::Boring,
289 let annotation = &self.cx.user_type_annotations[annotation_index];
293 "bad constant user type {:?} vs {:?}: {:?}",
300 if let ConstValue::Unevaluated(def_id, substs) = constant.literal.val {
301 if let Err(terr) = self.cx.fully_perform_op(
302 location.to_locations(),
303 ConstraintCategory::Boring,
304 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
305 constant.literal.ty, def_id, UserSubsts { substs, user_self_ty: None },
311 "bad constant type {:?} ({:?})",
317 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
318 let tcx = self.tcx();
320 let instantiated_predicates = tcx
321 .predicates_of(def_id)
322 .instantiate(tcx, substs);
323 self.cx.normalize_and_prove_instantiated_predicates(
324 instantiated_predicates,
325 location.to_locations(),
331 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
332 self.super_rvalue(rvalue, location);
333 let rval_ty = rvalue.ty(self.body, self.tcx());
334 self.sanitize_type(rvalue, rval_ty);
337 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
338 self.super_local_decl(local, local_decl);
339 self.sanitize_type(local_decl, local_decl.ty);
341 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
342 let ty = if !local_decl.is_nonref_binding() {
343 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
344 // reference so we can check the type annotation for the remaining type.
345 if let ty::Ref(_, rty, _) = local_decl.ty.sty {
348 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
354 if let Err(terr) = self.cx.relate_type_and_user_type(
356 ty::Variance::Invariant,
358 Locations::All(*span),
359 ConstraintCategory::TypeAnnotation,
364 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
374 fn visit_body(&mut self, body: &Body<'tcx>) {
375 self.sanitize_type(&"return type", body.return_ty());
376 for local_decl in &body.local_decls {
377 self.sanitize_type(local_decl, local_decl.ty);
379 if self.errors_reported {
382 self.super_body(body);
386 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
388 cx: &'a mut TypeChecker<'b, 'tcx>,
389 body: &'b Body<'tcx>,
390 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
395 mir_def_id: cx.mir_def_id,
397 last_span: body.span,
398 errors_reported: false,
402 fn tcx(&self) -> TyCtxt<'tcx> {
406 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
407 if ty.has_escaping_bound_vars() || ty.references_error() {
408 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
414 /// Checks that the types internal to the `place` match up with
415 /// what would be expected.
420 context: PlaceContext,
422 debug!("sanitize_place: {:?}", place);
424 place.iterate(|place_base, place_projection| {
425 let mut place_ty = match place_base {
426 PlaceBase::Local(index) =>
427 PlaceTy::from_ty(self.body.local_decls[*index].ty),
428 PlaceBase::Static(box Static { kind, ty: sty, def_id }) => {
429 let sty = self.sanitize_type(place, sty);
431 |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
435 if let Err(terr) = verifier.cx.eq_types(
438 location.to_locations(),
439 ConstraintCategory::Boring,
444 "bad promoted type ({:?}: {:?}): {:?}",
452 StaticKind::Promoted(promoted, _) => {
453 if !self.errors_reported {
454 let promoted_body = &self.promoted[*promoted];
455 self.sanitize_promoted(promoted_body, location);
457 let promoted_ty = promoted_body.return_ty();
458 check_err(self, place, promoted_ty, sty);
461 StaticKind::Static => {
462 let ty = self.tcx().type_of(*def_id);
463 let ty = self.cx.normalize(ty, location);
465 check_err(self, place, ty, sty);
468 PlaceTy::from_ty(sty)
472 // FIXME use place_projection.is_empty() when is available
473 if place.projection.is_none() {
474 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
475 let is_promoted = match place {
477 base: PlaceBase::Static(box Static {
478 kind: StaticKind::Promoted(..),
487 let tcx = self.tcx();
488 let trait_ref = ty::TraitRef {
489 def_id: tcx.lang_items().copy_trait().unwrap(),
490 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
493 // In order to have a Copy operand, the type T of the
494 // value must be Copy. Note that we prove that T: Copy,
495 // rather than using the `is_copy_modulo_regions`
496 // test. This is important because
497 // `is_copy_modulo_regions` ignores the resulting region
498 // obligations and assumes they pass. This can result in
499 // bounds from Copy impls being unsoundly ignored (e.g.,
500 // #29149). Note that we decide to use Copy before knowing
501 // whether the bounds fully apply: in effect, the rule is
502 // that if a value of some type could implement Copy, then
504 self.cx.prove_trait_ref(
506 location.to_locations(),
507 ConstraintCategory::CopyBound,
513 for proj in place_projection {
514 if place_ty.variant_index.is_none() {
515 if place_ty.ty.references_error() {
516 assert!(self.errors_reported);
517 return PlaceTy::from_ty(self.tcx().types.err);
520 place_ty = self.sanitize_projection(place_ty, &proj.elem, place, location)
527 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
528 // Determine the constraints from the promoted MIR by running the type
529 // checker on the promoted MIR, then transfer the constraints back to
530 // the main MIR, changing the locations to the provided location.
532 let parent_body = mem::replace(&mut self.body, promoted_body);
534 let all_facts = &mut None;
535 let mut constraints = Default::default();
536 let mut closure_bounds = Default::default();
537 // Don't try to add borrow_region facts for the promoted MIR
538 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
540 // Use a new sets of constraints and closure bounds so that we can
541 // modify their locations.
543 &mut self.cx.borrowck_context.constraints.outlives_constraints,
547 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
551 self.visit_body(promoted_body);
553 if !self.errors_reported {
554 // if verifier failed, don't do further checks to avoid ICEs
555 self.cx.typeck_mir(promoted_body);
558 self.body = parent_body;
559 // Merge the outlives constraints back in, at the given location.
560 mem::swap(self.cx.borrowck_context.all_facts, all_facts);
562 &mut self.cx.borrowck_context.constraints.outlives_constraints,
566 &mut self.cx.borrowck_context.constraints.closure_bounds_mapping,
570 let locations = location.to_locations();
571 for constraint in constraints.outlives().iter() {
572 let mut constraint = *constraint;
573 constraint.locations = locations;
574 if let ConstraintCategory::Return
575 | ConstraintCategory::UseAsConst
576 | ConstraintCategory::UseAsStatic = constraint.category
578 // "Returning" from a promoted is an assigment to a
579 // temporary from the user's point of view.
580 constraint.category = ConstraintCategory::Boring;
582 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
585 if !closure_bounds.is_empty() {
586 let combined_bounds_mapping = closure_bounds
588 .flat_map(|(_, value)| value)
590 let existing = self.cx.borrowck_context
592 .closure_bounds_mapping
593 .insert(location, combined_bounds_mapping);
596 "Multiple promoteds/closures at the same location."
601 fn sanitize_projection(
604 pi: &PlaceElem<'tcx>,
608 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
609 let tcx = self.tcx();
610 let base_ty = base.ty;
612 ProjectionElem::Deref => {
613 let deref_ty = base_ty.builtin_deref(true);
615 deref_ty.map(|t| t.ty).unwrap_or_else(|| {
616 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
620 ProjectionElem::Index(i) => {
621 let index_ty = Place::from(i).ty(self.body, tcx).ty;
622 if index_ty != tcx.types.usize {
624 span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
628 base_ty.builtin_index().unwrap_or_else(|| {
629 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
634 ProjectionElem::ConstantIndex { .. } => {
635 // consider verifying in-bounds
637 base_ty.builtin_index().unwrap_or_else(|| {
638 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
642 ProjectionElem::Subslice { from, to } => PlaceTy::from_ty(
644 ty::Array(inner, size) => {
645 let size = size.eval_usize(tcx, self.cx.param_env);
646 let min_size = (from as u64) + (to as u64);
647 if let Some(rest_size) = size.checked_sub(min_size) {
648 tcx.mk_array(inner, rest_size)
650 span_mirbug_and_err!(
653 "taking too-small slice of {:?}",
658 ty::Slice(..) => base_ty,
659 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
662 ProjectionElem::Downcast(maybe_name, index) => match base_ty.sty {
663 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
664 if index.as_usize() >= adt_def.variants.len() {
666 span_mirbug_and_err!(
669 "cast to variant #{:?} but enum only has {:?}",
671 adt_def.variants.len()
677 variant_index: Some(index),
681 // We do not need to handle generators here, because this runs
682 // before the generator transform stage.
684 let ty = if let Some(name) = maybe_name {
685 span_mirbug_and_err!(
688 "can't downcast {:?} as {:?}",
693 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
698 ProjectionElem::Field(field, fty) => {
699 let fty = self.sanitize_type(place, fty);
700 match self.field_ty(place, base, field, location) {
701 Ok(ty) => if let Err(terr) = self.cx.eq_types(
704 location.to_locations(),
705 ConstraintCategory::Boring,
710 "bad field access ({:?}: {:?}): {:?}",
716 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
719 "accessed field #{} but variant only has {}",
724 PlaceTy::from_ty(fty)
729 fn error(&mut self) -> Ty<'tcx> {
730 self.errors_reported = true;
736 parent: &dyn fmt::Debug,
737 base_ty: PlaceTy<'tcx>,
740 ) -> Result<Ty<'tcx>, FieldAccessError> {
741 let tcx = self.tcx();
743 let (variant, substs) = match base_ty {
744 PlaceTy { ty, variant_index: Some(variant_index) } => match ty.sty {
745 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
746 ty::Generator(def_id, substs, _) => {
747 let mut variants = substs.state_tys(def_id, tcx);
748 let mut variant = match variants.nth(variant_index.into()) {
751 bug!("variant_index of generator out of range: {:?}/{:?}",
753 substs.state_tys(def_id, tcx).count())
756 return match variant.nth(field.index()) {
758 None => Err(FieldAccessError::OutOfRange {
759 field_count: variant.count(),
763 _ => bug!("can't have downcast of non-adt non-generator type"),
765 PlaceTy { ty, variant_index: None } => match ty.sty {
766 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
767 (&adt_def.variants[VariantIdx::new(0)], substs),
768 ty::Closure(def_id, substs) => {
769 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
771 None => Err(FieldAccessError::OutOfRange {
772 field_count: substs.upvar_tys(def_id, tcx).count(),
776 ty::Generator(def_id, substs, _) => {
777 // Only prefix fields (upvars and current state) are
778 // accessible without a variant index.
779 return match substs.prefix_tys(def_id, tcx).nth(field.index()) {
781 None => Err(FieldAccessError::OutOfRange {
782 field_count: substs.prefix_tys(def_id, tcx).count(),
787 return match tys.get(field.index()) {
788 Some(&ty) => Ok(ty.expect_ty()),
789 None => Err(FieldAccessError::OutOfRange {
790 field_count: tys.len(),
795 return Ok(span_mirbug_and_err!(
798 "can't project out of {:?}",
805 if let Some(field) = variant.fields.get(field.index()) {
806 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
808 Err(FieldAccessError::OutOfRange {
809 field_count: variant.fields.len(),
815 /// The MIR type checker. Visits the MIR and enforces all the
816 /// constraints needed for it to be valid and well-typed. Along the
817 /// way, it accrues region constraints -- these can later be used by
818 /// NLL region checking.
819 struct TypeChecker<'a, 'tcx> {
820 infcx: &'a InferCtxt<'a, 'tcx>,
821 param_env: ty::ParamEnv<'tcx>,
823 body: &'a Body<'tcx>,
824 /// User type annotations are shared between the main MIR and the MIR of
825 /// all of the promoted items.
826 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
828 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
829 implicit_region_bound: ty::Region<'tcx>,
830 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
831 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
832 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
835 struct BorrowCheckContext<'a, 'tcx> {
836 universal_regions: &'a UniversalRegions<'tcx>,
837 location_table: &'a LocationTable,
838 all_facts: &'a mut Option<AllFacts>,
839 borrow_set: &'a BorrowSet<'tcx>,
840 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
843 crate struct MirTypeckResults<'tcx> {
844 crate constraints: MirTypeckRegionConstraints<'tcx>,
845 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
848 /// A collection of region constraints that must be satisfied for the
849 /// program to be considered well-typed.
850 crate struct MirTypeckRegionConstraints<'tcx> {
851 /// Maps from a `ty::Placeholder` to the corresponding
852 /// `PlaceholderIndex` bit that we will use for it.
854 /// To keep everything in sync, do not insert this set
855 /// directly. Instead, use the `placeholder_region` helper.
856 crate placeholder_indices: PlaceholderIndices,
858 /// Each time we add a placeholder to `placeholder_indices`, we
859 /// also create a corresponding "representative" region vid for
860 /// that wraps it. This vector tracks those. This way, when we
861 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
862 /// the same underlying `RegionVid`.
863 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
865 /// In general, the type-checker is not responsible for enforcing
866 /// liveness constraints; this job falls to the region inferencer,
867 /// which performs a liveness analysis. However, in some limited
868 /// cases, the MIR type-checker creates temporary regions that do
869 /// not otherwise appear in the MIR -- in particular, the
870 /// late-bound regions that it instantiates at call-sites -- and
871 /// hence it must report on their liveness constraints.
872 crate liveness_constraints: LivenessValues<RegionVid>,
874 crate outlives_constraints: OutlivesConstraintSet,
876 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
878 crate closure_bounds_mapping:
879 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
881 crate type_tests: Vec<TypeTest<'tcx>>,
884 impl MirTypeckRegionConstraints<'tcx> {
885 fn placeholder_region(
887 infcx: &InferCtxt<'_, 'tcx>,
888 placeholder: ty::PlaceholderRegion,
889 ) -> ty::Region<'tcx> {
890 let placeholder_index = self.placeholder_indices.insert(placeholder);
891 match self.placeholder_index_to_region.get(placeholder_index) {
894 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
895 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
896 self.placeholder_index_to_region.push(region);
903 /// The `Locations` type summarizes *where* region constraints are
904 /// required to hold. Normally, this is at a particular point which
905 /// created the obligation, but for constraints that the user gave, we
906 /// want the constraint to hold at all points.
907 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
909 /// Indicates that a type constraint should always be true. This
910 /// is particularly important in the new borrowck analysis for
911 /// things like the type of the return slot. Consider this
915 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
917 /// return &y; // error
921 /// Here, we wind up with the signature from the return type being
922 /// something like `&'1 u32` where `'1` is a universal region. But
923 /// the type of the return slot `_0` is something like `&'2 u32`
924 /// where `'2` is an existential region variable. The type checker
925 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
926 /// older NLL analysis, we required this only at the entry point
927 /// to the function. By the nature of the constraints, this wound
928 /// up propagating to all points reachable from start (because
929 /// `'1` -- as a universal region -- is live everywhere). In the
930 /// newer analysis, though, this doesn't work: `_0` is considered
931 /// dead at the start (it has no usable value) and hence this type
932 /// equality is basically a no-op. Then, later on, when we do `_0
933 /// = &'3 y`, that region `'3` never winds up related to the
934 /// universal region `'1` and hence no error occurs. Therefore, we
935 /// use Locations::All instead, which ensures that the `'1` and
936 /// `'2` are equal everything. We also use this for other
937 /// user-given type annotations; e.g., if the user wrote `let mut
938 /// x: &'static u32 = ...`, we would ensure that all values
939 /// assigned to `x` are of `'static` lifetime.
941 /// The span points to the place the constraint arose. For example,
942 /// it points to the type in a user-given type annotation. If
943 /// there's no sensible span then it's DUMMY_SP.
946 /// An outlives constraint that only has to hold at a single location,
947 /// usually it represents a point where references flow from one spot to
948 /// another (e.g., `x = y`)
953 pub fn from_location(&self) -> Option<Location> {
955 Locations::All(_) => None,
956 Locations::Single(from_location) => Some(*from_location),
960 /// Gets a span representing the location.
961 pub fn span(&self, body: &Body<'_>) -> Span {
963 Locations::All(span) => *span,
964 Locations::Single(l) => body.source_info(*l).span,
969 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
971 infcx: &'a InferCtxt<'a, 'tcx>,
972 body: &'a Body<'tcx>,
974 param_env: ty::ParamEnv<'tcx>,
975 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
976 implicit_region_bound: ty::Region<'tcx>,
977 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
978 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
980 let mut checker = Self {
985 user_type_annotations: &body.user_type_annotations,
988 implicit_region_bound,
990 reported_errors: Default::default(),
991 universal_region_relations,
993 checker.check_user_type_annotations();
997 /// Equate the inferred type and the annotated type for user type annotations
998 fn check_user_type_annotations(&mut self) {
1000 "check_user_type_annotations: user_type_annotations={:?}",
1001 self.user_type_annotations
1003 for user_annotation in self.user_type_annotations {
1004 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1005 let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
1009 UserType::Ty(mut ty) => {
1010 ty = self.normalize(ty, Locations::All(span));
1012 if let Err(terr) = self.eq_types(
1015 Locations::All(span),
1016 ConstraintCategory::BoringNoLocation,
1021 "bad user type ({:?} = {:?}): {:?}",
1028 self.prove_predicate(
1029 ty::Predicate::WellFormed(inferred_ty),
1030 Locations::All(span),
1031 ConstraintCategory::TypeAnnotation,
1034 UserType::TypeOf(def_id, user_substs) => {
1035 if let Err(terr) = self.fully_perform_op(
1036 Locations::All(span),
1037 ConstraintCategory::BoringNoLocation,
1038 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1039 inferred_ty, def_id, user_substs,
1045 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1057 /// Given some operation `op` that manipulates types, proves
1058 /// predicates, or otherwise uses the inference context, executes
1059 /// `op` and then executes all the further obligations that `op`
1060 /// returns. This will yield a set of outlives constraints amongst
1061 /// regions which are extracted and stored as having occurred at
1064 /// **Any `rustc::infer` operations that might generate region
1065 /// constraints should occur within this method so that those
1066 /// constraints can be properly localized!**
1067 fn fully_perform_op<R>(
1069 locations: Locations,
1070 category: ConstraintCategory,
1071 op: impl type_op::TypeOp<'tcx, Output = R>,
1073 let (r, opt_data) = op.fully_perform(self.infcx)?;
1075 if let Some(data) = &opt_data {
1076 self.push_region_constraints(locations, category, data);
1082 fn push_region_constraints(
1084 locations: Locations,
1085 category: ConstraintCategory,
1086 data: &QueryRegionConstraints<'tcx>,
1089 "push_region_constraints: constraints generated at {:?} are {:#?}",
1093 constraint_conversion::ConstraintConversion::new(
1095 self.borrowck_context.universal_regions,
1096 self.region_bound_pairs,
1097 Some(self.implicit_region_bound),
1101 &mut self.borrowck_context.constraints,
1102 ).convert_all(data);
1105 /// Convenient wrapper around `relate_tys::relate_types` -- see
1106 /// that fn for docs.
1112 locations: Locations,
1113 category: ConstraintCategory,
1115 relate_tys::relate_types(
1122 Some(self.borrowck_context),
1130 locations: Locations,
1131 category: ConstraintCategory,
1133 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1136 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1137 /// variables in `sub` with their inferred definitions and try
1138 /// again. This is used for opaque types in places (e.g., `let x:
1139 /// impl Foo = ..`).
1140 fn sub_types_or_anon(
1144 locations: Locations,
1145 category: ConstraintCategory,
1147 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1148 if let ty::Opaque(..) = sup.sty {
1149 // When you have `let x: impl Foo = ...` in a closure,
1150 // the resulting inferend values are stored with the
1151 // def-id of the base function.
1152 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1153 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1165 locations: Locations,
1166 category: ConstraintCategory,
1168 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1171 fn relate_type_and_user_type(
1175 user_ty: &UserTypeProjection,
1176 locations: Locations,
1177 category: ConstraintCategory,
1180 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1181 a, v, user_ty, locations,
1184 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1185 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1187 let tcx = self.infcx.tcx;
1189 for proj in &user_ty.projs {
1190 let projected_ty = curr_projected_ty.projection_ty_core(
1194 |this, field, &()| {
1195 let ty = this.field_ty(tcx, field);
1196 self.normalize(ty, locations)
1199 curr_projected_ty = projected_ty;
1201 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1202 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1204 let ty = curr_projected_ty.ty;
1205 self.relate_types(a, v, ty, locations, category)?;
1210 fn eq_opaque_type_and_type(
1212 revealed_ty: Ty<'tcx>,
1214 anon_owner_def_id: DefId,
1215 locations: Locations,
1216 category: ConstraintCategory,
1219 "eq_opaque_type_and_type( \
1222 revealed_ty, anon_ty
1224 let infcx = self.infcx;
1225 let tcx = infcx.tcx;
1226 let param_env = self.param_env;
1227 let body = self.body;
1228 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1229 let opaque_type_map = self.fully_perform_op(
1234 let mut obligations = ObligationAccumulator::default();
1236 let dummy_body_id = ObligationCause::dummy().body_id;
1237 let (output_ty, opaque_type_map) =
1238 obligations.add(infcx.instantiate_opaque_types(
1243 locations.span(body),
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);
1260 let concrete_is_opaque = infcx
1261 .resolve_vars_if_possible(&opaque_decl.concrete_ty).is_impl_trait();
1264 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?} \
1265 concrete_is_opaque={}",
1266 opaque_decl.concrete_ty,
1267 infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty),
1272 // concrete_is_opaque is `true` when we're using an opaque `impl Trait`
1273 // type without 'revealing' it. For example, code like this:
1275 // type Foo = impl Debug;
1276 // fn foo1() -> Foo { ... }
1277 // fn foo2() -> Foo { foo1() }
1279 // In `foo2`, we're not revealing the type of `Foo` - we're
1280 // just treating it as the opaque type.
1282 // When this occurs, we do *not* want to try to equate
1283 // the concrete type with the underlying defining type
1284 // of the opaque type - this will always fail, since
1285 // the defining type of an opaque type is always
1286 // some other type (e.g. not itself)
1287 // Essentially, none of the normal obligations apply here -
1288 // we're just passing around some unknown opaque type,
1289 // without actually looking at the underlying type it
1290 // gets 'revealed' into
1292 if !concrete_is_opaque {
1293 obligations.add(infcx
1294 .at(&ObligationCause::dummy(), param_env)
1295 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1299 debug!("eq_opaque_type_and_type: equated");
1302 value: Some(opaque_type_map),
1303 obligations: obligations.into_vec(),
1306 || "input_output".to_string(),
1310 let universal_region_relations = self.universal_region_relations;
1312 // Finally, if we instantiated the anon types successfully, we
1313 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1314 // prove that `T: Iterator` where `T` is the type we
1315 // instantiated it with).
1316 if let Some(opaque_type_map) = opaque_type_map {
1317 for (opaque_def_id, opaque_decl) in opaque_type_map {
1318 self.fully_perform_op(
1320 ConstraintCategory::OpaqueType,
1323 infcx.constrain_opaque_type(
1326 universal_region_relations,
1330 obligations: vec![],
1333 || "opaque_type_map".to_string(),
1341 fn tcx(&self) -> TyCtxt<'tcx> {
1345 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1346 debug!("check_stmt: {:?}", stmt);
1347 let tcx = self.tcx();
1349 StatementKind::Assign(ref place, ref rv) => {
1350 // Assignments to temporaries are not "interesting";
1351 // they are not caused by the user, but rather artifacts
1352 // of lowering. Assignments to other sorts of places *are* interesting
1354 let category = match *place {
1356 base: PlaceBase::Local(RETURN_PLACE),
1358 } => if let BorrowCheckContext {
1361 defining_ty: DefiningTy::Const(def_id, _),
1365 } = self.borrowck_context {
1366 if tcx.is_static(*def_id) {
1367 ConstraintCategory::UseAsStatic
1369 ConstraintCategory::UseAsConst
1372 ConstraintCategory::Return
1375 base: PlaceBase::Local(l),
1377 } if !body.local_decls[l].is_user_variable.is_some() => {
1378 ConstraintCategory::Boring
1380 _ => ConstraintCategory::Assignment,
1383 let place_ty = place.ty(body, tcx).ty;
1384 let rv_ty = rv.ty(body, tcx);
1386 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1391 "bad assignment ({:?} = {:?}): {:?}",
1398 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1399 if let Err(terr) = self.relate_type_and_user_type(
1401 ty::Variance::Invariant,
1402 &UserTypeProjection { base: annotation_index, projs: vec![], },
1403 location.to_locations(),
1404 ConstraintCategory::Boring,
1406 let annotation = &self.user_type_annotations[annotation_index];
1410 "bad user type on rvalue ({:?} = {:?}): {:?}",
1418 self.check_rvalue(body, rv, location);
1419 if !self.tcx().features().unsized_locals {
1420 let trait_ref = ty::TraitRef {
1421 def_id: tcx.lang_items().sized_trait().unwrap(),
1422 substs: tcx.mk_substs_trait(place_ty, &[]),
1424 self.prove_trait_ref(
1426 location.to_locations(),
1427 ConstraintCategory::SizedBound,
1431 StatementKind::SetDiscriminant {
1435 let place_type = place.ty(body, tcx).ty;
1436 let adt = match place_type.sty {
1437 ty::Adt(adt, _) if adt.is_enum() => adt,
1440 stmt.source_info.span,
1441 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1447 if variant_index.as_usize() >= adt.variants.len() {
1449 stmt.source_info.span,
1450 "bad set discriminant ({:?} = {:?}): value of of range",
1456 StatementKind::AscribeUserType(ref place, variance, box ref projection) => {
1457 let place_ty = place.ty(body, tcx).ty;
1458 if let Err(terr) = self.relate_type_and_user_type(
1462 Locations::All(stmt.source_info.span),
1463 ConstraintCategory::TypeAnnotation,
1465 let annotation = &self.user_type_annotations[projection.base];
1469 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1477 StatementKind::FakeRead(..)
1478 | StatementKind::StorageLive(..)
1479 | StatementKind::StorageDead(..)
1480 | StatementKind::InlineAsm { .. }
1481 | StatementKind::Retag { .. }
1482 | StatementKind::Nop => {}
1486 fn check_terminator(
1489 term: &Terminator<'tcx>,
1490 term_location: Location,
1492 debug!("check_terminator: {:?}", term);
1493 let tcx = self.tcx();
1495 TerminatorKind::Goto { .. }
1496 | TerminatorKind::Resume
1497 | TerminatorKind::Abort
1498 | TerminatorKind::Return
1499 | TerminatorKind::GeneratorDrop
1500 | TerminatorKind::Unreachable
1501 | TerminatorKind::Drop { .. }
1502 | TerminatorKind::FalseEdges { .. }
1503 | TerminatorKind::FalseUnwind { .. } => {
1504 // no checks needed for these
1507 TerminatorKind::DropAndReplace {
1513 let place_ty = location.ty(body, tcx).ty;
1514 let rv_ty = value.ty(body, tcx);
1516 let locations = term_location.to_locations();
1518 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1523 "bad DropAndReplace ({:?} = {:?}): {:?}",
1530 TerminatorKind::SwitchInt {
1535 let discr_ty = discr.ty(body, tcx);
1536 if let Err(terr) = self.sub_types(
1539 term_location.to_locations(),
1540 ConstraintCategory::Assignment,
1545 "bad SwitchInt ({:?} on {:?}): {:?}",
1551 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1552 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1554 // FIXME: check the values
1556 TerminatorKind::Call {
1563 let func_ty = func.ty(body, tcx);
1564 debug!("check_terminator: call, func_ty={:?}", func_ty);
1565 let sig = match func_ty.sty {
1566 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1568 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1572 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1573 term.source_info.span,
1574 LateBoundRegionConversionTime::FnCall,
1577 let sig = self.normalize(sig, term_location);
1578 self.check_call_dest(body, term, &sig, destination, term_location);
1580 self.prove_predicates(
1581 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1582 term_location.to_locations(),
1583 ConstraintCategory::Boring,
1586 // The ordinary liveness rules will ensure that all
1587 // regions in the type of the callee are live here. We
1588 // then further constrain the late-bound regions that
1589 // were instantiated at the call site to be live as
1590 // well. The resulting is that all the input (and
1591 // output) types in the signature must be live, since
1592 // all the inputs that fed into it were live.
1593 for &late_bound_region in map.values() {
1594 let region_vid = self.borrowck_context
1596 .to_region_vid(late_bound_region);
1597 self.borrowck_context
1599 .liveness_constraints
1600 .add_element(region_vid, term_location);
1603 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1605 TerminatorKind::Assert {
1606 ref cond, ref msg, ..
1608 let cond_ty = cond.ty(body, tcx);
1609 if cond_ty != tcx.types.bool {
1610 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1613 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
1614 if len.ty(body, tcx) != tcx.types.usize {
1615 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1617 if index.ty(body, tcx) != tcx.types.usize {
1618 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1622 TerminatorKind::Yield { ref value, .. } => {
1623 let value_ty = value.ty(body, tcx);
1624 match body.yield_ty {
1625 None => span_mirbug!(self, term, "yield in non-generator"),
1627 if let Err(terr) = self.sub_types(
1630 term_location.to_locations(),
1631 ConstraintCategory::Yield,
1636 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1651 term: &Terminator<'tcx>,
1652 sig: &ty::FnSig<'tcx>,
1653 destination: &Option<(Place<'tcx>, BasicBlock)>,
1654 term_location: Location,
1656 let tcx = self.tcx();
1657 match *destination {
1658 Some((ref dest, _target_block)) => {
1659 let dest_ty = dest.ty(body, tcx).ty;
1660 let category = match *dest {
1662 base: PlaceBase::Local(RETURN_PLACE),
1665 if let BorrowCheckContext {
1668 defining_ty: DefiningTy::Const(def_id, _),
1672 } = self.borrowck_context
1674 if tcx.is_static(*def_id) {
1675 ConstraintCategory::UseAsStatic
1677 ConstraintCategory::UseAsConst
1680 ConstraintCategory::Return
1684 base: PlaceBase::Local(l),
1686 } if !body.local_decls[l].is_user_variable.is_some() => {
1687 ConstraintCategory::Boring
1689 _ => ConstraintCategory::Assignment,
1692 let locations = term_location.to_locations();
1695 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1700 "call dest mismatch ({:?} <- {:?}): {:?}",
1707 // When `#![feature(unsized_locals)]` is not enabled,
1708 // this check is done at `check_local`.
1709 if self.tcx().features().unsized_locals {
1710 let span = term.source_info.span;
1711 self.ensure_place_sized(dest_ty, span);
1715 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1716 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1722 fn check_call_inputs(
1725 term: &Terminator<'tcx>,
1726 sig: &ty::FnSig<'tcx>,
1727 args: &[Operand<'tcx>],
1728 term_location: Location,
1729 from_hir_call: bool,
1731 debug!("check_call_inputs({:?}, {:?})", sig, args);
1732 // Do not count the `VaListImpl` argument as a "true" argument to
1733 // a C-variadic function.
1734 let inputs = if sig.c_variadic {
1735 &sig.inputs()[..sig.inputs().len() - 1]
1739 if args.len() < inputs.len() || (args.len() > inputs.len() && !sig.c_variadic) {
1740 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1742 for (n, (fn_arg, op_arg)) in inputs.iter().zip(args).enumerate() {
1743 let op_arg_ty = op_arg.ty(body, self.tcx());
1744 let category = if from_hir_call {
1745 ConstraintCategory::CallArgument
1747 ConstraintCategory::Boring
1750 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1755 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1765 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1766 let is_cleanup = block_data.is_cleanup;
1767 self.last_span = block_data.terminator().source_info.span;
1768 match block_data.terminator().kind {
1769 TerminatorKind::Goto { target } => {
1770 self.assert_iscleanup(body, block_data, target, is_cleanup)
1772 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1773 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1775 TerminatorKind::Resume => if !is_cleanup {
1776 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1778 TerminatorKind::Abort => if !is_cleanup {
1779 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1781 TerminatorKind::Return => if is_cleanup {
1782 span_mirbug!(self, block_data, "return on cleanup block")
1784 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1785 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1787 TerminatorKind::Yield { resume, drop, .. } => {
1789 span_mirbug!(self, block_data, "yield in cleanup block")
1791 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1792 if let Some(drop) = drop {
1793 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1796 TerminatorKind::Unreachable => {}
1797 TerminatorKind::Drop { target, unwind, .. }
1798 | TerminatorKind::DropAndReplace { target, unwind, .. }
1799 | TerminatorKind::Assert {
1804 self.assert_iscleanup(body, block_data, target, is_cleanup);
1805 if let Some(unwind) = unwind {
1807 span_mirbug!(self, block_data, "unwind on cleanup block")
1809 self.assert_iscleanup(body, block_data, unwind, true);
1812 TerminatorKind::Call {
1817 if let &Some((_, target)) = destination {
1818 self.assert_iscleanup(body, block_data, target, is_cleanup);
1820 if let Some(cleanup) = cleanup {
1822 span_mirbug!(self, block_data, "cleanup on cleanup block")
1824 self.assert_iscleanup(body, block_data, cleanup, true);
1827 TerminatorKind::FalseEdges {
1831 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1832 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1834 TerminatorKind::FalseUnwind {
1838 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1839 if let Some(unwind) = unwind {
1844 "cleanup in cleanup block via false unwind"
1847 self.assert_iscleanup(body, block_data, unwind, true);
1853 fn assert_iscleanup(
1856 ctxt: &dyn fmt::Debug,
1860 if body[bb].is_cleanup != iscleanuppad {
1864 "cleanuppad mismatch: {:?} should be {:?}",
1871 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1872 match body.local_kind(local) {
1873 LocalKind::ReturnPointer | LocalKind::Arg => {
1874 // return values of normal functions are required to be
1875 // sized by typeck, but return values of ADT constructors are
1876 // not because we don't include a `Self: Sized` bounds on them.
1878 // Unbound parts of arguments were never required to be Sized
1879 // - maybe we should make that a warning.
1882 LocalKind::Var | LocalKind::Temp => {}
1885 // When `#![feature(unsized_locals)]` is enabled, only function calls
1886 // and nullary ops are checked in `check_call_dest`.
1887 if !self.tcx().features().unsized_locals {
1888 let span = local_decl.source_info.span;
1889 let ty = local_decl.ty;
1890 self.ensure_place_sized(ty, span);
1894 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1895 let tcx = self.tcx();
1897 // Erase the regions from `ty` to get a global type. The
1898 // `Sized` bound in no way depends on precise regions, so this
1899 // shouldn't affect `is_sized`.
1900 let gcx = tcx.global_tcx();
1901 let erased_ty = tcx.erase_regions(&ty);
1902 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1903 // in current MIR construction, all non-control-flow rvalue
1904 // expressions evaluate through `as_temp` or `into` a return
1905 // slot or local, so to find all unsized rvalues it is enough
1906 // to check all temps, return slots and locals.
1907 if let None = self.reported_errors.replace((ty, span)) {
1908 let mut diag = struct_span_err!(
1912 "cannot move a value of type {0}: the size of {0} \
1913 cannot be statically determined",
1917 // While this is located in `nll::typeck` this error is not
1918 // an NLL error, it's a required check to prevent creation
1919 // of unsized rvalues in certain cases:
1920 // * operand of a box expression
1921 // * callee in a call expression
1927 fn aggregate_field_ty(
1929 ak: &AggregateKind<'tcx>,
1932 ) -> Result<Ty<'tcx>, FieldAccessError> {
1933 let tcx = self.tcx();
1936 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1937 let variant = &def.variants[variant_index];
1938 let adj_field_index = active_field_index.unwrap_or(field_index);
1939 if let Some(field) = variant.fields.get(adj_field_index) {
1940 Ok(self.normalize(field.ty(tcx, substs), location))
1942 Err(FieldAccessError::OutOfRange {
1943 field_count: variant.fields.len(),
1947 AggregateKind::Closure(def_id, substs) => {
1948 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1950 None => Err(FieldAccessError::OutOfRange {
1951 field_count: substs.upvar_tys(def_id, tcx).count(),
1955 AggregateKind::Generator(def_id, substs, _) => {
1956 // It doesn't make sense to look at a field beyond the prefix;
1957 // these require a variant index, and are not initialized in
1958 // aggregate rvalues.
1959 match substs.prefix_tys(def_id, tcx).nth(field_index) {
1961 None => Err(FieldAccessError::OutOfRange {
1962 field_count: substs.prefix_tys(def_id, tcx).count(),
1966 AggregateKind::Array(ty) => Ok(ty),
1967 AggregateKind::Tuple => {
1968 unreachable!("This should have been covered in check_rvalues");
1973 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1974 let tcx = self.tcx();
1977 Rvalue::Aggregate(ak, ops) => {
1978 self.check_aggregate_rvalue(body, rvalue, ak, ops, location)
1981 Rvalue::Repeat(operand, len) => if *len > 1 {
1982 if let Operand::Move(_) = operand {
1983 // While this is located in `nll::typeck` this error is not an NLL error, it's
1984 // a required check to make sure that repeated elements implement `Copy`.
1985 let span = body.source_info(location).span;
1986 let ty = operand.ty(body, tcx);
1987 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1988 self.infcx.report_selection_error(
1989 &traits::Obligation::new(
1990 ObligationCause::new(
1992 self.tcx().hir().def_index_to_hir_id(self.mir_def_id.index),
1993 traits::ObligationCauseCode::RepeatVec,
1996 ty::Predicate::Trait(ty::Binder::bind(ty::TraitPredicate {
1997 trait_ref: ty::TraitRef::new(
1998 self.tcx().lang_items().copy_trait().unwrap(),
1999 tcx.mk_substs_trait(ty, &[]),
2003 &traits::SelectionError::Unimplemented,
2010 Rvalue::NullaryOp(_, ty) => {
2011 // Even with unsized locals cannot box an unsized value.
2012 if self.tcx().features().unsized_locals {
2013 let span = body.source_info(location).span;
2014 self.ensure_place_sized(ty, span);
2017 let trait_ref = ty::TraitRef {
2018 def_id: tcx.lang_items().sized_trait().unwrap(),
2019 substs: tcx.mk_substs_trait(ty, &[]),
2022 self.prove_trait_ref(
2024 location.to_locations(),
2025 ConstraintCategory::SizedBound,
2029 Rvalue::Cast(cast_kind, op, ty) => {
2031 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2032 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2034 // The type that we see in the fcx is like
2035 // `foo::<'a, 'b>`, where `foo` is the path to a
2036 // function definition. When we extract the
2037 // signature, it comes from the `fn_sig` query,
2038 // and hence may contain unnormalized results.
2039 let fn_sig = self.normalize(fn_sig, location);
2041 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2043 if let Err(terr) = self.eq_types(
2046 location.to_locations(),
2047 ConstraintCategory::Cast,
2052 "equating {:?} with {:?} yields {:?}",
2060 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2061 let sig = match op.ty(body, tcx).sty {
2062 ty::Closure(def_id, substs) => {
2063 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
2067 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2069 if let Err(terr) = self.eq_types(
2072 location.to_locations(),
2073 ConstraintCategory::Cast,
2078 "equating {:?} with {:?} yields {:?}",
2086 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2087 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2089 // The type that we see in the fcx is like
2090 // `foo::<'a, 'b>`, where `foo` is the path to a
2091 // function definition. When we extract the
2092 // signature, it comes from the `fn_sig` query,
2093 // and hence may contain unnormalized results.
2094 let fn_sig = self.normalize(fn_sig, location);
2096 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2098 if let Err(terr) = self.eq_types(
2101 location.to_locations(),
2102 ConstraintCategory::Cast,
2107 "equating {:?} with {:?} yields {:?}",
2115 CastKind::Pointer(PointerCast::Unsize) => {
2117 let trait_ref = ty::TraitRef {
2118 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2119 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2122 self.prove_trait_ref(
2124 location.to_locations(),
2125 ConstraintCategory::Cast,
2129 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2130 let ty_from = match op.ty(body, tcx).sty {
2131 ty::RawPtr(ty::TypeAndMut {
2133 mutbl: hir::MutMutable,
2139 "unexpected base type for cast {:?}",
2145 let ty_to = match ty.sty {
2146 ty::RawPtr(ty::TypeAndMut {
2148 mutbl: hir::MutImmutable,
2154 "unexpected target type for cast {:?}",
2160 if let Err(terr) = self.sub_types(
2163 location.to_locations(),
2164 ConstraintCategory::Cast,
2169 "relating {:?} with {:?} yields {:?}",
2178 if let ty::Ref(_, mut ty_from, _) = op.ty(body, tcx).sty {
2179 let (mut ty_to, mutability) = if let ty::RawPtr(ty::TypeAndMut {
2188 "invalid cast types {:?} -> {:?}",
2195 // Handle the direct cast from `&[T; N]` to `*const T` by unwrapping
2196 // any array we find.
2197 while let ty::Array(ty_elem_from, _) = ty_from.sty {
2198 ty_from = ty_elem_from;
2199 if let ty::Array(ty_elem_to, _) = ty_to.sty {
2206 if let hir::MutMutable = mutability {
2207 if let Err(terr) = self.eq_types(
2210 location.to_locations(),
2211 ConstraintCategory::Cast,
2216 "equating {:?} with {:?} yields {:?}",
2223 if let Err(terr) = self.sub_types(
2226 location.to_locations(),
2227 ConstraintCategory::Cast,
2232 "relating {:?} with {:?} yields {:?}",
2244 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2245 self.add_reborrow_constraint(body, location, region, borrowed_place);
2248 Rvalue::BinaryOp(BinOp::Eq, left, right)
2249 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2250 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2251 | Rvalue::BinaryOp(BinOp::Le, left, right)
2252 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2253 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2254 let ty_left = left.ty(body, tcx);
2255 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.sty {
2256 let ty_right = right.ty(body, tcx);
2257 let common_ty = self.infcx.next_ty_var(
2258 TypeVariableOrigin {
2259 kind: TypeVariableOriginKind::MiscVariable,
2260 span: body.source_info(location).span,
2266 location.to_locations(),
2267 ConstraintCategory::Boring
2268 ).unwrap_or_else(|err| {
2269 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2271 if let Err(terr) = self.sub_types(
2274 location.to_locations(),
2275 ConstraintCategory::Boring
2280 "unexpected comparison types {:?} and {:?} yields {:?}",
2291 | Rvalue::BinaryOp(..)
2292 | Rvalue::CheckedBinaryOp(..)
2293 | Rvalue::UnaryOp(..)
2294 | Rvalue::Discriminant(..) => {}
2298 /// If this rvalue supports a user-given type annotation, then
2299 /// extract and return it. This represents the final type of the
2300 /// rvalue and will be unified with the inferred type.
2301 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2304 | Rvalue::Repeat(..)
2308 | Rvalue::BinaryOp(..)
2309 | Rvalue::CheckedBinaryOp(..)
2310 | Rvalue::NullaryOp(..)
2311 | Rvalue::UnaryOp(..)
2312 | Rvalue::Discriminant(..) => None,
2314 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2315 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2316 AggregateKind::Array(_) => None,
2317 AggregateKind::Tuple => None,
2318 AggregateKind::Closure(_, _) => None,
2319 AggregateKind::Generator(_, _, _) => None,
2324 fn check_aggregate_rvalue(
2327 rvalue: &Rvalue<'tcx>,
2328 aggregate_kind: &AggregateKind<'tcx>,
2329 operands: &[Operand<'tcx>],
2332 let tcx = self.tcx();
2334 self.prove_aggregate_predicates(aggregate_kind, location);
2336 if *aggregate_kind == AggregateKind::Tuple {
2337 // tuple rvalue field type is always the type of the op. Nothing to check here.
2341 for (i, operand) in operands.iter().enumerate() {
2342 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2343 Ok(field_ty) => field_ty,
2344 Err(FieldAccessError::OutOfRange { field_count }) => {
2348 "accessed field #{} but variant only has {}",
2355 let operand_ty = operand.ty(body, tcx);
2357 if let Err(terr) = self.sub_types(
2360 location.to_locations(),
2361 ConstraintCategory::Boring,
2366 "{:?} is not a subtype of {:?}: {:?}",
2375 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2379 /// - `location`: the location `L` where the borrow expression occurs
2380 /// - `borrow_region`: the region `'a` associated with the borrow
2381 /// - `borrowed_place`: the place `P` being borrowed
2382 fn add_reborrow_constraint(
2386 borrow_region: ty::Region<'tcx>,
2387 borrowed_place: &Place<'tcx>,
2389 // These constraints are only meaningful during borrowck:
2390 let BorrowCheckContext {
2396 } = self.borrowck_context;
2398 // In Polonius mode, we also push a `borrow_region` fact
2399 // linking the loan to the region (in some cases, though,
2400 // there is no loan associated with this borrow expression --
2401 // that occurs when we are borrowing an unsafe place, for
2403 if let Some(all_facts) = all_facts {
2404 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2405 let region_vid = borrow_region.to_region_vid();
2406 all_facts.borrow_region.push((
2409 location_table.mid_index(location),
2414 // If we are reborrowing the referent of another reference, we
2415 // need to add outlives relationships. In a case like `&mut
2416 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2417 // need to ensure that `'b: 'a`.
2419 let mut borrowed_projection = &borrowed_place.projection;
2422 "add_reborrow_constraint({:?}, {:?}, {:?})",
2423 location, borrow_region, borrowed_place
2425 while let Some(box proj) = borrowed_projection {
2426 debug!("add_reborrow_constraint - iteration {:?}", borrowed_projection);
2429 ProjectionElem::Deref => {
2430 let tcx = self.infcx.tcx;
2431 let base_ty = Place::ty_from(&borrowed_place.base, &proj.base, body, tcx).ty;
2433 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2435 ty::Ref(ref_region, _, mutbl) => {
2436 constraints.outlives_constraints.push(OutlivesConstraint {
2437 sup: ref_region.to_region_vid(),
2438 sub: borrow_region.to_region_vid(),
2439 locations: location.to_locations(),
2440 category: ConstraintCategory::Boring,
2444 hir::Mutability::MutImmutable => {
2445 // Immutable reference. We don't need the base
2446 // to be valid for the entire lifetime of
2450 hir::Mutability::MutMutable => {
2451 // Mutable reference. We *do* need the base
2452 // to be valid, because after the base becomes
2453 // invalid, someone else can use our mutable deref.
2455 // This is in order to make the following function
2458 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2463 // As otherwise you could clone `&mut T` using the
2464 // following function:
2466 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2467 // let my_clone = unsafe_deref(&'a x);
2476 // deref of raw pointer, guaranteed to be valid
2479 ty::Adt(def, _) if def.is_box() => {
2480 // deref of `Box`, need the base to be valid - propagate
2482 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2485 ProjectionElem::Field(..)
2486 | ProjectionElem::Downcast(..)
2487 | ProjectionElem::Index(..)
2488 | ProjectionElem::ConstantIndex { .. }
2489 | ProjectionElem::Subslice { .. } => {
2490 // other field access
2494 // The "propagate" case. We need to check that our base is valid
2495 // for the borrow's lifetime.
2496 borrowed_projection = &proj.base;
2500 fn prove_aggregate_predicates(
2502 aggregate_kind: &AggregateKind<'tcx>,
2505 let tcx = self.tcx();
2508 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2509 aggregate_kind, location
2512 let instantiated_predicates = match aggregate_kind {
2513 AggregateKind::Adt(def, _, substs, _, _) => {
2514 tcx.predicates_of(def.did).instantiate(tcx, substs)
2517 // For closures, we have some **extra requirements** we
2519 // have to check. In particular, in their upvars and
2520 // signatures, closures often reference various regions
2521 // from the surrounding function -- we call those the
2522 // closure's free regions. When we borrow-check (and hence
2523 // region-check) closures, we may find that the closure
2524 // requires certain relationships between those free
2525 // regions. However, because those free regions refer to
2526 // portions of the CFG of their caller, the closure is not
2527 // in a position to verify those relationships. In that
2528 // case, the requirements get "propagated" to us, and so
2529 // we have to solve them here where we instantiate the
2532 // Despite the opacity of the previous parapgrah, this is
2533 // actually relatively easy to understand in terms of the
2534 // desugaring. A closure gets desugared to a struct, and
2535 // these extra requirements are basically like where
2536 // clauses on the struct.
2537 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2538 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2539 self.prove_closure_bounds(tcx, *def_id, substs, location)
2542 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2545 self.normalize_and_prove_instantiated_predicates(
2546 instantiated_predicates,
2547 location.to_locations(),
2551 fn prove_closure_bounds(
2555 substs: SubstsRef<'tcx>,
2557 ) -> ty::InstantiatedPredicates<'tcx> {
2558 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2559 let closure_constraints = QueryRegionConstraints {
2560 outlives: closure_region_requirements.apply_requirements(tcx, def_id, substs),
2562 // Presently, closures never propagate member
2563 // constraints to their parents -- they are enforced
2564 // locally. This is largely a non-issue as member
2565 // constraints only come from `-> impl Trait` and
2566 // friends which don't appear (thus far...) in
2568 member_constraints: vec![],
2571 let bounds_mapping = closure_constraints
2575 .filter_map(|(idx, constraint)| {
2576 let ty::OutlivesPredicate(k1, r2) =
2577 constraint.no_bound_vars().unwrap_or_else(|| {
2578 bug!("query_constraint {:?} contained bound vars", constraint,);
2582 UnpackedKind::Lifetime(r1) => {
2583 // constraint is r1: r2
2584 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2585 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2586 let outlives_requirements =
2587 &closure_region_requirements.outlives_requirements[idx];
2591 outlives_requirements.category,
2592 outlives_requirements.blame_span,
2596 UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2601 let existing = self.borrowck_context
2603 .closure_bounds_mapping
2604 .insert(location, bounds_mapping);
2607 "Multiple closures at the same location."
2610 self.push_region_constraints(
2611 location.to_locations(),
2612 ConstraintCategory::ClosureBounds,
2613 &closure_constraints,
2617 tcx.predicates_of(def_id).instantiate(tcx, substs)
2622 trait_ref: ty::TraitRef<'tcx>,
2623 locations: Locations,
2624 category: ConstraintCategory,
2626 self.prove_predicates(
2627 Some(ty::Predicate::Trait(
2628 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2635 fn normalize_and_prove_instantiated_predicates(
2637 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2638 locations: Locations,
2640 for predicate in instantiated_predicates.predicates {
2641 let predicate = self.normalize(predicate, locations);
2642 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2646 fn prove_predicates(
2648 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2649 locations: Locations,
2650 category: ConstraintCategory,
2652 for predicate in predicates {
2654 "prove_predicates(predicate={:?}, locations={:?})",
2655 predicate, locations,
2658 self.prove_predicate(predicate, locations, category);
2664 predicate: ty::Predicate<'tcx>,
2665 locations: Locations,
2666 category: ConstraintCategory,
2669 "prove_predicate(predicate={:?}, location={:?})",
2670 predicate, locations,
2673 let param_env = self.param_env;
2674 self.fully_perform_op(
2677 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2678 ).unwrap_or_else(|NoSolution| {
2679 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2683 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2684 self.last_span = body.span;
2685 debug!("run_on_mir: {:?}", body.span);
2687 for (local, local_decl) in body.local_decls.iter_enumerated() {
2688 self.check_local(body, local, local_decl);
2691 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2692 let mut location = Location {
2696 for stmt in &block_data.statements {
2697 if !stmt.source_info.span.is_dummy() {
2698 self.last_span = stmt.source_info.span;
2700 self.check_stmt(body, stmt, location);
2701 location.statement_index += 1;
2704 self.check_terminator(body, block_data.terminator(), location);
2705 self.check_iscleanup(body, block_data);
2709 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2711 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2713 debug!("normalize(value={:?}, location={:?})", value, location);
2714 let param_env = self.param_env;
2715 self.fully_perform_op(
2716 location.to_locations(),
2717 ConstraintCategory::Boring,
2718 param_env.and(type_op::normalize::Normalize::new(value)),
2719 ).unwrap_or_else(|NoSolution| {
2720 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2726 trait NormalizeLocation: fmt::Debug + Copy {
2727 fn to_locations(self) -> Locations;
2730 impl NormalizeLocation for Locations {
2731 fn to_locations(self) -> Locations {
2736 impl NormalizeLocation for Location {
2737 fn to_locations(self) -> Locations {
2738 Locations::Single(self)
2742 #[derive(Debug, Default)]
2743 struct ObligationAccumulator<'tcx> {
2744 obligations: PredicateObligations<'tcx>,
2747 impl<'tcx> ObligationAccumulator<'tcx> {
2748 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2749 let InferOk { value, obligations } = value;
2750 self.obligations.extend(obligations);
2754 fn into_vec(self) -> PredicateObligations<'tcx> {