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::transform::promote_consts::should_suggest_const_in_array_repeat_expressions_attribute;
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::QueryRegionConstraints;
27 use rustc::infer::outlives::env::RegionBoundPairs;
28 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
29 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
30 use rustc::mir::interpret::PanicInfo;
31 use rustc::mir::tcx::PlaceTy;
32 use rustc::mir::visit::{PlaceContext, Visitor, 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::{self, ObligationCause, PredicateObligations};
38 use rustc::ty::adjustment::{PointerCast};
39 use rustc::ty::cast::CastTy;
40 use rustc::ty::fold::TypeFoldable;
41 use rustc::ty::subst::{Subst, SubstsRef, GenericArgKind, UserSubsts};
43 self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, UserType,
44 CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
45 UserTypeAnnotationIndex,
47 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
48 use rustc_index::vec::{IndexVec, Idx};
49 use rustc::ty::layout::VariantIdx;
51 use std::{fmt, iter, mem};
52 use syntax_pos::{Span, DUMMY_SP};
54 use rustc_error_codes::*;
56 macro_rules! span_mirbug {
57 ($context:expr, $elem:expr, $($message:tt)*) => ({
58 $crate::borrow_check::nll::type_check::mirbug(
62 "broken MIR in {:?} ({:?}): {}",
65 format_args!($($message)*),
71 macro_rules! span_mirbug_and_err {
72 ($context:expr, $elem:expr, $($message:tt)*) => ({
74 span_mirbug!($context, $elem, $($message)*);
80 mod constraint_conversion;
81 pub mod free_region_relations;
86 /// Type checks the given `mir` in the context of the inference
87 /// context `infcx`. Returns any region constraints that have yet to
88 /// be proven. This result is includes liveness constraints that
89 /// ensure that regions appearing in the types of all local variables
90 /// are live at all points where that local variable may later be
93 /// This phase of type-check ought to be infallible -- this is because
94 /// the original, HIR-based type-check succeeded. So if any errors
95 /// occur here, we will get a `bug!` reported.
99 /// - `infcx` -- inference context to use
100 /// - `param_env` -- parameter environment to use for trait solving
101 /// - `mir` -- MIR to type-check
102 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
103 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
104 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
105 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
106 /// to outlive; should represent the fn body
107 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
108 /// the types of the input parameters found in the MIR itself will be equated with these
109 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
110 /// the type for the RETURN_PLACE will be equated with this
111 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
112 /// constraints for the regions in the types of variables
113 /// - `flow_inits` -- results of a maybe-init dataflow analysis
114 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
115 pub(crate) fn type_check<'tcx>(
116 infcx: &InferCtxt<'_, 'tcx>,
117 param_env: ty::ParamEnv<'tcx>,
119 promoted: &IndexVec<Promoted, Body<'tcx>>,
121 universal_regions: &Rc<UniversalRegions<'tcx>>,
122 location_table: &LocationTable,
123 borrow_set: &BorrowSet<'tcx>,
124 all_facts: &mut Option<AllFacts>,
125 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'_, 'tcx>>,
126 move_data: &MoveData<'tcx>,
127 elements: &Rc<RegionValueElements>,
128 ) -> MirTypeckResults<'tcx> {
129 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
130 let mut constraints = MirTypeckRegionConstraints {
131 placeholder_indices: PlaceholderIndices::default(),
132 placeholder_index_to_region: IndexVec::default(),
133 liveness_constraints: LivenessValues::new(elements.clone()),
134 outlives_constraints: OutlivesConstraintSet::default(),
135 member_constraints: MemberConstraintSet::default(),
136 closure_bounds_mapping: Default::default(),
137 type_tests: Vec::default(),
141 universal_region_relations,
143 normalized_inputs_and_output,
144 } = free_region_relations::create(
147 Some(implicit_region_bound),
152 let mut borrowck_context = BorrowCheckContext {
157 constraints: &mut constraints,
167 implicit_region_bound,
168 &mut borrowck_context,
169 &universal_region_relations,
171 cx.equate_inputs_and_outputs(body, universal_regions, &normalized_inputs_and_output);
172 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
174 translate_outlives_facts(cx.borrowck_context);
180 universal_region_relations,
184 fn type_check_internal<'a, 'tcx, R>(
185 infcx: &'a InferCtxt<'a, 'tcx>,
187 param_env: ty::ParamEnv<'tcx>,
188 body: &'a Body<'tcx>,
189 promoted: &'a IndexVec<Promoted, Body<'tcx>>,
190 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
191 implicit_region_bound: ty::Region<'tcx>,
192 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
193 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
194 mut extra: impl FnMut(&mut TypeChecker<'a, 'tcx>) -> R,
196 let mut checker = TypeChecker::new(
202 implicit_region_bound,
204 universal_region_relations,
206 let errors_reported = {
207 let mut verifier = TypeVerifier::new(&mut checker, body, promoted);
208 verifier.visit_body(body);
209 verifier.errors_reported
212 if !errors_reported {
213 // if verifier failed, don't do further checks to avoid ICEs
214 checker.typeck_mir(body);
220 fn translate_outlives_facts(cx: &mut BorrowCheckContext<'_, '_>) {
221 if let Some(facts) = cx.all_facts {
222 let location_table = cx.location_table;
225 .extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
226 |constraint: &OutlivesConstraint| {
227 if let Some(from_location) = constraint.locations.from_location() {
228 Either::Left(iter::once((
231 location_table.mid_index(from_location),
237 .map(move |location| (constraint.sup, constraint.sub, location)),
245 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
246 // We sometimes see MIR failures (notably predicate failures) due to
247 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
248 // to avoid reporting bugs in those cases.
249 tcx.sess.diagnostic().delay_span_bug(span, msg);
252 enum FieldAccessError {
253 OutOfRange { field_count: usize },
256 /// Verifies that MIR types are sane to not crash further checks.
258 /// The sanitize_XYZ methods here take an MIR object and compute its
259 /// type, calling `span_mirbug` and returning an error type if there
261 struct TypeVerifier<'a, 'b, 'tcx> {
262 cx: &'a mut TypeChecker<'b, 'tcx>,
263 body: &'b Body<'tcx>,
264 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
267 errors_reported: bool,
270 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
271 fn visit_span(&mut self, span: &Span) {
272 if !span.is_dummy() {
273 self.last_span = *span;
277 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
278 self.sanitize_place(place, location, context);
281 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
282 self.super_constant(constant, location);
283 let ty = self.sanitize_type(constant, constant.literal.ty);
285 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
286 let live_region_vid =
287 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
291 .liveness_constraints
292 .add_element(live_region_vid, location);
295 if let Some(annotation_index) = constant.user_ty {
296 if let Err(terr) = self.cx.relate_type_and_user_type(
298 ty::Variance::Invariant,
299 &UserTypeProjection { base: annotation_index, projs: vec![], },
300 location.to_locations(),
301 ConstraintCategory::Boring,
303 let annotation = &self.cx.user_type_annotations[annotation_index];
307 "bad constant user type {:?} vs {:?}: {:?}",
314 if let ty::ConstKind::Unevaluated(def_id, substs) = constant.literal.val {
315 if let Err(terr) = self.cx.fully_perform_op(
316 location.to_locations(),
317 ConstraintCategory::Boring,
318 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
319 constant.literal.ty, def_id, UserSubsts { substs, user_self_ty: None },
325 "bad constant type {:?} ({:?})",
331 if let ty::FnDef(def_id, substs) = constant.literal.ty.kind {
332 let tcx = self.tcx();
334 let instantiated_predicates = tcx
335 .predicates_of(def_id)
336 .instantiate(tcx, substs);
337 self.cx.normalize_and_prove_instantiated_predicates(
338 instantiated_predicates,
339 location.to_locations(),
345 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
346 self.super_rvalue(rvalue, location);
347 let rval_ty = rvalue.ty(self.body, self.tcx());
348 self.sanitize_type(rvalue, rval_ty);
351 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
352 self.super_local_decl(local, local_decl);
353 self.sanitize_type(local_decl, local_decl.ty);
355 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
356 let ty = if !local_decl.is_nonref_binding() {
357 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
358 // reference so we can check the type annotation for the remaining type.
359 if let ty::Ref(_, rty, _) = local_decl.ty.kind {
362 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
368 if let Err(terr) = self.cx.relate_type_and_user_type(
370 ty::Variance::Invariant,
372 Locations::All(*span),
373 ConstraintCategory::TypeAnnotation,
378 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
388 fn visit_body(&mut self, body: &Body<'tcx>) {
389 self.sanitize_type(&"return type", body.return_ty());
390 for local_decl in &body.local_decls {
391 self.sanitize_type(local_decl, local_decl.ty);
393 if self.errors_reported {
396 self.super_body(body);
400 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
402 cx: &'a mut TypeChecker<'b, 'tcx>,
403 body: &'b Body<'tcx>,
404 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
409 mir_def_id: cx.mir_def_id,
411 last_span: body.span,
412 errors_reported: false,
416 fn tcx(&self) -> TyCtxt<'tcx> {
420 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
421 if ty.has_escaping_bound_vars() || ty.references_error() {
422 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
428 /// Checks that the types internal to the `place` match up with
429 /// what would be expected.
434 context: PlaceContext,
436 debug!("sanitize_place: {:?}", place);
438 let mut place_ty = match &place.base {
439 PlaceBase::Local(index) =>
440 PlaceTy::from_ty(self.body.local_decls[*index].ty),
441 PlaceBase::Static(box Static { kind, ty, def_id }) => {
442 let san_ty = self.sanitize_type(place, ty);
444 |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
448 if let Err(terr) = verifier.cx.eq_types(
451 location.to_locations(),
452 ConstraintCategory::Boring,
457 "bad promoted type ({:?}: {:?}): {:?}",
465 StaticKind::Promoted(promoted, _) => {
466 if !self.errors_reported {
467 let promoted_body = &self.promoted[*promoted];
468 self.sanitize_promoted(promoted_body, location);
470 let promoted_ty = promoted_body.return_ty();
471 check_err(self, place, promoted_ty, san_ty);
474 StaticKind::Static => {
475 let ty = self.tcx().type_of(*def_id);
476 let ty = self.cx.normalize(ty, location);
478 check_err(self, place, ty, san_ty);
481 PlaceTy::from_ty(san_ty)
485 if place.projection.is_empty() {
486 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
487 let is_promoted = match place.as_ref() {
489 base: &PlaceBase::Static(box Static {
490 kind: StaticKind::Promoted(..),
499 let tcx = self.tcx();
500 let trait_ref = ty::TraitRef {
501 def_id: tcx.lang_items().copy_trait().unwrap(),
502 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
505 // To have a `Copy` operand, the type `T` of the
506 // value must be `Copy`. Note that we prove that `T: Copy`,
507 // rather than using the `is_copy_modulo_regions`
508 // test. This is important because
509 // `is_copy_modulo_regions` ignores the resulting region
510 // obligations and assumes they pass. This can result in
511 // bounds from `Copy` impls being unsoundly ignored (e.g.,
512 // #29149). Note that we decide to use `Copy` before knowing
513 // whether the bounds fully apply: in effect, the rule is
514 // that if a value of some type could implement `Copy`, then
516 self.cx.prove_trait_ref(
518 location.to_locations(),
519 ConstraintCategory::CopyBound,
525 for elem in place.projection.iter() {
526 if place_ty.variant_index.is_none() {
527 if place_ty.ty.references_error() {
528 assert!(self.errors_reported);
529 return PlaceTy::from_ty(self.tcx().types.err);
532 place_ty = self.sanitize_projection(place_ty, elem, place, location)
538 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'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_body = mem::replace(&mut self.body, promoted_body);
545 // Use new sets of constraints and closure bounds so that we can
546 // modify their locations.
547 let all_facts = &mut None;
548 let mut constraints = Default::default();
549 let mut closure_bounds = Default::default();
550 let mut liveness_constraints = LivenessValues::new(
551 Rc::new(RegionValueElements::new(promoted_body)),
553 // Don't try to add borrow_region facts for the promoted MIR
555 let mut swap_constraints = |this: &mut Self| {
556 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
558 &mut this.cx.borrowck_context.constraints.outlives_constraints,
562 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
566 &mut this.cx.borrowck_context.constraints.liveness_constraints,
567 &mut liveness_constraints
571 swap_constraints(self);
573 self.visit_body(promoted_body);
576 if !self.errors_reported {
577 // if verifier failed, don't do further checks to avoid ICEs
578 self.cx.typeck_mir(promoted_body);
581 self.body = parent_body;
582 // Merge the outlives constraints back in, at the given location.
583 swap_constraints(self);
585 let locations = location.to_locations();
586 for constraint in constraints.outlives().iter() {
587 let mut constraint = *constraint;
588 constraint.locations = locations;
589 if let ConstraintCategory::Return
590 | ConstraintCategory::UseAsConst
591 | ConstraintCategory::UseAsStatic = constraint.category
593 // "Returning" from a promoted is an assigment to a
594 // temporary from the user's point of view.
595 constraint.category = ConstraintCategory::Boring;
597 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
599 for live_region in liveness_constraints.rows() {
600 self.cx.borrowck_context.constraints.liveness_constraints
601 .add_element(live_region, location);
604 if !closure_bounds.is_empty() {
605 let combined_bounds_mapping = closure_bounds
607 .flat_map(|(_, value)| value)
609 let existing = self.cx.borrowck_context
611 .closure_bounds_mapping
612 .insert(location, combined_bounds_mapping);
615 "Multiple promoteds/closures at the same location."
620 fn sanitize_projection(
623 pi: &PlaceElem<'tcx>,
627 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
628 let tcx = self.tcx();
629 let base_ty = base.ty;
631 ProjectionElem::Deref => {
632 let deref_ty = base_ty.builtin_deref(true);
634 deref_ty.map(|t| t.ty).unwrap_or_else(|| {
635 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
639 ProjectionElem::Index(i) => {
640 let index_ty = Place::from(i).ty(self.body, tcx).ty;
641 if index_ty != tcx.types.usize {
643 span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
647 base_ty.builtin_index().unwrap_or_else(|| {
648 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
653 ProjectionElem::ConstantIndex { .. } => {
654 // consider verifying in-bounds
656 base_ty.builtin_index().unwrap_or_else(|| {
657 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
661 ProjectionElem::Subslice { from, to } => PlaceTy::from_ty(
663 ty::Array(inner, size) => {
664 let size = size.eval_usize(tcx, self.cx.param_env);
665 let min_size = (from as u64) + (to as u64);
666 if let Some(rest_size) = size.checked_sub(min_size) {
667 tcx.mk_array(inner, rest_size)
669 span_mirbug_and_err!(
672 "taking too-small slice of {:?}",
677 ty::Slice(..) => base_ty,
678 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
681 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind {
682 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
683 if index.as_usize() >= adt_def.variants.len() {
685 span_mirbug_and_err!(
688 "cast to variant #{:?} but enum only has {:?}",
690 adt_def.variants.len()
696 variant_index: Some(index),
700 // We do not need to handle generators here, because this runs
701 // before the generator transform stage.
703 let ty = if let Some(name) = maybe_name {
704 span_mirbug_and_err!(
707 "can't downcast {:?} as {:?}",
712 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
717 ProjectionElem::Field(field, fty) => {
718 let fty = self.sanitize_type(place, fty);
719 match self.field_ty(place, base, field, location) {
720 Ok(ty) => if let Err(terr) = self.cx.eq_types(
723 location.to_locations(),
724 ConstraintCategory::Boring,
729 "bad field access ({:?}: {:?}): {:?}",
735 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
738 "accessed field #{} but variant only has {}",
743 PlaceTy::from_ty(fty)
748 fn error(&mut self) -> Ty<'tcx> {
749 self.errors_reported = true;
755 parent: &dyn fmt::Debug,
756 base_ty: PlaceTy<'tcx>,
759 ) -> Result<Ty<'tcx>, FieldAccessError> {
760 let tcx = self.tcx();
762 let (variant, substs) = match base_ty {
763 PlaceTy { ty, variant_index: Some(variant_index) } => match ty.kind {
764 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
765 ty::Generator(def_id, substs, _) => {
766 let mut variants = substs.as_generator().state_tys(def_id, tcx);
767 let mut variant = match variants.nth(variant_index.into()) {
770 bug!("variant_index of generator out of range: {:?}/{:?}",
772 substs.as_generator().state_tys(def_id, tcx).count())
775 return match variant.nth(field.index()) {
777 None => Err(FieldAccessError::OutOfRange {
778 field_count: variant.count(),
782 _ => bug!("can't have downcast of non-adt non-generator type"),
784 PlaceTy { ty, variant_index: None } => match ty.kind {
785 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
786 (&adt_def.variants[VariantIdx::new(0)], substs),
787 ty::Closure(def_id, substs) => {
788 return match substs.as_closure().upvar_tys(def_id, tcx).nth(field.index()) {
790 None => Err(FieldAccessError::OutOfRange {
791 field_count: substs.as_closure().upvar_tys(def_id, tcx).count(),
795 ty::Generator(def_id, substs, _) => {
796 // Only prefix fields (upvars and current state) are
797 // accessible without a variant index.
798 return match substs.as_generator().prefix_tys(def_id, tcx).nth(field.index()) {
800 None => Err(FieldAccessError::OutOfRange {
801 field_count: substs.as_generator().prefix_tys(def_id, tcx).count(),
806 return match tys.get(field.index()) {
807 Some(&ty) => Ok(ty.expect_ty()),
808 None => Err(FieldAccessError::OutOfRange {
809 field_count: tys.len(),
814 return Ok(span_mirbug_and_err!(
817 "can't project out of {:?}",
824 if let Some(field) = variant.fields.get(field.index()) {
825 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
827 Err(FieldAccessError::OutOfRange {
828 field_count: variant.fields.len(),
834 /// The MIR type checker. Visits the MIR and enforces all the
835 /// constraints needed for it to be valid and well-typed. Along the
836 /// way, it accrues region constraints -- these can later be used by
837 /// NLL region checking.
838 struct TypeChecker<'a, 'tcx> {
839 infcx: &'a InferCtxt<'a, 'tcx>,
840 param_env: ty::ParamEnv<'tcx>,
842 body: &'a Body<'tcx>,
843 /// User type annotations are shared between the main MIR and the MIR of
844 /// all of the promoted items.
845 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
847 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
848 implicit_region_bound: ty::Region<'tcx>,
849 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
850 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
851 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
854 struct BorrowCheckContext<'a, 'tcx> {
855 universal_regions: &'a UniversalRegions<'tcx>,
856 location_table: &'a LocationTable,
857 all_facts: &'a mut Option<AllFacts>,
858 borrow_set: &'a BorrowSet<'tcx>,
859 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
862 crate struct MirTypeckResults<'tcx> {
863 crate constraints: MirTypeckRegionConstraints<'tcx>,
864 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
867 /// A collection of region constraints that must be satisfied for the
868 /// program to be considered well-typed.
869 crate struct MirTypeckRegionConstraints<'tcx> {
870 /// Maps from a `ty::Placeholder` to the corresponding
871 /// `PlaceholderIndex` bit that we will use for it.
873 /// To keep everything in sync, do not insert this set
874 /// directly. Instead, use the `placeholder_region` helper.
875 crate placeholder_indices: PlaceholderIndices,
877 /// Each time we add a placeholder to `placeholder_indices`, we
878 /// also create a corresponding "representative" region vid for
879 /// that wraps it. This vector tracks those. This way, when we
880 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
881 /// the same underlying `RegionVid`.
882 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
884 /// In general, the type-checker is not responsible for enforcing
885 /// liveness constraints; this job falls to the region inferencer,
886 /// which performs a liveness analysis. However, in some limited
887 /// cases, the MIR type-checker creates temporary regions that do
888 /// not otherwise appear in the MIR -- in particular, the
889 /// late-bound regions that it instantiates at call-sites -- and
890 /// hence it must report on their liveness constraints.
891 crate liveness_constraints: LivenessValues<RegionVid>,
893 crate outlives_constraints: OutlivesConstraintSet,
895 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
897 crate closure_bounds_mapping:
898 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
900 crate type_tests: Vec<TypeTest<'tcx>>,
903 impl MirTypeckRegionConstraints<'tcx> {
904 fn placeholder_region(
906 infcx: &InferCtxt<'_, 'tcx>,
907 placeholder: ty::PlaceholderRegion,
908 ) -> ty::Region<'tcx> {
909 let placeholder_index = self.placeholder_indices.insert(placeholder);
910 match self.placeholder_index_to_region.get(placeholder_index) {
913 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
914 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
915 self.placeholder_index_to_region.push(region);
922 /// The `Locations` type summarizes *where* region constraints are
923 /// required to hold. Normally, this is at a particular point which
924 /// created the obligation, but for constraints that the user gave, we
925 /// want the constraint to hold at all points.
926 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
928 /// Indicates that a type constraint should always be true. This
929 /// is particularly important in the new borrowck analysis for
930 /// things like the type of the return slot. Consider this
934 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
936 /// return &y; // error
940 /// Here, we wind up with the signature from the return type being
941 /// something like `&'1 u32` where `'1` is a universal region. But
942 /// the type of the return slot `_0` is something like `&'2 u32`
943 /// where `'2` is an existential region variable. The type checker
944 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
945 /// older NLL analysis, we required this only at the entry point
946 /// to the function. By the nature of the constraints, this wound
947 /// up propagating to all points reachable from start (because
948 /// `'1` -- as a universal region -- is live everywhere). In the
949 /// newer analysis, though, this doesn't work: `_0` is considered
950 /// dead at the start (it has no usable value) and hence this type
951 /// equality is basically a no-op. Then, later on, when we do `_0
952 /// = &'3 y`, that region `'3` never winds up related to the
953 /// universal region `'1` and hence no error occurs. Therefore, we
954 /// use Locations::All instead, which ensures that the `'1` and
955 /// `'2` are equal everything. We also use this for other
956 /// user-given type annotations; e.g., if the user wrote `let mut
957 /// x: &'static u32 = ...`, we would ensure that all values
958 /// assigned to `x` are of `'static` lifetime.
960 /// The span points to the place the constraint arose. For example,
961 /// it points to the type in a user-given type annotation. If
962 /// there's no sensible span then it's DUMMY_SP.
965 /// An outlives constraint that only has to hold at a single location,
966 /// usually it represents a point where references flow from one spot to
967 /// another (e.g., `x = y`)
972 pub fn from_location(&self) -> Option<Location> {
974 Locations::All(_) => None,
975 Locations::Single(from_location) => Some(*from_location),
979 /// Gets a span representing the location.
980 pub fn span(&self, body: &Body<'_>) -> Span {
982 Locations::All(span) => *span,
983 Locations::Single(l) => body.source_info(*l).span,
988 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
990 infcx: &'a InferCtxt<'a, 'tcx>,
991 body: &'a Body<'tcx>,
993 param_env: ty::ParamEnv<'tcx>,
994 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
995 implicit_region_bound: ty::Region<'tcx>,
996 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
997 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
999 let mut checker = Self {
1001 last_span: DUMMY_SP,
1004 user_type_annotations: &body.user_type_annotations,
1007 implicit_region_bound,
1009 reported_errors: Default::default(),
1010 universal_region_relations,
1012 checker.check_user_type_annotations();
1016 /// Equate the inferred type and the annotated type for user type annotations
1017 fn check_user_type_annotations(&mut self) {
1019 "check_user_type_annotations: user_type_annotations={:?}",
1020 self.user_type_annotations
1022 for user_annotation in self.user_type_annotations {
1023 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1024 let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
1028 UserType::Ty(mut ty) => {
1029 ty = self.normalize(ty, Locations::All(span));
1031 if let Err(terr) = self.eq_types(
1034 Locations::All(span),
1035 ConstraintCategory::BoringNoLocation,
1040 "bad user type ({:?} = {:?}): {:?}",
1047 self.prove_predicate(
1048 ty::Predicate::WellFormed(inferred_ty),
1049 Locations::All(span),
1050 ConstraintCategory::TypeAnnotation,
1053 UserType::TypeOf(def_id, user_substs) => {
1054 if let Err(terr) = self.fully_perform_op(
1055 Locations::All(span),
1056 ConstraintCategory::BoringNoLocation,
1057 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1058 inferred_ty, def_id, user_substs,
1064 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1076 /// Given some operation `op` that manipulates types, proves
1077 /// predicates, or otherwise uses the inference context, executes
1078 /// `op` and then executes all the further obligations that `op`
1079 /// returns. This will yield a set of outlives constraints amongst
1080 /// regions which are extracted and stored as having occurred at
1083 /// **Any `rustc::infer` operations that might generate region
1084 /// constraints should occur within this method so that those
1085 /// constraints can be properly localized!**
1086 fn fully_perform_op<R>(
1088 locations: Locations,
1089 category: ConstraintCategory,
1090 op: impl type_op::TypeOp<'tcx, Output = R>,
1092 let (r, opt_data) = op.fully_perform(self.infcx)?;
1094 if let Some(data) = &opt_data {
1095 self.push_region_constraints(locations, category, data);
1101 fn push_region_constraints(
1103 locations: Locations,
1104 category: ConstraintCategory,
1105 data: &QueryRegionConstraints<'tcx>,
1108 "push_region_constraints: constraints generated at {:?} are {:#?}",
1112 constraint_conversion::ConstraintConversion::new(
1114 self.borrowck_context.universal_regions,
1115 self.region_bound_pairs,
1116 Some(self.implicit_region_bound),
1120 &mut self.borrowck_context.constraints,
1121 ).convert_all(data);
1124 /// Convenient wrapper around `relate_tys::relate_types` -- see
1125 /// that fn for docs.
1131 locations: Locations,
1132 category: ConstraintCategory,
1134 relate_tys::relate_types(
1141 Some(self.borrowck_context),
1149 locations: Locations,
1150 category: ConstraintCategory,
1152 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1155 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1156 /// variables in `sub` with their inferred definitions and try
1157 /// again. This is used for opaque types in places (e.g., `let x:
1158 /// impl Foo = ..`).
1159 fn sub_types_or_anon(
1163 locations: Locations,
1164 category: ConstraintCategory,
1166 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1167 if let ty::Opaque(..) = sup.kind {
1168 // When you have `let x: impl Foo = ...` in a closure,
1169 // the resulting inferend values are stored with the
1170 // def-id of the base function.
1171 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1172 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1184 locations: Locations,
1185 category: ConstraintCategory,
1187 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1190 fn relate_type_and_user_type(
1194 user_ty: &UserTypeProjection,
1195 locations: Locations,
1196 category: ConstraintCategory,
1199 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1200 a, v, user_ty, locations,
1203 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1204 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1206 let tcx = self.infcx.tcx;
1208 for proj in &user_ty.projs {
1209 let projected_ty = curr_projected_ty.projection_ty_core(
1213 |this, field, &()| {
1214 let ty = this.field_ty(tcx, field);
1215 self.normalize(ty, locations)
1218 curr_projected_ty = projected_ty;
1220 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1221 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1223 let ty = curr_projected_ty.ty;
1224 self.relate_types(a, v, ty, locations, category)?;
1229 fn eq_opaque_type_and_type(
1231 revealed_ty: Ty<'tcx>,
1233 anon_owner_def_id: DefId,
1234 locations: Locations,
1235 category: ConstraintCategory,
1238 "eq_opaque_type_and_type( \
1241 revealed_ty, anon_ty
1243 let infcx = self.infcx;
1244 let tcx = infcx.tcx;
1245 let param_env = self.param_env;
1246 let body = self.body;
1247 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1248 let opaque_type_map = self.fully_perform_op(
1253 let mut obligations = ObligationAccumulator::default();
1255 let dummy_body_id = ObligationCause::dummy().body_id;
1256 let (output_ty, opaque_type_map) =
1257 obligations.add(infcx.instantiate_opaque_types(
1262 locations.span(body),
1265 "eq_opaque_type_and_type: \
1266 instantiated output_ty={:?} \
1267 opaque_type_map={:#?} \
1269 output_ty, opaque_type_map, revealed_ty
1271 obligations.add(infcx
1272 .at(&ObligationCause::dummy(), param_env)
1273 .eq(output_ty, revealed_ty)?);
1275 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1276 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1277 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1278 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1279 let concrete_is_opaque = infcx
1280 .resolve_vars_if_possible(&opaque_decl.concrete_ty).is_impl_trait();
1283 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?} \
1284 concrete_is_opaque={}",
1285 opaque_decl.concrete_ty,
1286 infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty),
1291 // concrete_is_opaque is `true` when we're using an opaque `impl Trait`
1292 // type without 'revealing' it. For example, code like this:
1294 // type Foo = impl Debug;
1295 // fn foo1() -> Foo { ... }
1296 // fn foo2() -> Foo { foo1() }
1298 // In `foo2`, we're not revealing the type of `Foo` - we're
1299 // just treating it as the opaque type.
1301 // When this occurs, we do *not* want to try to equate
1302 // the concrete type with the underlying defining type
1303 // of the opaque type - this will always fail, since
1304 // the defining type of an opaque type is always
1305 // some other type (e.g. not itself)
1306 // Essentially, none of the normal obligations apply here -
1307 // we're just passing around some unknown opaque type,
1308 // without actually looking at the underlying type it
1309 // gets 'revealed' into
1311 if !concrete_is_opaque {
1312 obligations.add(infcx
1313 .at(&ObligationCause::dummy(), param_env)
1314 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1318 debug!("eq_opaque_type_and_type: equated");
1321 value: Some(opaque_type_map),
1322 obligations: obligations.into_vec(),
1325 || "input_output".to_string(),
1329 let universal_region_relations = self.universal_region_relations;
1331 // Finally, if we instantiated the anon types successfully, we
1332 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1333 // prove that `T: Iterator` where `T` is the type we
1334 // instantiated it with).
1335 if let Some(opaque_type_map) = opaque_type_map {
1336 for (opaque_def_id, opaque_decl) in opaque_type_map {
1337 self.fully_perform_op(
1339 ConstraintCategory::OpaqueType,
1342 infcx.constrain_opaque_type(
1345 universal_region_relations,
1349 obligations: vec![],
1352 || "opaque_type_map".to_string(),
1360 fn tcx(&self) -> TyCtxt<'tcx> {
1364 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1365 debug!("check_stmt: {:?}", stmt);
1366 let tcx = self.tcx();
1368 StatementKind::Assign(box(ref place, ref rv)) => {
1369 // Assignments to temporaries are not "interesting";
1370 // they are not caused by the user, but rather artifacts
1371 // of lowering. Assignments to other sorts of places *are* interesting
1373 let category = match place.as_local() {
1374 Some(RETURN_PLACE) => if let BorrowCheckContext {
1377 defining_ty: DefiningTy::Const(def_id, _),
1381 } = self.borrowck_context {
1382 if tcx.is_static(*def_id) {
1383 ConstraintCategory::UseAsStatic
1385 ConstraintCategory::UseAsConst
1388 ConstraintCategory::Return
1390 Some(l) if !body.local_decls[l].is_user_variable.is_some() => {
1391 ConstraintCategory::Boring
1393 _ => ConstraintCategory::Assignment,
1396 let place_ty = place.ty(body, tcx).ty;
1397 let place_ty = self.normalize(place_ty, location);
1398 let rv_ty = rv.ty(body, tcx);
1399 let rv_ty = self.normalize(rv_ty, location);
1401 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1406 "bad assignment ({:?} = {:?}): {:?}",
1413 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1414 if let Err(terr) = self.relate_type_and_user_type(
1416 ty::Variance::Invariant,
1417 &UserTypeProjection { base: annotation_index, projs: vec![], },
1418 location.to_locations(),
1419 ConstraintCategory::Boring,
1421 let annotation = &self.user_type_annotations[annotation_index];
1425 "bad user type on rvalue ({:?} = {:?}): {:?}",
1433 self.check_rvalue(body, rv, location);
1434 if !self.tcx().features().unsized_locals {
1435 let trait_ref = ty::TraitRef {
1436 def_id: tcx.lang_items().sized_trait().unwrap(),
1437 substs: tcx.mk_substs_trait(place_ty, &[]),
1439 self.prove_trait_ref(
1441 location.to_locations(),
1442 ConstraintCategory::SizedBound,
1446 StatementKind::SetDiscriminant {
1450 let place_type = place.ty(body, tcx).ty;
1451 let adt = match place_type.kind {
1452 ty::Adt(adt, _) if adt.is_enum() => adt,
1455 stmt.source_info.span,
1456 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1462 if variant_index.as_usize() >= adt.variants.len() {
1464 stmt.source_info.span,
1465 "bad set discriminant ({:?} = {:?}): value of of range",
1471 StatementKind::AscribeUserType(box(ref place, ref projection), variance) => {
1472 let place_ty = place.ty(body, tcx).ty;
1473 if let Err(terr) = self.relate_type_and_user_type(
1477 Locations::All(stmt.source_info.span),
1478 ConstraintCategory::TypeAnnotation,
1480 let annotation = &self.user_type_annotations[projection.base];
1484 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1492 StatementKind::FakeRead(..)
1493 | StatementKind::StorageLive(..)
1494 | StatementKind::StorageDead(..)
1495 | StatementKind::InlineAsm { .. }
1496 | StatementKind::Retag { .. }
1497 | StatementKind::Nop => {}
1501 fn check_terminator(
1504 term: &Terminator<'tcx>,
1505 term_location: Location,
1507 debug!("check_terminator: {:?}", term);
1508 let tcx = self.tcx();
1510 TerminatorKind::Goto { .. }
1511 | TerminatorKind::Resume
1512 | TerminatorKind::Abort
1513 | TerminatorKind::Return
1514 | TerminatorKind::GeneratorDrop
1515 | TerminatorKind::Unreachable
1516 | TerminatorKind::Drop { .. }
1517 | TerminatorKind::FalseEdges { .. }
1518 | TerminatorKind::FalseUnwind { .. } => {
1519 // no checks needed for these
1522 TerminatorKind::DropAndReplace {
1528 let place_ty = location.ty(body, tcx).ty;
1529 let rv_ty = value.ty(body, tcx);
1531 let locations = term_location.to_locations();
1533 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1538 "bad DropAndReplace ({:?} = {:?}): {:?}",
1545 TerminatorKind::SwitchInt {
1550 let discr_ty = discr.ty(body, tcx);
1551 if let Err(terr) = self.sub_types(
1554 term_location.to_locations(),
1555 ConstraintCategory::Assignment,
1560 "bad SwitchInt ({:?} on {:?}): {:?}",
1566 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1567 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1569 // FIXME: check the values
1571 TerminatorKind::Call {
1578 let func_ty = func.ty(body, tcx);
1579 debug!("check_terminator: call, func_ty={:?}", func_ty);
1580 let sig = match func_ty.kind {
1581 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1583 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1587 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1588 term.source_info.span,
1589 LateBoundRegionConversionTime::FnCall,
1592 let sig = self.normalize(sig, term_location);
1593 self.check_call_dest(body, term, &sig, destination, term_location);
1595 self.prove_predicates(
1596 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1597 term_location.to_locations(),
1598 ConstraintCategory::Boring,
1601 // The ordinary liveness rules will ensure that all
1602 // regions in the type of the callee are live here. We
1603 // then further constrain the late-bound regions that
1604 // were instantiated at the call site to be live as
1605 // well. The resulting is that all the input (and
1606 // output) types in the signature must be live, since
1607 // all the inputs that fed into it were live.
1608 for &late_bound_region in map.values() {
1609 let region_vid = self.borrowck_context
1611 .to_region_vid(late_bound_region);
1612 self.borrowck_context
1614 .liveness_constraints
1615 .add_element(region_vid, term_location);
1618 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1620 TerminatorKind::Assert {
1621 ref cond, ref msg, ..
1623 let cond_ty = cond.ty(body, tcx);
1624 if cond_ty != tcx.types.bool {
1625 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1628 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
1629 if len.ty(body, tcx) != tcx.types.usize {
1630 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1632 if index.ty(body, tcx) != tcx.types.usize {
1633 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1637 TerminatorKind::Yield { ref value, .. } => {
1638 let value_ty = value.ty(body, tcx);
1639 match body.yield_ty {
1640 None => span_mirbug!(self, term, "yield in non-generator"),
1642 if let Err(terr) = self.sub_types(
1645 term_location.to_locations(),
1646 ConstraintCategory::Yield,
1651 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1666 term: &Terminator<'tcx>,
1667 sig: &ty::FnSig<'tcx>,
1668 destination: &Option<(Place<'tcx>, BasicBlock)>,
1669 term_location: Location,
1671 let tcx = self.tcx();
1672 match *destination {
1673 Some((ref dest, _target_block)) => {
1674 let dest_ty = dest.ty(body, tcx).ty;
1675 let dest_ty = self.normalize(dest_ty, term_location);
1676 let category = match dest.as_local() {
1677 Some(RETURN_PLACE) => {
1678 if let BorrowCheckContext {
1681 defining_ty: DefiningTy::Const(def_id, _),
1685 } = self.borrowck_context
1687 if tcx.is_static(*def_id) {
1688 ConstraintCategory::UseAsStatic
1690 ConstraintCategory::UseAsConst
1693 ConstraintCategory::Return
1696 Some(l) if !body.local_decls[l].is_user_variable.is_some() => {
1697 ConstraintCategory::Boring
1699 _ => ConstraintCategory::Assignment,
1702 let locations = term_location.to_locations();
1705 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1710 "call dest mismatch ({:?} <- {:?}): {:?}",
1717 // When `#![feature(unsized_locals)]` is not enabled,
1718 // this check is done at `check_local`.
1719 if self.tcx().features().unsized_locals {
1720 let span = term.source_info.span;
1721 self.ensure_place_sized(dest_ty, span);
1725 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1726 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1732 fn check_call_inputs(
1735 term: &Terminator<'tcx>,
1736 sig: &ty::FnSig<'tcx>,
1737 args: &[Operand<'tcx>],
1738 term_location: Location,
1739 from_hir_call: bool,
1741 debug!("check_call_inputs({:?}, {:?})", sig, args);
1742 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1743 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1745 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1746 let op_arg_ty = op_arg.ty(body, self.tcx());
1747 let category = if from_hir_call {
1748 ConstraintCategory::CallArgument
1750 ConstraintCategory::Boring
1753 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1758 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1768 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1769 let is_cleanup = block_data.is_cleanup;
1770 self.last_span = block_data.terminator().source_info.span;
1771 match block_data.terminator().kind {
1772 TerminatorKind::Goto { target } => {
1773 self.assert_iscleanup(body, block_data, target, is_cleanup)
1775 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1776 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1778 TerminatorKind::Resume => if !is_cleanup {
1779 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1781 TerminatorKind::Abort => if !is_cleanup {
1782 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1784 TerminatorKind::Return => if is_cleanup {
1785 span_mirbug!(self, block_data, "return on cleanup block")
1787 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1788 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1790 TerminatorKind::Yield { resume, drop, .. } => {
1792 span_mirbug!(self, block_data, "yield in cleanup block")
1794 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1795 if let Some(drop) = drop {
1796 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1799 TerminatorKind::Unreachable => {}
1800 TerminatorKind::Drop { target, unwind, .. }
1801 | TerminatorKind::DropAndReplace { target, unwind, .. }
1802 | TerminatorKind::Assert {
1807 self.assert_iscleanup(body, block_data, target, is_cleanup);
1808 if let Some(unwind) = unwind {
1810 span_mirbug!(self, block_data, "unwind on cleanup block")
1812 self.assert_iscleanup(body, block_data, unwind, true);
1815 TerminatorKind::Call {
1820 if let &Some((_, target)) = destination {
1821 self.assert_iscleanup(body, block_data, target, is_cleanup);
1823 if let Some(cleanup) = cleanup {
1825 span_mirbug!(self, block_data, "cleanup on cleanup block")
1827 self.assert_iscleanup(body, block_data, cleanup, true);
1830 TerminatorKind::FalseEdges {
1834 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1835 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1837 TerminatorKind::FalseUnwind {
1841 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1842 if let Some(unwind) = unwind {
1847 "cleanup in cleanup block via false unwind"
1850 self.assert_iscleanup(body, block_data, unwind, true);
1856 fn assert_iscleanup(
1859 ctxt: &dyn fmt::Debug,
1863 if body[bb].is_cleanup != iscleanuppad {
1867 "cleanuppad mismatch: {:?} should be {:?}",
1874 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1875 match body.local_kind(local) {
1876 LocalKind::ReturnPointer | LocalKind::Arg => {
1877 // return values of normal functions are required to be
1878 // sized by typeck, but return values of ADT constructors are
1879 // not because we don't include a `Self: Sized` bounds on them.
1881 // Unbound parts of arguments were never required to be Sized
1882 // - maybe we should make that a warning.
1885 LocalKind::Var | LocalKind::Temp => {}
1888 // When `#![feature(unsized_locals)]` is enabled, only function calls
1889 // and nullary ops are checked in `check_call_dest`.
1890 if !self.tcx().features().unsized_locals {
1891 let span = local_decl.source_info.span;
1892 let ty = local_decl.ty;
1893 self.ensure_place_sized(ty, span);
1897 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1898 let tcx = self.tcx();
1900 // Erase the regions from `ty` to get a global type. The
1901 // `Sized` bound in no way depends on precise regions, so this
1902 // shouldn't affect `is_sized`.
1903 let erased_ty = tcx.erase_regions(&ty);
1904 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1905 // in current MIR construction, all non-control-flow rvalue
1906 // expressions evaluate through `as_temp` or `into` a return
1907 // slot or local, so to find all unsized rvalues it is enough
1908 // to check all temps, return slots and locals.
1909 if let None = self.reported_errors.replace((ty, span)) {
1910 let mut diag = struct_span_err!(
1914 "cannot move a value of type {0}: the size of {0} \
1915 cannot be statically determined",
1919 // While this is located in `nll::typeck` this error is not
1920 // an NLL error, it's a required check to prevent creation
1921 // of unsized rvalues in certain cases:
1922 // * operand of a box expression
1923 // * callee in a call expression
1929 fn aggregate_field_ty(
1931 ak: &AggregateKind<'tcx>,
1934 ) -> Result<Ty<'tcx>, FieldAccessError> {
1935 let tcx = self.tcx();
1938 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1939 let variant = &def.variants[variant_index];
1940 let adj_field_index = active_field_index.unwrap_or(field_index);
1941 if let Some(field) = variant.fields.get(adj_field_index) {
1942 Ok(self.normalize(field.ty(tcx, substs), location))
1944 Err(FieldAccessError::OutOfRange {
1945 field_count: variant.fields.len(),
1949 AggregateKind::Closure(def_id, substs) => {
1950 match substs.as_closure().upvar_tys(def_id, tcx).nth(field_index) {
1952 None => Err(FieldAccessError::OutOfRange {
1953 field_count: substs.as_closure().upvar_tys(def_id, tcx).count(),
1957 AggregateKind::Generator(def_id, substs, _) => {
1958 // It doesn't make sense to look at a field beyond the prefix;
1959 // these require a variant index, and are not initialized in
1960 // aggregate rvalues.
1961 match substs.as_generator().prefix_tys(def_id, tcx).nth(field_index) {
1963 None => Err(FieldAccessError::OutOfRange {
1964 field_count: substs.as_generator().prefix_tys(def_id, tcx).count(),
1968 AggregateKind::Array(ty) => Ok(ty),
1969 AggregateKind::Tuple => {
1970 unreachable!("This should have been covered in check_rvalues");
1975 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1976 let tcx = self.tcx();
1979 Rvalue::Aggregate(ak, ops) => {
1980 self.check_aggregate_rvalue(body, rvalue, ak, ops, location)
1983 Rvalue::Repeat(operand, len) => if *len > 1 {
1984 if let Operand::Move(_) = operand {
1985 // While this is located in `nll::typeck` this error is not an NLL error, it's
1986 // a required check to make sure that repeated elements implement `Copy`.
1987 let span = body.source_info(location).span;
1988 let ty = operand.ty(body, tcx);
1989 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1990 // To determine if `const_in_array_repeat_expressions` feature gate should
1991 // be mentioned, need to check if the rvalue is promotable.
1992 let should_suggest =
1993 should_suggest_const_in_array_repeat_expressions_attribute(
1994 tcx, self.mir_def_id, body, operand);
1995 debug!("check_rvalue: should_suggest={:?}", should_suggest);
1997 self.infcx.report_selection_error(
1998 &traits::Obligation::new(
1999 ObligationCause::new(
2001 self.tcx().hir().def_index_to_hir_id(self.mir_def_id.index),
2002 traits::ObligationCauseCode::RepeatVec(should_suggest),
2005 ty::Predicate::Trait(ty::Binder::bind(ty::TraitPredicate {
2006 trait_ref: ty::TraitRef::new(
2007 self.tcx().lang_items().copy_trait().unwrap(),
2008 tcx.mk_substs_trait(ty, &[]),
2012 &traits::SelectionError::Unimplemented,
2020 Rvalue::NullaryOp(_, ty) => {
2021 // Even with unsized locals cannot box an unsized value.
2022 if self.tcx().features().unsized_locals {
2023 let span = body.source_info(location).span;
2024 self.ensure_place_sized(ty, span);
2027 let trait_ref = ty::TraitRef {
2028 def_id: tcx.lang_items().sized_trait().unwrap(),
2029 substs: tcx.mk_substs_trait(ty, &[]),
2032 self.prove_trait_ref(
2034 location.to_locations(),
2035 ConstraintCategory::SizedBound,
2039 Rvalue::Cast(cast_kind, op, ty) => {
2041 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2042 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2044 // The type that we see in the fcx is like
2045 // `foo::<'a, 'b>`, where `foo` is the path to a
2046 // function definition. When we extract the
2047 // signature, it comes from the `fn_sig` query,
2048 // and hence may contain unnormalized results.
2049 let fn_sig = self.normalize(fn_sig, location);
2051 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2053 if let Err(terr) = self.eq_types(
2056 location.to_locations(),
2057 ConstraintCategory::Cast,
2062 "equating {:?} with {:?} yields {:?}",
2070 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2071 let sig = match op.ty(body, tcx).kind {
2072 ty::Closure(def_id, substs) => {
2073 substs.as_closure().sig_ty(def_id, tcx).fn_sig(tcx)
2077 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2079 if let Err(terr) = self.eq_types(
2082 location.to_locations(),
2083 ConstraintCategory::Cast,
2088 "equating {:?} with {:?} yields {:?}",
2096 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2097 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2099 // The type that we see in the fcx is like
2100 // `foo::<'a, 'b>`, where `foo` is the path to a
2101 // function definition. When we extract the
2102 // signature, it comes from the `fn_sig` query,
2103 // and hence may contain unnormalized results.
2104 let fn_sig = self.normalize(fn_sig, location);
2106 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2108 if let Err(terr) = self.eq_types(
2111 location.to_locations(),
2112 ConstraintCategory::Cast,
2117 "equating {:?} with {:?} yields {:?}",
2125 CastKind::Pointer(PointerCast::Unsize) => {
2127 let trait_ref = ty::TraitRef {
2128 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2129 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2132 self.prove_trait_ref(
2134 location.to_locations(),
2135 ConstraintCategory::Cast,
2139 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2140 let ty_from = match op.ty(body, tcx).kind {
2141 ty::RawPtr(ty::TypeAndMut {
2143 mutbl: hir::Mutability::Mutable,
2149 "unexpected base type for cast {:?}",
2155 let ty_to = match ty.kind {
2156 ty::RawPtr(ty::TypeAndMut {
2158 mutbl: hir::Mutability::Immutable,
2164 "unexpected target type for cast {:?}",
2170 if let Err(terr) = self.sub_types(
2173 location.to_locations(),
2174 ConstraintCategory::Cast,
2179 "relating {:?} with {:?} yields {:?}",
2187 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2188 let ty_from = op.ty(body, tcx);
2190 let opt_ty_elem = match ty_from.kind {
2192 ty::TypeAndMut { mutbl: hir::Mutability::Immutable, ty: array_ty }
2194 match array_ty.kind {
2195 ty::Array(ty_elem, _) => Some(ty_elem),
2202 let ty_elem = match opt_ty_elem {
2203 Some(ty_elem) => ty_elem,
2208 "ArrayToPointer cast from unexpected type {:?}",
2215 let ty_to = match ty.kind {
2217 ty::TypeAndMut { mutbl: hir::Mutability::Immutable, ty: ty_to }
2225 "ArrayToPointer cast to unexpected type {:?}",
2232 if let Err(terr) = self.sub_types(
2235 location.to_locations(),
2236 ConstraintCategory::Cast,
2241 "relating {:?} with {:?} yields {:?}",
2250 let ty_from = op.ty(body, tcx);
2251 let cast_ty_from = CastTy::from_ty(ty_from);
2252 let cast_ty_to = CastTy::from_ty(ty);
2253 match (cast_ty_from, cast_ty_to) {
2254 (Some(CastTy::RPtr(ref_tm)), Some(CastTy::Ptr(ptr_tm))) => {
2255 if let hir::Mutability::Mutable = ptr_tm.mutbl {
2256 if let Err(terr) = self.eq_types(
2259 location.to_locations(),
2260 ConstraintCategory::Cast,
2265 "equating {:?} with {:?} yields {:?}",
2272 if let Err(terr) = self.sub_types(
2275 location.to_locations(),
2276 ConstraintCategory::Cast,
2281 "relating {:?} with {:?} yields {:?}",
2291 | (_, Some(CastTy::FnPtr))
2292 | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2293 | (Some(CastTy::Ptr(_)), Some(CastTy::Float))
2294 | (Some(CastTy::FnPtr), Some(CastTy::Float)) => span_mirbug!(
2297 "Invalid cast {:?} -> {:?}",
2307 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2308 self.add_reborrow_constraint(body, location, region, borrowed_place);
2311 Rvalue::BinaryOp(BinOp::Eq, left, right)
2312 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2313 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2314 | Rvalue::BinaryOp(BinOp::Le, left, right)
2315 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2316 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2317 let ty_left = left.ty(body, tcx);
2318 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.kind {
2319 let ty_right = right.ty(body, tcx);
2320 let common_ty = self.infcx.next_ty_var(
2321 TypeVariableOrigin {
2322 kind: TypeVariableOriginKind::MiscVariable,
2323 span: body.source_info(location).span,
2329 location.to_locations(),
2330 ConstraintCategory::Boring
2331 ).unwrap_or_else(|err| {
2332 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2334 if let Err(terr) = self.sub_types(
2337 location.to_locations(),
2338 ConstraintCategory::Boring
2343 "unexpected comparison types {:?} and {:?} yields {:?}",
2354 | Rvalue::BinaryOp(..)
2355 | Rvalue::CheckedBinaryOp(..)
2356 | Rvalue::UnaryOp(..)
2357 | Rvalue::Discriminant(..) => {}
2361 /// If this rvalue supports a user-given type annotation, then
2362 /// extract and return it. This represents the final type of the
2363 /// rvalue and will be unified with the inferred type.
2364 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2367 | Rvalue::Repeat(..)
2371 | Rvalue::BinaryOp(..)
2372 | Rvalue::CheckedBinaryOp(..)
2373 | Rvalue::NullaryOp(..)
2374 | Rvalue::UnaryOp(..)
2375 | Rvalue::Discriminant(..) => None,
2377 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2378 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2379 AggregateKind::Array(_) => None,
2380 AggregateKind::Tuple => None,
2381 AggregateKind::Closure(_, _) => None,
2382 AggregateKind::Generator(_, _, _) => None,
2387 fn check_aggregate_rvalue(
2390 rvalue: &Rvalue<'tcx>,
2391 aggregate_kind: &AggregateKind<'tcx>,
2392 operands: &[Operand<'tcx>],
2395 let tcx = self.tcx();
2397 self.prove_aggregate_predicates(aggregate_kind, location);
2399 if *aggregate_kind == AggregateKind::Tuple {
2400 // tuple rvalue field type is always the type of the op. Nothing to check here.
2404 for (i, operand) in operands.iter().enumerate() {
2405 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2406 Ok(field_ty) => field_ty,
2407 Err(FieldAccessError::OutOfRange { field_count }) => {
2411 "accessed field #{} but variant only has {}",
2418 let operand_ty = operand.ty(body, tcx);
2420 if let Err(terr) = self.sub_types(
2423 location.to_locations(),
2424 ConstraintCategory::Boring,
2429 "{:?} is not a subtype of {:?}: {:?}",
2438 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2442 /// - `location`: the location `L` where the borrow expression occurs
2443 /// - `borrow_region`: the region `'a` associated with the borrow
2444 /// - `borrowed_place`: the place `P` being borrowed
2445 fn add_reborrow_constraint(
2449 borrow_region: ty::Region<'tcx>,
2450 borrowed_place: &Place<'tcx>,
2452 // These constraints are only meaningful during borrowck:
2453 let BorrowCheckContext {
2459 } = self.borrowck_context;
2461 // In Polonius mode, we also push a `borrow_region` fact
2462 // linking the loan to the region (in some cases, though,
2463 // there is no loan associated with this borrow expression --
2464 // that occurs when we are borrowing an unsafe place, for
2466 if let Some(all_facts) = all_facts {
2467 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2468 let region_vid = borrow_region.to_region_vid();
2469 all_facts.borrow_region.push((
2472 location_table.mid_index(location),
2477 // If we are reborrowing the referent of another reference, we
2478 // need to add outlives relationships. In a case like `&mut
2479 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2480 // need to ensure that `'b: 'a`.
2483 "add_reborrow_constraint({:?}, {:?}, {:?})",
2484 location, borrow_region, borrowed_place
2487 let mut cursor = borrowed_place.projection.as_ref();
2488 while let [proj_base @ .., elem] = cursor {
2491 debug!("add_reborrow_constraint - iteration {:?}", elem);
2494 ProjectionElem::Deref => {
2495 let tcx = self.infcx.tcx;
2496 let base_ty = Place::ty_from(&borrowed_place.base, proj_base, body, tcx).ty;
2498 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2499 match base_ty.kind {
2500 ty::Ref(ref_region, _, mutbl) => {
2501 constraints.outlives_constraints.push(OutlivesConstraint {
2502 sup: ref_region.to_region_vid(),
2503 sub: borrow_region.to_region_vid(),
2504 locations: location.to_locations(),
2505 category: ConstraintCategory::Boring,
2509 hir::Mutability::Immutable => {
2510 // Immutable reference. We don't need the base
2511 // to be valid for the entire lifetime of
2515 hir::Mutability::Mutable => {
2516 // Mutable reference. We *do* need the base
2517 // to be valid, because after the base becomes
2518 // invalid, someone else can use our mutable deref.
2520 // This is in order to make the following function
2523 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2528 // As otherwise you could clone `&mut T` using the
2529 // following function:
2531 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2532 // let my_clone = unsafe_deref(&'a x);
2541 // deref of raw pointer, guaranteed to be valid
2544 ty::Adt(def, _) if def.is_box() => {
2545 // deref of `Box`, need the base to be valid - propagate
2547 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2550 ProjectionElem::Field(..)
2551 | ProjectionElem::Downcast(..)
2552 | ProjectionElem::Index(..)
2553 | ProjectionElem::ConstantIndex { .. }
2554 | ProjectionElem::Subslice { .. } => {
2555 // other field access
2561 fn prove_aggregate_predicates(
2563 aggregate_kind: &AggregateKind<'tcx>,
2566 let tcx = self.tcx();
2569 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2570 aggregate_kind, location
2573 let instantiated_predicates = match aggregate_kind {
2574 AggregateKind::Adt(def, _, substs, _, _) => {
2575 tcx.predicates_of(def.did).instantiate(tcx, substs)
2578 // For closures, we have some **extra requirements** we
2580 // have to check. In particular, in their upvars and
2581 // signatures, closures often reference various regions
2582 // from the surrounding function -- we call those the
2583 // closure's free regions. When we borrow-check (and hence
2584 // region-check) closures, we may find that the closure
2585 // requires certain relationships between those free
2586 // regions. However, because those free regions refer to
2587 // portions of the CFG of their caller, the closure is not
2588 // in a position to verify those relationships. In that
2589 // case, the requirements get "propagated" to us, and so
2590 // we have to solve them here where we instantiate the
2593 // Despite the opacity of the previous parapgrah, this is
2594 // actually relatively easy to understand in terms of the
2595 // desugaring. A closure gets desugared to a struct, and
2596 // these extra requirements are basically like where
2597 // clauses on the struct.
2598 AggregateKind::Closure(def_id, substs)
2599 | AggregateKind::Generator(def_id, substs, _) => {
2600 self.prove_closure_bounds(tcx, *def_id, substs, location)
2603 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2606 self.normalize_and_prove_instantiated_predicates(
2607 instantiated_predicates,
2608 location.to_locations(),
2612 fn prove_closure_bounds(
2616 substs: SubstsRef<'tcx>,
2618 ) -> ty::InstantiatedPredicates<'tcx> {
2619 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2620 let closure_constraints = QueryRegionConstraints {
2621 outlives: closure_region_requirements.apply_requirements(tcx, def_id, substs),
2623 // Presently, closures never propagate member
2624 // constraints to their parents -- they are enforced
2625 // locally. This is largely a non-issue as member
2626 // constraints only come from `-> impl Trait` and
2627 // friends which don't appear (thus far...) in
2629 member_constraints: vec![],
2632 let bounds_mapping = closure_constraints
2636 .filter_map(|(idx, constraint)| {
2637 let ty::OutlivesPredicate(k1, r2) =
2638 constraint.no_bound_vars().unwrap_or_else(|| {
2639 bug!("query_constraint {:?} contained bound vars", constraint,);
2643 GenericArgKind::Lifetime(r1) => {
2644 // constraint is r1: r2
2645 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2646 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2647 let outlives_requirements =
2648 &closure_region_requirements.outlives_requirements[idx];
2652 outlives_requirements.category,
2653 outlives_requirements.blame_span,
2657 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2662 let existing = self.borrowck_context
2664 .closure_bounds_mapping
2665 .insert(location, bounds_mapping);
2668 "Multiple closures at the same location."
2671 self.push_region_constraints(
2672 location.to_locations(),
2673 ConstraintCategory::ClosureBounds,
2674 &closure_constraints,
2678 tcx.predicates_of(def_id).instantiate(tcx, substs)
2683 trait_ref: ty::TraitRef<'tcx>,
2684 locations: Locations,
2685 category: ConstraintCategory,
2687 self.prove_predicates(
2688 Some(ty::Predicate::Trait(
2689 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2696 fn normalize_and_prove_instantiated_predicates(
2698 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2699 locations: Locations,
2701 for predicate in instantiated_predicates.predicates {
2702 let predicate = self.normalize(predicate, locations);
2703 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2707 fn prove_predicates(
2709 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2710 locations: Locations,
2711 category: ConstraintCategory,
2713 for predicate in predicates {
2715 "prove_predicates(predicate={:?}, locations={:?})",
2716 predicate, locations,
2719 self.prove_predicate(predicate, locations, category);
2725 predicate: ty::Predicate<'tcx>,
2726 locations: Locations,
2727 category: ConstraintCategory,
2730 "prove_predicate(predicate={:?}, location={:?})",
2731 predicate, locations,
2734 let param_env = self.param_env;
2735 self.fully_perform_op(
2738 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2739 ).unwrap_or_else(|NoSolution| {
2740 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2744 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2745 self.last_span = body.span;
2746 debug!("run_on_mir: {:?}", body.span);
2748 for (local, local_decl) in body.local_decls.iter_enumerated() {
2749 self.check_local(body, local, local_decl);
2752 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2753 let mut location = Location {
2757 for stmt in &block_data.statements {
2758 if !stmt.source_info.span.is_dummy() {
2759 self.last_span = stmt.source_info.span;
2761 self.check_stmt(body, stmt, location);
2762 location.statement_index += 1;
2765 self.check_terminator(body, block_data.terminator(), location);
2766 self.check_iscleanup(body, block_data);
2770 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2772 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2774 debug!("normalize(value={:?}, location={:?})", value, location);
2775 let param_env = self.param_env;
2776 self.fully_perform_op(
2777 location.to_locations(),
2778 ConstraintCategory::Boring,
2779 param_env.and(type_op::normalize::Normalize::new(value)),
2780 ).unwrap_or_else(|NoSolution| {
2781 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2787 trait NormalizeLocation: fmt::Debug + Copy {
2788 fn to_locations(self) -> Locations;
2791 impl NormalizeLocation for Locations {
2792 fn to_locations(self) -> Locations {
2797 impl NormalizeLocation for Location {
2798 fn to_locations(self) -> Locations {
2799 Locations::Single(self)
2803 #[derive(Debug, Default)]
2804 struct ObligationAccumulator<'tcx> {
2805 obligations: PredicateObligations<'tcx>,
2808 impl<'tcx> ObligationAccumulator<'tcx> {
2809 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2810 let InferOk { value, obligations } = value;
2811 self.obligations.extend(obligations);
2815 fn into_vec(self) -> PredicateObligations<'tcx> {