1 //! This pass type-checks the MIR to ensure it is not broken.
4 use std::{fmt, iter, mem};
8 use rustc::infer::canonical::QueryRegionConstraints;
9 use rustc::infer::outlives::env::RegionBoundPairs;
10 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
11 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
12 use rustc::mir::interpret::PanicInfo;
13 use rustc::mir::tcx::PlaceTy;
14 use rustc::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
16 use rustc::traits::query::type_op;
17 use rustc::traits::query::type_op::custom::CustomTypeOp;
18 use rustc::traits::query::{Fallible, NoSolution};
19 use rustc::traits::{self, ObligationCause, PredicateObligations};
20 use rustc::ty::adjustment::PointerCast;
21 use rustc::ty::cast::CastTy;
22 use rustc::ty::fold::TypeFoldable;
23 use rustc::ty::layout::VariantIdx;
24 use rustc::ty::subst::{GenericArgKind, Subst, SubstsRef, UserSubsts};
26 self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, RegionVid, ToPolyTraitRef, Ty,
27 TyCtxt, UserType, UserTypeAnnotationIndex,
29 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
30 use rustc_error_codes::*;
31 use rustc_errors::struct_span_err;
33 use rustc_hir::def_id::DefId;
34 use rustc_index::vec::{Idx, IndexVec};
35 use rustc_span::{Span, DUMMY_SP};
37 use crate::dataflow::move_paths::MoveData;
38 use crate::dataflow::FlowAtLocation;
39 use crate::dataflow::MaybeInitializedPlaces;
40 use crate::transform::promote_consts::should_suggest_const_in_array_repeat_expressions_attribute;
42 use crate::borrow_check::{
43 borrow_set::BorrowSet,
44 constraints::{OutlivesConstraint, OutlivesConstraintSet},
46 location::LocationTable,
47 member_constraints::MemberConstraintSet,
49 region_infer::values::{
50 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
52 region_infer::{ClosureRegionRequirementsExt, TypeTest},
54 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
55 universal_regions::{DefiningTy, UniversalRegions},
58 macro_rules! span_mirbug {
59 ($context:expr, $elem:expr, $($message:tt)*) => ({
60 $crate::borrow_check::type_check::mirbug(
64 "broken MIR in {:?} ({:?}): {}",
67 format_args!($($message)*),
73 macro_rules! span_mirbug_and_err {
74 ($context:expr, $elem:expr, $($message:tt)*) => ({
76 span_mirbug!($context, $elem, $($message)*);
82 mod constraint_conversion;
83 pub mod free_region_relations;
88 /// Type checks the given `mir` in the context of the inference
89 /// context `infcx`. Returns any region constraints that have yet to
90 /// be proven. This result is includes liveness constraints that
91 /// ensure that regions appearing in the types of all local variables
92 /// are live at all points where that local variable may later be
95 /// This phase of type-check ought to be infallible -- this is because
96 /// the original, HIR-based type-check succeeded. So if any errors
97 /// occur here, we will get a `bug!` reported.
101 /// - `infcx` -- inference context to use
102 /// - `param_env` -- parameter environment to use for trait solving
103 /// - `mir` -- MIR to type-check
104 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
105 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
106 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
107 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
108 /// to outlive; should represent the fn body
109 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
110 /// the types of the input parameters found in the MIR itself will be equated with these
111 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
112 /// the type for the RETURN_PLACE will be equated with this
113 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
114 /// constraints for the regions in the types of variables
115 /// - `flow_inits` -- results of a maybe-init dataflow analysis
116 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
117 pub(crate) fn type_check<'tcx>(
118 infcx: &InferCtxt<'_, 'tcx>,
119 param_env: ty::ParamEnv<'tcx>,
120 body: ReadOnlyBodyAndCache<'_, 'tcx>,
121 promoted: &IndexVec<Promoted, ReadOnlyBodyAndCache<'_, 'tcx>>,
123 universal_regions: &Rc<UniversalRegions<'tcx>>,
124 location_table: &LocationTable,
125 borrow_set: &BorrowSet<'tcx>,
126 all_facts: &mut Option<AllFacts>,
127 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'_, 'tcx>>,
128 move_data: &MoveData<'tcx>,
129 elements: &Rc<RegionValueElements>,
130 ) -> MirTypeckResults<'tcx> {
131 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
132 let mut constraints = MirTypeckRegionConstraints {
133 placeholder_indices: PlaceholderIndices::default(),
134 placeholder_index_to_region: IndexVec::default(),
135 liveness_constraints: LivenessValues::new(elements.clone()),
136 outlives_constraints: OutlivesConstraintSet::default(),
137 member_constraints: MemberConstraintSet::default(),
138 closure_bounds_mapping: Default::default(),
139 type_tests: Vec::default(),
143 universal_region_relations,
145 normalized_inputs_and_output,
146 } = free_region_relations::create(
149 Some(implicit_region_bound),
154 let mut borrowck_context = BorrowCheckContext {
159 constraints: &mut constraints,
169 implicit_region_bound,
170 &mut borrowck_context,
171 &universal_region_relations,
173 cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
174 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
176 translate_outlives_facts(&mut cx);
180 MirTypeckResults { constraints, universal_region_relations }
183 fn type_check_internal<'a, 'tcx, R>(
184 infcx: &'a InferCtxt<'a, 'tcx>,
186 param_env: ty::ParamEnv<'tcx>,
187 body: ReadOnlyBodyAndCache<'a, 'tcx>,
188 promoted: &'a IndexVec<Promoted, ReadOnlyBodyAndCache<'_, 'tcx>>,
189 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
190 implicit_region_bound: ty::Region<'tcx>,
191 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
192 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
193 mut extra: impl FnMut(&mut TypeChecker<'a, 'tcx>) -> R,
195 let mut checker = TypeChecker::new(
201 implicit_region_bound,
203 universal_region_relations,
205 let errors_reported = {
206 let mut verifier = TypeVerifier::new(&mut checker, *body, promoted);
207 verifier.visit_body(body);
208 verifier.errors_reported
211 if !errors_reported {
212 // if verifier failed, don't do further checks to avoid ICEs
213 checker.typeck_mir(body);
219 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
220 let cx = &mut typeck.borrowck_context;
221 if let Some(facts) = cx.all_facts {
222 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
223 let location_table = cx.location_table;
224 facts.outlives.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
225 |constraint: &OutlivesConstraint| {
226 if let Some(from_location) = constraint.locations.from_location() {
227 Either::Left(iter::once((
230 location_table.mid_index(from_location),
236 .map(move |location| (constraint.sup, constraint.sub, location)),
244 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
245 // We sometimes see MIR failures (notably predicate failures) due to
246 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
247 // to avoid reporting bugs in those cases.
248 tcx.sess.diagnostic().delay_span_bug(span, msg);
251 enum FieldAccessError {
252 OutOfRange { field_count: usize },
255 /// Verifies that MIR types are sane to not crash further checks.
257 /// The sanitize_XYZ methods here take an MIR object and compute its
258 /// type, calling `span_mirbug` and returning an error type if there
260 struct TypeVerifier<'a, 'b, 'tcx> {
261 cx: &'a mut TypeChecker<'b, 'tcx>,
262 body: &'b Body<'tcx>,
263 promoted: &'b IndexVec<Promoted, ReadOnlyBodyAndCache<'b, 'tcx>>,
266 errors_reported: bool,
269 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
270 fn visit_span(&mut self, span: &Span) {
271 if !span.is_dummy() {
272 self.last_span = *span;
276 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
277 self.sanitize_place(place, location, context);
280 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
281 self.super_constant(constant, location);
282 let ty = self.sanitize_type(constant, constant.literal.ty);
284 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
285 let live_region_vid =
286 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
290 .liveness_constraints
291 .add_element(live_region_vid, location);
294 if let Some(annotation_index) = constant.user_ty {
295 if let Err(terr) = self.cx.relate_type_and_user_type(
297 ty::Variance::Invariant,
298 &UserTypeProjection { base: annotation_index, projs: vec![] },
299 location.to_locations(),
300 ConstraintCategory::Boring,
302 let annotation = &self.cx.user_type_annotations[annotation_index];
306 "bad constant user type {:?} vs {:?}: {:?}",
313 if let ty::ConstKind::Unevaluated(def_id, substs, promoted) = constant.literal.val {
314 if let Some(promoted) = promoted {
315 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
316 promoted: &ReadOnlyBodyAndCache<'_, 'tcx>,
319 if let Err(terr) = verifier.cx.eq_types(
322 location.to_locations(),
323 ConstraintCategory::Boring,
328 "bad promoted type ({:?}: {:?}): {:?}",
336 if !self.errors_reported {
337 let promoted_body = self.promoted[promoted];
338 self.sanitize_promoted(promoted_body, location);
340 let promoted_ty = promoted_body.return_ty();
341 check_err(self, &promoted_body, ty, promoted_ty);
344 if let Err(terr) = self.cx.fully_perform_op(
345 location.to_locations(),
346 ConstraintCategory::Boring,
347 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
350 UserSubsts { substs, user_self_ty: None },
356 "bad constant type {:?} ({:?})",
363 if let ty::FnDef(def_id, substs) = constant.literal.ty.kind {
364 let tcx = self.tcx();
366 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
367 self.cx.normalize_and_prove_instantiated_predicates(
368 instantiated_predicates,
369 location.to_locations(),
375 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
376 self.super_rvalue(rvalue, location);
377 let rval_ty = rvalue.ty(self.body, self.tcx());
378 self.sanitize_type(rvalue, rval_ty);
381 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
382 self.super_local_decl(local, local_decl);
383 self.sanitize_type(local_decl, local_decl.ty);
385 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
386 let ty = if !local_decl.is_nonref_binding() {
387 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
388 // reference so we can check the type annotation for the remaining type.
389 if let ty::Ref(_, rty, _) = local_decl.ty.kind {
392 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
398 if let Err(terr) = self.cx.relate_type_and_user_type(
400 ty::Variance::Invariant,
402 Locations::All(*span),
403 ConstraintCategory::TypeAnnotation,
408 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
418 fn visit_body(&mut self, body: ReadOnlyBodyAndCache<'_, 'tcx>) {
419 self.sanitize_type(&"return type", body.return_ty());
420 for local_decl in &body.local_decls {
421 self.sanitize_type(local_decl, local_decl.ty);
423 if self.errors_reported {
426 self.super_body(body);
430 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
432 cx: &'a mut TypeChecker<'b, 'tcx>,
433 body: &'b Body<'tcx>,
434 promoted: &'b IndexVec<Promoted, ReadOnlyBodyAndCache<'b, 'tcx>>,
439 mir_def_id: cx.mir_def_id,
441 last_span: body.span,
442 errors_reported: false,
446 fn tcx(&self) -> TyCtxt<'tcx> {
450 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
451 if ty.has_escaping_bound_vars() || ty.references_error() {
452 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
458 /// Checks that the types internal to the `place` match up with
459 /// what would be expected.
464 context: PlaceContext,
466 debug!("sanitize_place: {:?}", place);
468 let mut place_ty = match &place.base {
469 PlaceBase::Local(index) => PlaceTy::from_ty(self.body.local_decls[*index].ty),
470 PlaceBase::Static(box Static { kind, ty, def_id }) => {
471 let san_ty = self.sanitize_type(place, ty);
473 |verifier: &mut TypeVerifier<'a, 'b, 'tcx>, place: &Place<'tcx>, ty, san_ty| {
474 if let Err(terr) = verifier.cx.eq_types(
477 location.to_locations(),
478 ConstraintCategory::Boring,
483 "bad promoted type ({:?}: {:?}): {:?}",
491 StaticKind::Static => {
492 let ty = self.tcx().type_of(*def_id);
493 let ty = self.cx.normalize(ty, location);
495 check_err(self, place, ty, san_ty);
498 PlaceTy::from_ty(san_ty)
502 if place.projection.is_empty() {
503 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
504 let tcx = self.tcx();
505 let trait_ref = ty::TraitRef {
506 def_id: tcx.lang_items().copy_trait().unwrap(),
507 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
510 // To have a `Copy` operand, the type `T` of the
511 // value must be `Copy`. Note that we prove that `T: Copy`,
512 // rather than using the `is_copy_modulo_regions`
513 // test. This is important because
514 // `is_copy_modulo_regions` ignores the resulting region
515 // obligations and assumes they pass. This can result in
516 // bounds from `Copy` impls being unsoundly ignored (e.g.,
517 // #29149). Note that we decide to use `Copy` before knowing
518 // whether the bounds fully apply: in effect, the rule is
519 // that if a value of some type could implement `Copy`, then
521 self.cx.prove_trait_ref(
523 location.to_locations(),
524 ConstraintCategory::CopyBound,
529 for elem in place.projection.iter() {
530 if place_ty.variant_index.is_none() {
531 if place_ty.ty.references_error() {
532 assert!(self.errors_reported);
533 return PlaceTy::from_ty(self.tcx().types.err);
536 place_ty = self.sanitize_projection(place_ty, elem, place, location)
542 fn sanitize_promoted(
544 promoted_body: ReadOnlyBodyAndCache<'b, 'tcx>,
547 // Determine the constraints from the promoted MIR by running the type
548 // checker on the promoted MIR, then transfer the constraints back to
549 // the main MIR, changing the locations to the provided location.
551 let parent_body = mem::replace(&mut self.body, *promoted_body);
553 // Use new sets of constraints and closure bounds so that we can
554 // modify their locations.
555 let all_facts = &mut None;
556 let mut constraints = Default::default();
557 let mut closure_bounds = Default::default();
558 let mut liveness_constraints =
559 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
560 // Don't try to add borrow_region facts for the promoted MIR
562 let mut swap_constraints = |this: &mut Self| {
563 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
565 &mut this.cx.borrowck_context.constraints.outlives_constraints,
569 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
573 &mut this.cx.borrowck_context.constraints.liveness_constraints,
574 &mut liveness_constraints,
578 swap_constraints(self);
580 self.visit_body(promoted_body);
582 if !self.errors_reported {
583 // if verifier failed, don't do further checks to avoid ICEs
584 self.cx.typeck_mir(promoted_body);
587 self.body = parent_body;
588 // Merge the outlives constraints back in, at the given location.
589 swap_constraints(self);
591 let locations = location.to_locations();
592 for constraint in constraints.outlives().iter() {
593 let mut constraint = *constraint;
594 constraint.locations = locations;
595 if let ConstraintCategory::Return
596 | ConstraintCategory::UseAsConst
597 | ConstraintCategory::UseAsStatic = constraint.category
599 // "Returning" from a promoted is an assigment to a
600 // temporary from the user's point of view.
601 constraint.category = ConstraintCategory::Boring;
603 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
605 for live_region in liveness_constraints.rows() {
609 .liveness_constraints
610 .add_element(live_region, location);
613 if !closure_bounds.is_empty() {
614 let combined_bounds_mapping =
615 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
620 .closure_bounds_mapping
621 .insert(location, combined_bounds_mapping);
622 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
626 fn sanitize_projection(
629 pi: &PlaceElem<'tcx>,
633 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
634 let tcx = self.tcx();
635 let base_ty = base.ty;
637 ProjectionElem::Deref => {
638 let deref_ty = base_ty.builtin_deref(true);
639 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
640 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
643 ProjectionElem::Index(i) => {
644 let index_ty = Place::from(i).ty(self.body, tcx).ty;
645 if index_ty != tcx.types.usize {
646 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
648 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
649 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
653 ProjectionElem::ConstantIndex { .. } => {
654 // consider verifying in-bounds
655 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
656 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
659 ProjectionElem::Subslice { from, to, from_end } => {
660 PlaceTy::from_ty(match base_ty.kind {
661 ty::Array(inner, _) => {
662 assert!(!from_end, "array subslices should not use from_end");
663 tcx.mk_array(inner, (to - from) as u64)
666 assert!(from_end, "slice subslices should use from_end");
669 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
672 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind {
673 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
674 if index.as_usize() >= adt_def.variants.len() {
675 PlaceTy::from_ty(span_mirbug_and_err!(
678 "cast to variant #{:?} but enum only has {:?}",
680 adt_def.variants.len()
683 PlaceTy { ty: base_ty, variant_index: Some(index) }
686 // We do not need to handle generators here, because this runs
687 // before the generator transform stage.
689 let ty = if let Some(name) = maybe_name {
690 span_mirbug_and_err!(
693 "can't downcast {:?} as {:?}",
698 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
703 ProjectionElem::Field(field, fty) => {
704 let fty = self.sanitize_type(place, fty);
705 match self.field_ty(place, base, field, location) {
707 if let Err(terr) = self.cx.eq_types(
710 location.to_locations(),
711 ConstraintCategory::Boring,
716 "bad field access ({:?}: {:?}): {:?}",
723 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
726 "accessed field #{} but variant only has {}",
731 PlaceTy::from_ty(fty)
736 fn error(&mut self) -> Ty<'tcx> {
737 self.errors_reported = true;
743 parent: &dyn fmt::Debug,
744 base_ty: PlaceTy<'tcx>,
747 ) -> Result<Ty<'tcx>, FieldAccessError> {
748 let tcx = self.tcx();
750 let (variant, substs) = match base_ty {
751 PlaceTy { ty, variant_index: Some(variant_index) } => match ty.kind {
752 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
753 ty::Generator(def_id, substs, _) => {
754 let mut variants = substs.as_generator().state_tys(def_id, tcx);
755 let mut variant = match variants.nth(variant_index.into()) {
758 "variant_index of generator out of range: {:?}/{:?}",
760 substs.as_generator().state_tys(def_id, tcx).count()
763 return match variant.nth(field.index()) {
765 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
768 _ => bug!("can't have downcast of non-adt non-generator type"),
770 PlaceTy { ty, variant_index: None } => match ty.kind {
771 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
772 (&adt_def.variants[VariantIdx::new(0)], substs)
774 ty::Closure(def_id, substs) => {
775 return match substs.as_closure().upvar_tys(def_id, tcx).nth(field.index()) {
777 None => Err(FieldAccessError::OutOfRange {
778 field_count: substs.as_closure().upvar_tys(def_id, tcx).count(),
782 ty::Generator(def_id, substs, _) => {
783 // Only prefix fields (upvars and current state) are
784 // accessible without a variant index.
785 return match substs.as_generator().prefix_tys(def_id, tcx).nth(field.index()) {
787 None => Err(FieldAccessError::OutOfRange {
788 field_count: substs.as_generator().prefix_tys(def_id, tcx).count(),
793 return match tys.get(field.index()) {
794 Some(&ty) => Ok(ty.expect_ty()),
795 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
799 return Ok(span_mirbug_and_err!(
802 "can't project out of {:?}",
809 if let Some(field) = variant.fields.get(field.index()) {
810 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
812 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
817 /// The MIR type checker. Visits the MIR and enforces all the
818 /// constraints needed for it to be valid and well-typed. Along the
819 /// way, it accrues region constraints -- these can later be used by
820 /// NLL region checking.
821 struct TypeChecker<'a, 'tcx> {
822 infcx: &'a InferCtxt<'a, 'tcx>,
823 param_env: ty::ParamEnv<'tcx>,
825 body: &'a Body<'tcx>,
826 /// User type annotations are shared between the main MIR and the MIR of
827 /// all of the promoted items.
828 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
830 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
831 implicit_region_bound: ty::Region<'tcx>,
832 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
833 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
834 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
837 struct BorrowCheckContext<'a, 'tcx> {
838 universal_regions: &'a UniversalRegions<'tcx>,
839 location_table: &'a LocationTable,
840 all_facts: &'a mut Option<AllFacts>,
841 borrow_set: &'a BorrowSet<'tcx>,
842 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
845 crate struct MirTypeckResults<'tcx> {
846 crate constraints: MirTypeckRegionConstraints<'tcx>,
847 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
850 /// A collection of region constraints that must be satisfied for the
851 /// program to be considered well-typed.
852 crate struct MirTypeckRegionConstraints<'tcx> {
853 /// Maps from a `ty::Placeholder` to the corresponding
854 /// `PlaceholderIndex` bit that we will use for it.
856 /// To keep everything in sync, do not insert this set
857 /// directly. Instead, use the `placeholder_region` helper.
858 crate placeholder_indices: PlaceholderIndices,
860 /// Each time we add a placeholder to `placeholder_indices`, we
861 /// also create a corresponding "representative" region vid for
862 /// that wraps it. This vector tracks those. This way, when we
863 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
864 /// the same underlying `RegionVid`.
865 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
867 /// In general, the type-checker is not responsible for enforcing
868 /// liveness constraints; this job falls to the region inferencer,
869 /// which performs a liveness analysis. However, in some limited
870 /// cases, the MIR type-checker creates temporary regions that do
871 /// not otherwise appear in the MIR -- in particular, the
872 /// late-bound regions that it instantiates at call-sites -- and
873 /// hence it must report on their liveness constraints.
874 crate liveness_constraints: LivenessValues<RegionVid>,
876 crate outlives_constraints: OutlivesConstraintSet,
878 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
880 crate closure_bounds_mapping:
881 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
883 crate type_tests: Vec<TypeTest<'tcx>>,
886 impl MirTypeckRegionConstraints<'tcx> {
887 fn placeholder_region(
889 infcx: &InferCtxt<'_, 'tcx>,
890 placeholder: ty::PlaceholderRegion,
891 ) -> ty::Region<'tcx> {
892 let placeholder_index = self.placeholder_indices.insert(placeholder);
893 match self.placeholder_index_to_region.get(placeholder_index) {
896 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
897 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
898 self.placeholder_index_to_region.push(region);
905 /// The `Locations` type summarizes *where* region constraints are
906 /// required to hold. Normally, this is at a particular point which
907 /// created the obligation, but for constraints that the user gave, we
908 /// want the constraint to hold at all points.
909 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
911 /// Indicates that a type constraint should always be true. This
912 /// is particularly important in the new borrowck analysis for
913 /// things like the type of the return slot. Consider this
917 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
919 /// return &y; // error
923 /// Here, we wind up with the signature from the return type being
924 /// something like `&'1 u32` where `'1` is a universal region. But
925 /// the type of the return slot `_0` is something like `&'2 u32`
926 /// where `'2` is an existential region variable. The type checker
927 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
928 /// older NLL analysis, we required this only at the entry point
929 /// to the function. By the nature of the constraints, this wound
930 /// up propagating to all points reachable from start (because
931 /// `'1` -- as a universal region -- is live everywhere). In the
932 /// newer analysis, though, this doesn't work: `_0` is considered
933 /// dead at the start (it has no usable value) and hence this type
934 /// equality is basically a no-op. Then, later on, when we do `_0
935 /// = &'3 y`, that region `'3` never winds up related to the
936 /// universal region `'1` and hence no error occurs. Therefore, we
937 /// use Locations::All instead, which ensures that the `'1` and
938 /// `'2` are equal everything. We also use this for other
939 /// user-given type annotations; e.g., if the user wrote `let mut
940 /// x: &'static u32 = ...`, we would ensure that all values
941 /// assigned to `x` are of `'static` lifetime.
943 /// The span points to the place the constraint arose. For example,
944 /// it points to the type in a user-given type annotation. If
945 /// there's no sensible span then it's DUMMY_SP.
948 /// An outlives constraint that only has to hold at a single location,
949 /// usually it represents a point where references flow from one spot to
950 /// another (e.g., `x = y`)
955 pub fn from_location(&self) -> Option<Location> {
957 Locations::All(_) => None,
958 Locations::Single(from_location) => Some(*from_location),
962 /// Gets a span representing the location.
963 pub fn span(&self, body: &Body<'_>) -> Span {
965 Locations::All(span) => *span,
966 Locations::Single(l) => body.source_info(*l).span,
971 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
973 infcx: &'a InferCtxt<'a, 'tcx>,
974 body: &'a Body<'tcx>,
976 param_env: ty::ParamEnv<'tcx>,
977 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
978 implicit_region_bound: ty::Region<'tcx>,
979 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
980 universal_region_relations: &'a UniversalRegionRelations<'tcx>,
982 let mut checker = Self {
987 user_type_annotations: &body.user_type_annotations,
990 implicit_region_bound,
992 reported_errors: Default::default(),
993 universal_region_relations,
995 checker.check_user_type_annotations();
999 /// Equate the inferred type and the annotated type for user type annotations
1000 fn check_user_type_annotations(&mut self) {
1002 "check_user_type_annotations: user_type_annotations={:?}",
1003 self.user_type_annotations
1005 for user_annotation in self.user_type_annotations {
1006 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1007 let (annotation, _) =
1008 self.infcx.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1010 UserType::Ty(mut ty) => {
1011 ty = self.normalize(ty, Locations::All(span));
1013 if let Err(terr) = self.eq_types(
1016 Locations::All(span),
1017 ConstraintCategory::BoringNoLocation,
1022 "bad user type ({:?} = {:?}): {:?}",
1029 self.prove_predicate(
1030 ty::Predicate::WellFormed(inferred_ty),
1031 Locations::All(span),
1032 ConstraintCategory::TypeAnnotation,
1035 UserType::TypeOf(def_id, user_substs) => {
1036 if let Err(terr) = self.fully_perform_op(
1037 Locations::All(span),
1038 ConstraintCategory::BoringNoLocation,
1039 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1048 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1060 /// Given some operation `op` that manipulates types, proves
1061 /// predicates, or otherwise uses the inference context, executes
1062 /// `op` and then executes all the further obligations that `op`
1063 /// returns. This will yield a set of outlives constraints amongst
1064 /// regions which are extracted and stored as having occurred at
1067 /// **Any `rustc::infer` operations that might generate region
1068 /// constraints should occur within this method so that those
1069 /// constraints can be properly localized!**
1070 fn fully_perform_op<R>(
1072 locations: Locations,
1073 category: ConstraintCategory,
1074 op: impl type_op::TypeOp<'tcx, Output = R>,
1076 let (r, opt_data) = op.fully_perform(self.infcx)?;
1078 if let Some(data) = &opt_data {
1079 self.push_region_constraints(locations, category, data);
1085 fn push_region_constraints(
1087 locations: Locations,
1088 category: ConstraintCategory,
1089 data: &QueryRegionConstraints<'tcx>,
1091 debug!("push_region_constraints: constraints generated at {:?} are {:#?}", locations, data);
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,
1106 /// Convenient wrapper around `relate_tys::relate_types` -- see
1107 /// that fn for docs.
1113 locations: Locations,
1114 category: ConstraintCategory,
1116 relate_tys::relate_types(
1123 Some(self.borrowck_context),
1131 locations: Locations,
1132 category: ConstraintCategory,
1134 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1137 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1138 /// variables in `sub` with their inferred definitions and try
1139 /// again. This is used for opaque types in places (e.g., `let x:
1140 /// impl Foo = ..`).
1141 fn sub_types_or_anon(
1145 locations: Locations,
1146 category: ConstraintCategory,
1148 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1149 if let ty::Opaque(..) = sup.kind {
1150 // When you have `let x: impl Foo = ...` in a closure,
1151 // the resulting inferend values are stored with the
1152 // def-id of the base function.
1153 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1154 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1166 locations: Locations,
1167 category: ConstraintCategory,
1169 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1172 fn relate_type_and_user_type(
1176 user_ty: &UserTypeProjection,
1177 locations: Locations,
1178 category: ConstraintCategory,
1181 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1182 a, v, user_ty, locations,
1185 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1186 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1188 let tcx = self.infcx.tcx;
1190 for proj in &user_ty.projs {
1191 let projected_ty = curr_projected_ty.projection_ty_core(
1195 |this, field, &()| {
1196 let ty = this.field_ty(tcx, field);
1197 self.normalize(ty, locations)
1200 curr_projected_ty = projected_ty;
1203 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1204 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1207 let ty = curr_projected_ty.ty;
1208 self.relate_types(a, v, ty, locations, category)?;
1213 fn eq_opaque_type_and_type(
1215 revealed_ty: Ty<'tcx>,
1217 anon_owner_def_id: DefId,
1218 locations: Locations,
1219 category: ConstraintCategory,
1222 "eq_opaque_type_and_type( \
1225 revealed_ty, anon_ty
1227 let infcx = self.infcx;
1228 let tcx = infcx.tcx;
1229 let param_env = self.param_env;
1230 let body = self.body;
1231 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1232 let opaque_type_map = self.fully_perform_op(
1237 let mut obligations = ObligationAccumulator::default();
1239 let dummy_body_id = ObligationCause::dummy().body_id;
1240 let (output_ty, opaque_type_map) =
1241 obligations.add(infcx.instantiate_opaque_types(
1246 locations.span(body),
1249 "eq_opaque_type_and_type: \
1250 instantiated output_ty={:?} \
1251 opaque_type_map={:#?} \
1253 output_ty, opaque_type_map, revealed_ty
1257 .at(&ObligationCause::dummy(), param_env)
1258 .eq(output_ty, revealed_ty)?,
1261 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1262 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1263 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1264 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1265 let concrete_is_opaque = infcx
1266 .resolve_vars_if_possible(&opaque_decl.concrete_ty)
1270 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?} \
1271 concrete_is_opaque={}",
1272 opaque_decl.concrete_ty,
1273 infcx.resolve_vars_if_possible(&opaque_decl.concrete_ty),
1278 // concrete_is_opaque is `true` when we're using an opaque `impl Trait`
1279 // type without 'revealing' it. For example, code like this:
1281 // type Foo = impl Debug;
1282 // fn foo1() -> Foo { ... }
1283 // fn foo2() -> Foo { foo1() }
1285 // In `foo2`, we're not revealing the type of `Foo` - we're
1286 // just treating it as the opaque type.
1288 // When this occurs, we do *not* want to try to equate
1289 // the concrete type with the underlying defining type
1290 // of the opaque type - this will always fail, since
1291 // the defining type of an opaque type is always
1292 // some other type (e.g. not itself)
1293 // Essentially, none of the normal obligations apply here -
1294 // we're just passing around some unknown opaque type,
1295 // without actually looking at the underlying type it
1296 // gets 'revealed' into
1298 if !concrete_is_opaque {
1301 .at(&ObligationCause::dummy(), param_env)
1302 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?,
1307 debug!("eq_opaque_type_and_type: equated");
1310 value: Some(opaque_type_map),
1311 obligations: obligations.into_vec(),
1314 || "input_output".to_string(),
1318 let universal_region_relations = self.universal_region_relations;
1320 // Finally, if we instantiated the anon types successfully, we
1321 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1322 // prove that `T: Iterator` where `T` is the type we
1323 // instantiated it with).
1324 if let Some(opaque_type_map) = opaque_type_map {
1325 for (opaque_def_id, opaque_decl) in opaque_type_map {
1326 self.fully_perform_op(
1328 ConstraintCategory::OpaqueType,
1331 infcx.constrain_opaque_type(
1334 universal_region_relations,
1336 Ok(InferOk { value: (), obligations: vec![] })
1338 || "opaque_type_map".to_string(),
1346 fn tcx(&self) -> TyCtxt<'tcx> {
1352 body: ReadOnlyBodyAndCache<'_, 'tcx>,
1353 stmt: &Statement<'tcx>,
1356 debug!("check_stmt: {:?}", stmt);
1357 let tcx = self.tcx();
1359 StatementKind::Assign(box (ref place, ref rv)) => {
1360 // Assignments to temporaries are not "interesting";
1361 // they are not caused by the user, but rather artifacts
1362 // of lowering. Assignments to other sorts of places *are* interesting
1364 let category = match place.as_local() {
1365 Some(RETURN_PLACE) => {
1366 if let BorrowCheckContext {
1368 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1370 } = self.borrowck_context
1372 if tcx.is_static(*def_id) {
1373 ConstraintCategory::UseAsStatic
1375 ConstraintCategory::UseAsConst
1378 ConstraintCategory::Return
1381 Some(l) if !body.local_decls[l].is_user_variable() => {
1382 ConstraintCategory::Boring
1384 _ => ConstraintCategory::Assignment,
1387 let place_ty = place.ty(*body, tcx).ty;
1388 let place_ty = self.normalize(place_ty, location);
1389 let rv_ty = rv.ty(*body, tcx);
1390 let rv_ty = self.normalize(rv_ty, location);
1392 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1397 "bad assignment ({:?} = {:?}): {:?}",
1404 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1405 if let Err(terr) = self.relate_type_and_user_type(
1407 ty::Variance::Invariant,
1408 &UserTypeProjection { base: annotation_index, projs: vec![] },
1409 location.to_locations(),
1410 ConstraintCategory::Boring,
1412 let annotation = &self.user_type_annotations[annotation_index];
1416 "bad user type on rvalue ({:?} = {:?}): {:?}",
1424 self.check_rvalue(body, rv, location);
1425 if !self.tcx().features().unsized_locals {
1426 let trait_ref = ty::TraitRef {
1427 def_id: tcx.lang_items().sized_trait().unwrap(),
1428 substs: tcx.mk_substs_trait(place_ty, &[]),
1430 self.prove_trait_ref(
1432 location.to_locations(),
1433 ConstraintCategory::SizedBound,
1437 StatementKind::SetDiscriminant { ref place, variant_index } => {
1438 let place_type = place.ty(*body, tcx).ty;
1439 let adt = match place_type.kind {
1440 ty::Adt(adt, _) if adt.is_enum() => adt,
1443 stmt.source_info.span,
1444 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1450 if variant_index.as_usize() >= adt.variants.len() {
1452 stmt.source_info.span,
1453 "bad set discriminant ({:?} = {:?}): value of of range",
1459 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1460 let place_ty = place.ty(*body, tcx).ty;
1461 if let Err(terr) = self.relate_type_and_user_type(
1465 Locations::All(stmt.source_info.span),
1466 ConstraintCategory::TypeAnnotation,
1468 let annotation = &self.user_type_annotations[projection.base];
1472 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1480 StatementKind::FakeRead(..)
1481 | StatementKind::StorageLive(..)
1482 | StatementKind::StorageDead(..)
1483 | StatementKind::InlineAsm { .. }
1484 | StatementKind::Retag { .. }
1485 | StatementKind::Nop => {}
1489 fn check_terminator(
1492 term: &Terminator<'tcx>,
1493 term_location: Location,
1495 debug!("check_terminator: {:?}", term);
1496 let tcx = self.tcx();
1498 TerminatorKind::Goto { .. }
1499 | TerminatorKind::Resume
1500 | TerminatorKind::Abort
1501 | TerminatorKind::Return
1502 | TerminatorKind::GeneratorDrop
1503 | TerminatorKind::Unreachable
1504 | TerminatorKind::Drop { .. }
1505 | TerminatorKind::FalseEdges { .. }
1506 | TerminatorKind::FalseUnwind { .. } => {
1507 // no checks needed for these
1510 TerminatorKind::DropAndReplace { ref location, ref value, target: _, unwind: _ } => {
1511 let place_ty = location.ty(body, tcx).ty;
1512 let rv_ty = value.ty(body, tcx);
1514 let locations = term_location.to_locations();
1516 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1521 "bad DropAndReplace ({:?} = {:?}): {:?}",
1528 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1529 let discr_ty = discr.ty(body, tcx);
1530 if let Err(terr) = self.sub_types(
1533 term_location.to_locations(),
1534 ConstraintCategory::Assignment,
1539 "bad SwitchInt ({:?} on {:?}): {:?}",
1545 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1546 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1548 // FIXME: check the values
1550 TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1551 let func_ty = func.ty(body, tcx);
1552 debug!("check_terminator: call, func_ty={:?}", func_ty);
1553 let sig = match func_ty.kind {
1554 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1556 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1560 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1561 term.source_info.span,
1562 LateBoundRegionConversionTime::FnCall,
1565 let sig = self.normalize(sig, term_location);
1566 self.check_call_dest(body, term, &sig, destination, term_location);
1568 self.prove_predicates(
1569 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1570 term_location.to_locations(),
1571 ConstraintCategory::Boring,
1574 // The ordinary liveness rules will ensure that all
1575 // regions in the type of the callee are live here. We
1576 // then further constrain the late-bound regions that
1577 // were instantiated at the call site to be live as
1578 // well. The resulting is that all the input (and
1579 // output) types in the signature must be live, since
1580 // all the inputs that fed into it were live.
1581 for &late_bound_region in map.values() {
1583 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1584 self.borrowck_context
1586 .liveness_constraints
1587 .add_element(region_vid, term_location);
1590 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1592 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1593 let cond_ty = cond.ty(body, tcx);
1594 if cond_ty != tcx.types.bool {
1595 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1598 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
1599 if len.ty(body, tcx) != tcx.types.usize {
1600 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1602 if index.ty(body, tcx) != tcx.types.usize {
1603 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1607 TerminatorKind::Yield { ref value, .. } => {
1608 let value_ty = value.ty(body, tcx);
1609 match body.yield_ty {
1610 None => span_mirbug!(self, term, "yield in non-generator"),
1612 if let Err(terr) = self.sub_types(
1615 term_location.to_locations(),
1616 ConstraintCategory::Yield,
1621 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1636 term: &Terminator<'tcx>,
1637 sig: &ty::FnSig<'tcx>,
1638 destination: &Option<(Place<'tcx>, BasicBlock)>,
1639 term_location: Location,
1641 let tcx = self.tcx();
1642 match *destination {
1643 Some((ref dest, _target_block)) => {
1644 let dest_ty = dest.ty(body, tcx).ty;
1645 let dest_ty = self.normalize(dest_ty, term_location);
1646 let category = match dest.as_local() {
1647 Some(RETURN_PLACE) => {
1648 if let BorrowCheckContext {
1650 UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
1652 } = self.borrowck_context
1654 if tcx.is_static(*def_id) {
1655 ConstraintCategory::UseAsStatic
1657 ConstraintCategory::UseAsConst
1660 ConstraintCategory::Return
1663 Some(l) if !body.local_decls[l].is_user_variable() => {
1664 ConstraintCategory::Boring
1666 _ => ConstraintCategory::Assignment,
1669 let locations = term_location.to_locations();
1672 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1677 "call dest mismatch ({:?} <- {:?}): {:?}",
1684 // When `#![feature(unsized_locals)]` is not enabled,
1685 // this check is done at `check_local`.
1686 if self.tcx().features().unsized_locals {
1687 let span = term.source_info.span;
1688 self.ensure_place_sized(dest_ty, span);
1692 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1693 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1699 fn check_call_inputs(
1702 term: &Terminator<'tcx>,
1703 sig: &ty::FnSig<'tcx>,
1704 args: &[Operand<'tcx>],
1705 term_location: Location,
1706 from_hir_call: bool,
1708 debug!("check_call_inputs({:?}, {:?})", sig, args);
1709 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1710 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1712 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1713 let op_arg_ty = op_arg.ty(body, self.tcx());
1714 let category = if from_hir_call {
1715 ConstraintCategory::CallArgument
1717 ConstraintCategory::Boring
1720 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1725 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1735 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1736 let is_cleanup = block_data.is_cleanup;
1737 self.last_span = block_data.terminator().source_info.span;
1738 match block_data.terminator().kind {
1739 TerminatorKind::Goto { target } => {
1740 self.assert_iscleanup(body, block_data, target, is_cleanup)
1742 TerminatorKind::SwitchInt { ref targets, .. } => {
1743 for target in targets {
1744 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1747 TerminatorKind::Resume => {
1749 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1752 TerminatorKind::Abort => {
1754 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1757 TerminatorKind::Return => {
1759 span_mirbug!(self, block_data, "return on cleanup block")
1762 TerminatorKind::GeneratorDrop { .. } => {
1764 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1767 TerminatorKind::Yield { resume, drop, .. } => {
1769 span_mirbug!(self, block_data, "yield in cleanup block")
1771 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1772 if let Some(drop) = drop {
1773 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1776 TerminatorKind::Unreachable => {}
1777 TerminatorKind::Drop { target, unwind, .. }
1778 | TerminatorKind::DropAndReplace { target, unwind, .. }
1779 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1780 self.assert_iscleanup(body, block_data, target, is_cleanup);
1781 if let Some(unwind) = unwind {
1783 span_mirbug!(self, block_data, "unwind on cleanup block")
1785 self.assert_iscleanup(body, block_data, unwind, true);
1788 TerminatorKind::Call { ref destination, cleanup, .. } => {
1789 if let &Some((_, target)) = destination {
1790 self.assert_iscleanup(body, block_data, target, is_cleanup);
1792 if let Some(cleanup) = cleanup {
1794 span_mirbug!(self, block_data, "cleanup on cleanup block")
1796 self.assert_iscleanup(body, block_data, cleanup, true);
1799 TerminatorKind::FalseEdges { real_target, imaginary_target } => {
1800 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1801 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1803 TerminatorKind::FalseUnwind { real_target, unwind } => {
1804 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1805 if let Some(unwind) = unwind {
1807 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1809 self.assert_iscleanup(body, block_data, unwind, true);
1815 fn assert_iscleanup(
1818 ctxt: &dyn fmt::Debug,
1822 if body[bb].is_cleanup != iscleanuppad {
1823 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1827 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1828 match body.local_kind(local) {
1829 LocalKind::ReturnPointer | LocalKind::Arg => {
1830 // return values of normal functions are required to be
1831 // sized by typeck, but return values of ADT constructors are
1832 // not because we don't include a `Self: Sized` bounds on them.
1834 // Unbound parts of arguments were never required to be Sized
1835 // - maybe we should make that a warning.
1838 LocalKind::Var | LocalKind::Temp => {}
1841 // When `#![feature(unsized_locals)]` is enabled, only function calls
1842 // and nullary ops are checked in `check_call_dest`.
1843 if !self.tcx().features().unsized_locals {
1844 let span = local_decl.source_info.span;
1845 let ty = local_decl.ty;
1846 self.ensure_place_sized(ty, span);
1850 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1851 let tcx = self.tcx();
1853 // Erase the regions from `ty` to get a global type. The
1854 // `Sized` bound in no way depends on precise regions, so this
1855 // shouldn't affect `is_sized`.
1856 let erased_ty = tcx.erase_regions(&ty);
1857 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1858 // in current MIR construction, all non-control-flow rvalue
1859 // expressions evaluate through `as_temp` or `into` a return
1860 // slot or local, so to find all unsized rvalues it is enough
1861 // to check all temps, return slots and locals.
1862 if let None = self.reported_errors.replace((ty, span)) {
1863 let mut diag = struct_span_err!(
1867 "cannot move a value of type {0}: the size of {0} \
1868 cannot be statically determined",
1872 // While this is located in `nll::typeck` this error is not
1873 // an NLL error, it's a required check to prevent creation
1874 // of unsized rvalues in certain cases:
1875 // * operand of a box expression
1876 // * callee in a call expression
1882 fn aggregate_field_ty(
1884 ak: &AggregateKind<'tcx>,
1887 ) -> Result<Ty<'tcx>, FieldAccessError> {
1888 let tcx = self.tcx();
1891 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1892 let variant = &def.variants[variant_index];
1893 let adj_field_index = active_field_index.unwrap_or(field_index);
1894 if let Some(field) = variant.fields.get(adj_field_index) {
1895 Ok(self.normalize(field.ty(tcx, substs), location))
1897 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1900 AggregateKind::Closure(def_id, substs) => {
1901 match substs.as_closure().upvar_tys(def_id, tcx).nth(field_index) {
1903 None => Err(FieldAccessError::OutOfRange {
1904 field_count: substs.as_closure().upvar_tys(def_id, tcx).count(),
1908 AggregateKind::Generator(def_id, substs, _) => {
1909 // It doesn't make sense to look at a field beyond the prefix;
1910 // these require a variant index, and are not initialized in
1911 // aggregate rvalues.
1912 match substs.as_generator().prefix_tys(def_id, tcx).nth(field_index) {
1914 None => Err(FieldAccessError::OutOfRange {
1915 field_count: substs.as_generator().prefix_tys(def_id, tcx).count(),
1919 AggregateKind::Array(ty) => Ok(ty),
1920 AggregateKind::Tuple => {
1921 unreachable!("This should have been covered in check_rvalues");
1928 body: ReadOnlyBodyAndCache<'_, 'tcx>,
1929 rvalue: &Rvalue<'tcx>,
1932 let tcx = self.tcx();
1935 Rvalue::Aggregate(ak, ops) => {
1936 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1939 Rvalue::Repeat(operand, len) => {
1941 if let Operand::Move(_) = operand {
1942 // While this is located in `nll::typeck` this error is not an NLL error, it's
1943 // a required check to make sure that repeated elements implement `Copy`.
1944 let span = body.source_info(location).span;
1945 let ty = operand.ty(*body, tcx);
1946 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1947 // To determine if `const_in_array_repeat_expressions` feature gate should
1948 // be mentioned, need to check if the rvalue is promotable.
1949 let should_suggest =
1950 should_suggest_const_in_array_repeat_expressions_attribute(
1956 debug!("check_rvalue: should_suggest={:?}", should_suggest);
1958 self.infcx.report_selection_error(
1959 &traits::Obligation::new(
1960 ObligationCause::new(
1962 self.tcx().hir().def_index_to_hir_id(self.mir_def_id.index),
1963 traits::ObligationCauseCode::RepeatVec(should_suggest),
1966 ty::Predicate::Trait(ty::Binder::bind(ty::TraitPredicate {
1967 trait_ref: ty::TraitRef::new(
1968 self.tcx().lang_items().copy_trait().unwrap(),
1969 tcx.mk_substs_trait(ty, &[]),
1973 &traits::SelectionError::Unimplemented,
1982 Rvalue::NullaryOp(_, ty) => {
1983 // Even with unsized locals cannot box an unsized value.
1984 if self.tcx().features().unsized_locals {
1985 let span = body.source_info(location).span;
1986 self.ensure_place_sized(ty, span);
1989 let trait_ref = ty::TraitRef {
1990 def_id: tcx.lang_items().sized_trait().unwrap(),
1991 substs: tcx.mk_substs_trait(ty, &[]),
1994 self.prove_trait_ref(
1996 location.to_locations(),
1997 ConstraintCategory::SizedBound,
2001 Rvalue::Cast(cast_kind, op, ty) => {
2003 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2004 let fn_sig = op.ty(*body, tcx).fn_sig(tcx);
2006 // The type that we see in the fcx is like
2007 // `foo::<'a, 'b>`, where `foo` is the path to a
2008 // function definition. When we extract the
2009 // signature, it comes from the `fn_sig` query,
2010 // and hence may contain unnormalized results.
2011 let fn_sig = self.normalize(fn_sig, location);
2013 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2015 if let Err(terr) = self.eq_types(
2018 location.to_locations(),
2019 ConstraintCategory::Cast,
2024 "equating {:?} with {:?} yields {:?}",
2032 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2033 let sig = match op.ty(*body, tcx).kind {
2034 ty::Closure(def_id, substs) => {
2035 substs.as_closure().sig_ty(def_id, tcx).fn_sig(tcx)
2039 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2041 if let Err(terr) = self.eq_types(
2044 location.to_locations(),
2045 ConstraintCategory::Cast,
2050 "equating {:?} with {:?} yields {:?}",
2058 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2059 let fn_sig = op.ty(*body, tcx).fn_sig(tcx);
2061 // The type that we see in the fcx is like
2062 // `foo::<'a, 'b>`, where `foo` is the path to a
2063 // function definition. When we extract the
2064 // signature, it comes from the `fn_sig` query,
2065 // and hence may contain unnormalized results.
2066 let fn_sig = self.normalize(fn_sig, location);
2068 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2070 if let Err(terr) = self.eq_types(
2073 location.to_locations(),
2074 ConstraintCategory::Cast,
2079 "equating {:?} with {:?} yields {:?}",
2087 CastKind::Pointer(PointerCast::Unsize) => {
2089 let trait_ref = ty::TraitRef {
2090 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2091 substs: tcx.mk_substs_trait(op.ty(*body, tcx), &[ty.into()]),
2094 self.prove_trait_ref(
2096 location.to_locations(),
2097 ConstraintCategory::Cast,
2101 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2102 let ty_from = match op.ty(*body, tcx).kind {
2103 ty::RawPtr(ty::TypeAndMut {
2105 mutbl: hir::Mutability::Mut,
2111 "unexpected base type for cast {:?}",
2117 let ty_to = match ty.kind {
2118 ty::RawPtr(ty::TypeAndMut {
2120 mutbl: hir::Mutability::Not,
2126 "unexpected target type for cast {:?}",
2132 if let Err(terr) = self.sub_types(
2135 location.to_locations(),
2136 ConstraintCategory::Cast,
2141 "relating {:?} with {:?} yields {:?}",
2149 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2150 let ty_from = op.ty(*body, tcx);
2152 let opt_ty_elem = match ty_from.kind {
2153 ty::RawPtr(ty::TypeAndMut {
2154 mutbl: hir::Mutability::Not,
2156 }) => match array_ty.kind {
2157 ty::Array(ty_elem, _) => Some(ty_elem),
2163 let ty_elem = match opt_ty_elem {
2164 Some(ty_elem) => ty_elem,
2169 "ArrayToPointer cast from unexpected type {:?}",
2176 let ty_to = match ty.kind {
2177 ty::RawPtr(ty::TypeAndMut {
2178 mutbl: hir::Mutability::Not,
2185 "ArrayToPointer cast to unexpected type {:?}",
2192 if let Err(terr) = self.sub_types(
2195 location.to_locations(),
2196 ConstraintCategory::Cast,
2201 "relating {:?} with {:?} yields {:?}",
2210 let ty_from = op.ty(*body, tcx);
2211 let cast_ty_from = CastTy::from_ty(ty_from);
2212 let cast_ty_to = CastTy::from_ty(ty);
2213 match (cast_ty_from, cast_ty_to) {
2216 | (_, Some(CastTy::FnPtr))
2217 | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2218 | (Some(CastTy::Ptr(_)), Some(CastTy::Float))
2219 | (Some(CastTy::FnPtr), Some(CastTy::Float)) => {
2220 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2222 (Some(CastTy::Int(_)), Some(CastTy::Int(_)))
2223 | (Some(CastTy::Float), Some(CastTy::Int(_)))
2224 | (Some(CastTy::Int(_)), Some(CastTy::Float))
2225 | (Some(CastTy::Float), Some(CastTy::Float))
2226 | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_)))
2227 | (Some(CastTy::FnPtr), Some(CastTy::Int(_)))
2228 | (Some(CastTy::Int(_)), Some(CastTy::Ptr(_)))
2229 | (Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_)))
2230 | (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
2236 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2237 self.add_reborrow_constraint(&body, location, region, borrowed_place);
2240 Rvalue::BinaryOp(BinOp::Eq, left, right)
2241 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2242 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2243 | Rvalue::BinaryOp(BinOp::Le, left, right)
2244 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2245 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2246 let ty_left = left.ty(*body, tcx);
2247 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.kind {
2248 let ty_right = right.ty(*body, tcx);
2249 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2250 kind: TypeVariableOriginKind::MiscVariable,
2251 span: body.source_info(location).span,
2256 location.to_locations(),
2257 ConstraintCategory::Boring,
2259 .unwrap_or_else(|err| {
2260 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2262 if let Err(terr) = self.sub_types(
2265 location.to_locations(),
2266 ConstraintCategory::Boring,
2271 "unexpected comparison types {:?} and {:?} yields {:?}",
2280 Rvalue::AddressOf(..)
2283 | Rvalue::BinaryOp(..)
2284 | Rvalue::CheckedBinaryOp(..)
2285 | Rvalue::UnaryOp(..)
2286 | Rvalue::Discriminant(..) => {}
2290 /// If this rvalue supports a user-given type annotation, then
2291 /// extract and return it. This represents the final type of the
2292 /// rvalue and will be unified with the inferred type.
2293 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2296 | Rvalue::Repeat(..)
2298 | Rvalue::AddressOf(..)
2301 | Rvalue::BinaryOp(..)
2302 | Rvalue::CheckedBinaryOp(..)
2303 | Rvalue::NullaryOp(..)
2304 | Rvalue::UnaryOp(..)
2305 | Rvalue::Discriminant(..) => None,
2307 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2308 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2309 AggregateKind::Array(_) => None,
2310 AggregateKind::Tuple => None,
2311 AggregateKind::Closure(_, _) => None,
2312 AggregateKind::Generator(_, _, _) => None,
2317 fn check_aggregate_rvalue(
2320 rvalue: &Rvalue<'tcx>,
2321 aggregate_kind: &AggregateKind<'tcx>,
2322 operands: &[Operand<'tcx>],
2325 let tcx = self.tcx();
2327 self.prove_aggregate_predicates(aggregate_kind, location);
2329 if *aggregate_kind == AggregateKind::Tuple {
2330 // tuple rvalue field type is always the type of the op. Nothing to check here.
2334 for (i, operand) in operands.iter().enumerate() {
2335 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2336 Ok(field_ty) => field_ty,
2337 Err(FieldAccessError::OutOfRange { field_count }) => {
2341 "accessed field #{} but variant only has {}",
2348 let operand_ty = operand.ty(body, tcx);
2350 if let Err(terr) = self.sub_types(
2353 location.to_locations(),
2354 ConstraintCategory::Boring,
2359 "{:?} is not a subtype of {:?}: {:?}",
2368 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2372 /// - `location`: the location `L` where the borrow expression occurs
2373 /// - `borrow_region`: the region `'a` associated with the borrow
2374 /// - `borrowed_place`: the place `P` being borrowed
2375 fn add_reborrow_constraint(
2379 borrow_region: ty::Region<'tcx>,
2380 borrowed_place: &Place<'tcx>,
2382 // These constraints are only meaningful during borrowck:
2383 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2384 self.borrowck_context;
2386 // In Polonius mode, we also push a `borrow_region` fact
2387 // linking the loan to the region (in some cases, though,
2388 // there is no loan associated with this borrow expression --
2389 // that occurs when we are borrowing an unsafe place, for
2391 if let Some(all_facts) = all_facts {
2392 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2393 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2394 let region_vid = borrow_region.to_region_vid();
2395 all_facts.borrow_region.push((
2398 location_table.mid_index(location),
2403 // If we are reborrowing the referent of another reference, we
2404 // need to add outlives relationships. In a case like `&mut
2405 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2406 // need to ensure that `'b: 'a`.
2409 "add_reborrow_constraint({:?}, {:?}, {:?})",
2410 location, borrow_region, borrowed_place
2413 let mut cursor = borrowed_place.projection.as_ref();
2414 while let [proj_base @ .., elem] = cursor {
2417 debug!("add_reborrow_constraint - iteration {:?}", elem);
2420 ProjectionElem::Deref => {
2421 let tcx = self.infcx.tcx;
2422 let base_ty = Place::ty_from(&borrowed_place.base, proj_base, body, tcx).ty;
2424 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2425 match base_ty.kind {
2426 ty::Ref(ref_region, _, mutbl) => {
2427 constraints.outlives_constraints.push(OutlivesConstraint {
2428 sup: ref_region.to_region_vid(),
2429 sub: borrow_region.to_region_vid(),
2430 locations: location.to_locations(),
2431 category: ConstraintCategory::Boring,
2435 hir::Mutability::Not => {
2436 // Immutable reference. We don't need the base
2437 // to be valid for the entire lifetime of
2441 hir::Mutability::Mut => {
2442 // Mutable reference. We *do* need the base
2443 // to be valid, because after the base becomes
2444 // invalid, someone else can use our mutable deref.
2446 // This is in order to make the following function
2449 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2454 // As otherwise you could clone `&mut T` using the
2455 // following function:
2457 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2458 // let my_clone = unsafe_deref(&'a x);
2467 // deref of raw pointer, guaranteed to be valid
2470 ty::Adt(def, _) if def.is_box() => {
2471 // deref of `Box`, need the base to be valid - propagate
2473 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2476 ProjectionElem::Field(..)
2477 | ProjectionElem::Downcast(..)
2478 | ProjectionElem::Index(..)
2479 | ProjectionElem::ConstantIndex { .. }
2480 | ProjectionElem::Subslice { .. } => {
2481 // other field access
2487 fn prove_aggregate_predicates(
2489 aggregate_kind: &AggregateKind<'tcx>,
2492 let tcx = self.tcx();
2495 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2496 aggregate_kind, location
2499 let instantiated_predicates = match aggregate_kind {
2500 AggregateKind::Adt(def, _, substs, _, _) => {
2501 tcx.predicates_of(def.did).instantiate(tcx, substs)
2504 // For closures, we have some **extra requirements** we
2506 // have to check. In particular, in their upvars and
2507 // signatures, closures often reference various regions
2508 // from the surrounding function -- we call those the
2509 // closure's free regions. When we borrow-check (and hence
2510 // region-check) closures, we may find that the closure
2511 // requires certain relationships between those free
2512 // regions. However, because those free regions refer to
2513 // portions of the CFG of their caller, the closure is not
2514 // in a position to verify those relationships. In that
2515 // case, the requirements get "propagated" to us, and so
2516 // we have to solve them here where we instantiate the
2519 // Despite the opacity of the previous parapgrah, this is
2520 // actually relatively easy to understand in terms of the
2521 // desugaring. A closure gets desugared to a struct, and
2522 // these extra requirements are basically like where
2523 // clauses on the struct.
2524 AggregateKind::Closure(def_id, substs)
2525 | AggregateKind::Generator(def_id, substs, _) => {
2526 self.prove_closure_bounds(tcx, *def_id, substs, location)
2529 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2532 self.normalize_and_prove_instantiated_predicates(
2533 instantiated_predicates,
2534 location.to_locations(),
2538 fn prove_closure_bounds(
2542 substs: SubstsRef<'tcx>,
2544 ) -> ty::InstantiatedPredicates<'tcx> {
2545 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2546 let closure_constraints = QueryRegionConstraints {
2547 outlives: closure_region_requirements.apply_requirements(tcx, def_id, substs),
2549 // Presently, closures never propagate member
2550 // constraints to their parents -- they are enforced
2551 // locally. This is largely a non-issue as member
2552 // constraints only come from `-> impl Trait` and
2553 // friends which don't appear (thus far...) in
2555 member_constraints: vec![],
2558 let bounds_mapping = closure_constraints
2562 .filter_map(|(idx, constraint)| {
2563 let ty::OutlivesPredicate(k1, r2) =
2564 constraint.no_bound_vars().unwrap_or_else(|| {
2565 bug!("query_constraint {:?} contained bound vars", constraint,);
2569 GenericArgKind::Lifetime(r1) => {
2570 // constraint is r1: r2
2571 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2572 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2573 let outlives_requirements =
2574 &closure_region_requirements.outlives_requirements[idx];
2577 (outlives_requirements.category, outlives_requirements.blame_span),
2580 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2588 .closure_bounds_mapping
2589 .insert(location, bounds_mapping);
2590 assert!(existing.is_none(), "Multiple closures at the same location.");
2592 self.push_region_constraints(
2593 location.to_locations(),
2594 ConstraintCategory::ClosureBounds,
2595 &closure_constraints,
2599 tcx.predicates_of(def_id).instantiate(tcx, substs)
2604 trait_ref: ty::TraitRef<'tcx>,
2605 locations: Locations,
2606 category: ConstraintCategory,
2608 self.prove_predicates(
2609 Some(ty::Predicate::Trait(trait_ref.to_poly_trait_ref().to_poly_trait_predicate())),
2615 fn normalize_and_prove_instantiated_predicates(
2617 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2618 locations: Locations,
2620 for predicate in instantiated_predicates.predicates {
2621 let predicate = self.normalize(predicate, locations);
2622 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2626 fn prove_predicates(
2628 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2629 locations: Locations,
2630 category: ConstraintCategory,
2632 for predicate in predicates {
2633 debug!("prove_predicates(predicate={:?}, locations={:?})", predicate, locations,);
2635 self.prove_predicate(predicate, locations, category);
2641 predicate: ty::Predicate<'tcx>,
2642 locations: Locations,
2643 category: ConstraintCategory,
2645 debug!("prove_predicate(predicate={:?}, location={:?})", predicate, locations,);
2647 let param_env = self.param_env;
2648 self.fully_perform_op(
2651 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2653 .unwrap_or_else(|NoSolution| {
2654 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2658 fn typeck_mir(&mut self, body: ReadOnlyBodyAndCache<'_, 'tcx>) {
2659 self.last_span = body.span;
2660 debug!("run_on_mir: {:?}", body.span);
2662 for (local, local_decl) in body.local_decls.iter_enumerated() {
2663 self.check_local(&body, local, local_decl);
2666 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2667 let mut location = Location { block, statement_index: 0 };
2668 for stmt in &block_data.statements {
2669 if !stmt.source_info.span.is_dummy() {
2670 self.last_span = stmt.source_info.span;
2672 self.check_stmt(body, stmt, location);
2673 location.statement_index += 1;
2676 self.check_terminator(&body, block_data.terminator(), location);
2677 self.check_iscleanup(&body, block_data);
2681 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2683 T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2685 debug!("normalize(value={:?}, location={:?})", value, location);
2686 let param_env = self.param_env;
2687 self.fully_perform_op(
2688 location.to_locations(),
2689 ConstraintCategory::Boring,
2690 param_env.and(type_op::normalize::Normalize::new(value)),
2692 .unwrap_or_else(|NoSolution| {
2693 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2699 trait NormalizeLocation: fmt::Debug + Copy {
2700 fn to_locations(self) -> Locations;
2703 impl NormalizeLocation for Locations {
2704 fn to_locations(self) -> Locations {
2709 impl NormalizeLocation for Location {
2710 fn to_locations(self) -> Locations {
2711 Locations::Single(self)
2715 #[derive(Debug, Default)]
2716 struct ObligationAccumulator<'tcx> {
2717 obligations: PredicateObligations<'tcx>,
2720 impl<'tcx> ObligationAccumulator<'tcx> {
2721 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2722 let InferOk { value, obligations } = value;
2723 self.obligations.extend(obligations);
2727 fn into_vec(self) -> PredicateObligations<'tcx> {