1 //! This pass type-checks the MIR to ensure it is not broken.
4 use std::{fmt, iter, mem};
8 use rustc_data_structures::frozen::Frozen;
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_data_structures::vec_map::VecMap;
11 use rustc_errors::struct_span_err;
13 use rustc_hir::def::DefKind;
14 use rustc_hir::def_id::LocalDefId;
15 use rustc_hir::lang_items::LangItem;
16 use rustc_index::vec::{Idx, IndexVec};
17 use rustc_infer::infer::canonical::QueryRegionConstraints;
18 use rustc_infer::infer::opaque_types::OpaqueTypeDecl;
19 use rustc_infer::infer::outlives::env::RegionBoundPairs;
20 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
21 use rustc_infer::infer::{
22 InferCtxt, InferOk, LateBoundRegionConversionTime, NllRegionVariableOrigin,
24 use rustc_middle::mir::tcx::PlaceTy;
25 use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
26 use rustc_middle::mir::AssertKind;
27 use rustc_middle::mir::*;
28 use rustc_middle::ty::adjustment::PointerCast;
29 use rustc_middle::ty::cast::CastTy;
30 use rustc_middle::ty::fold::TypeFoldable;
31 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef, UserSubsts};
32 use rustc_middle::ty::{
33 self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, OpaqueTypeKey, RegionVid,
34 ToPredicate, Ty, TyCtxt, UserType, UserTypeAnnotationIndex,
36 use rustc_span::def_id::CRATE_DEF_ID;
37 use rustc_span::{Span, DUMMY_SP};
38 use rustc_target::abi::VariantIdx;
39 use rustc_trait_selection::infer::InferCtxtExt as _;
40 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
41 use rustc_trait_selection::traits::query::type_op;
42 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
43 use rustc_trait_selection::traits::query::Fallible;
44 use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligations};
46 use rustc_const_eval::transform::{
47 check_consts::ConstCx, promote_consts::is_const_fn_in_array_repeat_expression,
49 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
50 use rustc_mir_dataflow::move_paths::MoveData;
51 use rustc_mir_dataflow::ResultsCursor;
54 borrow_set::BorrowSet,
55 constraints::{OutlivesConstraint, OutlivesConstraintSet},
56 diagnostics::UniverseInfo,
58 location::LocationTable,
59 member_constraints::MemberConstraintSet,
62 region_infer::values::{
63 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
65 region_infer::{ClosureRegionRequirementsExt, TypeTest},
66 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
67 universal_regions::{DefiningTy, UniversalRegions},
71 macro_rules! span_mirbug {
72 ($context:expr, $elem:expr, $($message:tt)*) => ({
73 $crate::type_check::mirbug(
77 "broken MIR in {:?} ({:?}): {}",
78 $context.body.source.def_id(),
80 format_args!($($message)*),
86 macro_rules! span_mirbug_and_err {
87 ($context:expr, $elem:expr, $($message:tt)*) => ({
89 span_mirbug!($context, $elem, $($message)*);
96 mod constraint_conversion;
97 pub mod free_region_relations;
102 /// Type checks the given `mir` in the context of the inference
103 /// context `infcx`. Returns any region constraints that have yet to
104 /// be proven. This result includes liveness constraints that
105 /// ensure that regions appearing in the types of all local variables
106 /// are live at all points where that local variable may later be
109 /// This phase of type-check ought to be infallible -- this is because
110 /// the original, HIR-based type-check succeeded. So if any errors
111 /// occur here, we will get a `bug!` reported.
115 /// - `infcx` -- inference context to use
116 /// - `param_env` -- parameter environment to use for trait solving
117 /// - `body` -- MIR body to type-check
118 /// - `promoted` -- map of promoted constants within `body`
119 /// - `universal_regions` -- the universal regions from `body`s function signature
120 /// - `location_table` -- MIR location map of `body`
121 /// - `borrow_set` -- information about borrows occurring in `body`
122 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
123 /// - `flow_inits` -- results of a maybe-init dataflow analysis
124 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
125 /// - `elements` -- MIR region map
126 pub(crate) fn type_check<'mir, 'tcx>(
127 infcx: &InferCtxt<'_, 'tcx>,
128 param_env: ty::ParamEnv<'tcx>,
130 promoted: &IndexVec<Promoted, Body<'tcx>>,
131 universal_regions: &Rc<UniversalRegions<'tcx>>,
132 location_table: &LocationTable,
133 borrow_set: &BorrowSet<'tcx>,
134 all_facts: &mut Option<AllFacts>,
135 flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
136 move_data: &MoveData<'tcx>,
137 elements: &Rc<RegionValueElements>,
138 upvars: &[Upvar<'tcx>],
139 ) -> MirTypeckResults<'tcx> {
140 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
141 let mut universe_causes = FxHashMap::default();
142 universe_causes.insert(ty::UniverseIndex::from_u32(0), UniverseInfo::other());
143 let mut constraints = MirTypeckRegionConstraints {
144 placeholder_indices: PlaceholderIndices::default(),
145 placeholder_index_to_region: IndexVec::default(),
146 liveness_constraints: LivenessValues::new(elements.clone()),
147 outlives_constraints: OutlivesConstraintSet::default(),
148 member_constraints: MemberConstraintSet::default(),
149 closure_bounds_mapping: Default::default(),
150 type_tests: Vec::default(),
155 universal_region_relations,
157 normalized_inputs_and_output,
158 } = free_region_relations::create(
161 Some(implicit_region_bound),
166 for u in ty::UniverseIndex::ROOT..infcx.universe() {
167 let info = UniverseInfo::other();
168 constraints.universe_causes.insert(u, info);
171 let mut borrowck_context = BorrowCheckContext {
176 constraints: &mut constraints,
180 let opaque_type_values = type_check_internal(
186 implicit_region_bound,
187 &mut borrowck_context,
189 cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
190 liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
192 translate_outlives_facts(&mut cx);
193 let opaque_type_values = mem::take(&mut infcx.inner.borrow_mut().opaque_types);
197 .filter_map(|(opaque_type_key, mut decl)| {
198 decl.concrete_ty = infcx.resolve_vars_if_possible(decl.concrete_ty);
200 "finalized opaque type {:?} to {:#?}",
202 decl.concrete_ty.kind()
204 if decl.concrete_ty.has_infer_types_or_consts() {
205 infcx.tcx.sess.delay_span_bug(
207 &format!("could not resolve {:#?}", decl.concrete_ty.kind()),
209 decl.concrete_ty = infcx.tcx.ty_error();
211 let concrete_is_opaque = if let ty::Opaque(def_id, _) = decl.concrete_ty.kind()
213 *def_id == opaque_type_key.def_id
218 if concrete_is_opaque {
219 // We're using an opaque `impl Trait` type without
220 // 'revealing' it. For example, code like this:
222 // type Foo = impl Debug;
223 // fn foo1() -> Foo { ... }
224 // fn foo2() -> Foo { foo1() }
226 // In `foo2`, we're not revealing the type of `Foo` - we're
227 // just treating it as the opaque type.
229 // When this occurs, we do *not* want to try to equate
230 // the concrete type with the underlying defining type
231 // of the opaque type - this will always fail, since
232 // the defining type of an opaque type is always
233 // some other type (e.g. not itself)
234 // Essentially, none of the normal obligations apply here -
235 // we're just passing around some unknown opaque type,
236 // without actually looking at the underlying type it
237 // gets 'revealed' into
239 "eq_opaque_type_and_type: non-defining use of {:?}",
240 opaque_type_key.def_id,
244 Some((opaque_type_key, decl))
251 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
255 skip(infcx, body, promoted, region_bound_pairs, borrowck_context, extra),
258 fn type_check_internal<'a, 'tcx, R>(
259 infcx: &'a InferCtxt<'a, 'tcx>,
260 param_env: ty::ParamEnv<'tcx>,
261 body: &'a Body<'tcx>,
262 promoted: &'a IndexVec<Promoted, Body<'tcx>>,
263 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
264 implicit_region_bound: ty::Region<'tcx>,
265 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
266 extra: impl FnOnce(TypeChecker<'a, 'tcx>) -> R,
268 let mut checker = TypeChecker::new(
273 implicit_region_bound,
276 let errors_reported = {
277 let mut verifier = TypeVerifier::new(&mut checker, body, promoted);
278 verifier.visit_body(&body);
279 verifier.errors_reported
282 if !errors_reported {
283 // if verifier failed, don't do further checks to avoid ICEs
284 checker.typeck_mir(body);
290 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
291 let cx = &mut typeck.borrowck_context;
292 if let Some(facts) = cx.all_facts {
293 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
294 let location_table = cx.location_table;
295 facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
296 |constraint: &OutlivesConstraint<'_>| {
297 if let Some(from_location) = constraint.locations.from_location() {
298 Either::Left(iter::once((
301 location_table.mid_index(from_location),
307 .map(move |location| (constraint.sup, constraint.sub, location)),
315 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
316 // We sometimes see MIR failures (notably predicate failures) due to
317 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
318 // to avoid reporting bugs in those cases.
319 tcx.sess.diagnostic().delay_span_bug(span, msg);
322 enum FieldAccessError {
323 OutOfRange { field_count: usize },
326 /// Verifies that MIR types are sane to not crash further checks.
328 /// The sanitize_XYZ methods here take an MIR object and compute its
329 /// type, calling `span_mirbug` and returning an error type if there
331 struct TypeVerifier<'a, 'b, 'tcx> {
332 cx: &'a mut TypeChecker<'b, 'tcx>,
333 body: &'b Body<'tcx>,
334 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
336 errors_reported: bool,
339 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
340 fn visit_span(&mut self, span: &Span) {
341 if !span.is_dummy() {
342 self.last_span = *span;
346 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
347 self.sanitize_place(place, location, context);
350 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
351 self.super_constant(constant, location);
352 let ty = self.sanitize_type(constant, constant.literal.ty());
354 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
355 let live_region_vid =
356 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
360 .liveness_constraints
361 .add_element(live_region_vid, location);
364 if let Some(annotation_index) = constant.user_ty {
365 if let Err(terr) = self.cx.relate_type_and_user_type(
366 constant.literal.ty(),
367 ty::Variance::Invariant,
368 &UserTypeProjection { base: annotation_index, projs: vec![] },
369 location.to_locations(),
370 ConstraintCategory::Boring,
372 let annotation = &self.cx.user_type_annotations[annotation_index];
376 "bad constant user type {:?} vs {:?}: {:?}",
378 constant.literal.ty(),
383 let tcx = self.tcx();
384 let maybe_uneval = match constant.literal {
385 ConstantKind::Ty(ct) => match ct.val {
386 ty::ConstKind::Unevaluated(uv) => Some(uv),
391 if let Some(uv) = maybe_uneval {
392 if let Some(promoted) = uv.promoted {
393 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
394 promoted: &Body<'tcx>,
397 if let Err(terr) = verifier.cx.eq_types(
400 location.to_locations(),
401 ConstraintCategory::Boring,
406 "bad promoted type ({:?}: {:?}): {:?}",
414 if !self.errors_reported {
415 let promoted_body = &self.promoted[promoted];
416 self.sanitize_promoted(promoted_body, location);
418 let promoted_ty = promoted_body.return_ty();
419 check_err(self, promoted_body, ty, promoted_ty);
422 if let Err(terr) = self.cx.fully_perform_op(
423 location.to_locations(),
424 ConstraintCategory::Boring,
425 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
426 constant.literal.ty(),
428 UserSubsts { substs: uv.substs(self.tcx()), user_self_ty: None },
434 "bad constant type {:?} ({:?})",
440 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
441 let unnormalized_ty = tcx.type_of(static_def_id);
442 let locations = location.to_locations();
443 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
444 let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty;
446 if let Err(terr) = self.cx.eq_types(
450 ConstraintCategory::Boring,
452 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
456 if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() {
457 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
458 self.cx.normalize_and_prove_instantiated_predicates(
460 instantiated_predicates,
461 location.to_locations(),
467 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
468 self.super_rvalue(rvalue, location);
469 let rval_ty = rvalue.ty(self.body, self.tcx());
470 self.sanitize_type(rvalue, rval_ty);
473 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
474 self.super_local_decl(local, local_decl);
475 self.sanitize_type(local_decl, local_decl.ty);
477 if let Some(user_ty) = &local_decl.user_ty {
478 for (user_ty, span) in user_ty.projections_and_spans() {
479 let ty = if !local_decl.is_nonref_binding() {
480 // If we have a binding of the form `let ref x: T = ..`
481 // then remove the outermost reference so we can check the
482 // type annotation for the remaining type.
483 if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
486 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
492 if let Err(terr) = self.cx.relate_type_and_user_type(
494 ty::Variance::Invariant,
496 Locations::All(*span),
497 ConstraintCategory::TypeAnnotation,
502 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
513 fn visit_body(&mut self, body: &Body<'tcx>) {
514 self.sanitize_type(&"return type", body.return_ty());
515 for local_decl in &body.local_decls {
516 self.sanitize_type(local_decl, local_decl.ty);
518 if self.errors_reported {
521 self.super_body(body);
525 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
527 cx: &'a mut TypeChecker<'b, 'tcx>,
528 body: &'b Body<'tcx>,
529 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
531 TypeVerifier { body, promoted, cx, last_span: body.span, errors_reported: false }
534 fn tcx(&self) -> TyCtxt<'tcx> {
538 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
539 if ty.has_escaping_bound_vars() || ty.references_error() {
540 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
546 /// Checks that the types internal to the `place` match up with
547 /// what would be expected.
552 context: PlaceContext,
554 debug!("sanitize_place: {:?}", place);
556 let mut place_ty = PlaceTy::from_ty(self.body.local_decls[place.local].ty);
558 for elem in place.projection.iter() {
559 if place_ty.variant_index.is_none() {
560 if place_ty.ty.references_error() {
561 assert!(self.errors_reported);
562 return PlaceTy::from_ty(self.tcx().ty_error());
565 place_ty = self.sanitize_projection(place_ty, elem, place, location);
568 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
569 let tcx = self.tcx();
570 let trait_ref = ty::TraitRef {
571 def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
572 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
575 // To have a `Copy` operand, the type `T` of the
576 // value must be `Copy`. Note that we prove that `T: Copy`,
577 // rather than using the `is_copy_modulo_regions`
578 // test. This is important because
579 // `is_copy_modulo_regions` ignores the resulting region
580 // obligations and assumes they pass. This can result in
581 // bounds from `Copy` impls being unsoundly ignored (e.g.,
582 // #29149). Note that we decide to use `Copy` before knowing
583 // whether the bounds fully apply: in effect, the rule is
584 // that if a value of some type could implement `Copy`, then
586 self.cx.prove_trait_ref(
588 location.to_locations(),
589 ConstraintCategory::CopyBound,
596 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
597 // Determine the constraints from the promoted MIR by running the type
598 // checker on the promoted MIR, then transfer the constraints back to
599 // the main MIR, changing the locations to the provided location.
601 let parent_body = mem::replace(&mut self.body, promoted_body);
603 // Use new sets of constraints and closure bounds so that we can
604 // modify their locations.
605 let all_facts = &mut None;
606 let mut constraints = Default::default();
607 let mut closure_bounds = Default::default();
608 let mut liveness_constraints =
609 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
610 // Don't try to add borrow_region facts for the promoted MIR
612 let mut swap_constraints = |this: &mut Self| {
613 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
615 &mut this.cx.borrowck_context.constraints.outlives_constraints,
619 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
623 &mut this.cx.borrowck_context.constraints.liveness_constraints,
624 &mut liveness_constraints,
628 swap_constraints(self);
630 self.visit_body(&promoted_body);
632 if !self.errors_reported {
633 // if verifier failed, don't do further checks to avoid ICEs
634 self.cx.typeck_mir(promoted_body);
637 self.body = parent_body;
638 // Merge the outlives constraints back in, at the given location.
639 swap_constraints(self);
641 let locations = location.to_locations();
642 for constraint in constraints.outlives().iter() {
643 let mut constraint = constraint.clone();
644 constraint.locations = locations;
645 if let ConstraintCategory::Return(_)
646 | ConstraintCategory::UseAsConst
647 | ConstraintCategory::UseAsStatic = constraint.category
649 // "Returning" from a promoted is an assignment to a
650 // temporary from the user's point of view.
651 constraint.category = ConstraintCategory::Boring;
653 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
655 for region in liveness_constraints.rows() {
656 // If the region is live at at least one location in the promoted MIR,
657 // then add a liveness constraint to the main MIR for this region
658 // at the location provided as an argument to this method
659 if liveness_constraints.get_elements(region).next().is_some() {
663 .liveness_constraints
664 .add_element(region, location);
668 if !closure_bounds.is_empty() {
669 let combined_bounds_mapping =
670 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
675 .closure_bounds_mapping
676 .insert(location, combined_bounds_mapping);
677 assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
681 fn sanitize_projection(
688 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
689 let tcx = self.tcx();
690 let base_ty = base.ty;
692 ProjectionElem::Deref => {
693 let deref_ty = base_ty.builtin_deref(true);
694 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
695 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
698 ProjectionElem::Index(i) => {
699 let index_ty = Place::from(i).ty(self.body, tcx).ty;
700 if index_ty != tcx.types.usize {
701 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
703 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
704 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
708 ProjectionElem::ConstantIndex { .. } => {
709 // consider verifying in-bounds
710 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
711 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
714 ProjectionElem::Subslice { from, to, from_end } => {
715 PlaceTy::from_ty(match base_ty.kind() {
716 ty::Array(inner, _) => {
717 assert!(!from_end, "array subslices should not use from_end");
718 tcx.mk_array(inner, to - from)
721 assert!(from_end, "slice subslices should use from_end");
724 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
727 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
728 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
729 if index.as_usize() >= adt_def.variants.len() {
730 PlaceTy::from_ty(span_mirbug_and_err!(
733 "cast to variant #{:?} but enum only has {:?}",
735 adt_def.variants.len()
738 PlaceTy { ty: base_ty, variant_index: Some(index) }
741 // We do not need to handle generators here, because this runs
742 // before the generator transform stage.
744 let ty = if let Some(name) = maybe_name {
745 span_mirbug_and_err!(
748 "can't downcast {:?} as {:?}",
753 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
758 ProjectionElem::Field(field, fty) => {
759 let fty = self.sanitize_type(place, fty);
760 match self.field_ty(place, base, field, location) {
762 let ty = self.cx.normalize(ty, location);
763 if let Err(terr) = self.cx.eq_types(
766 location.to_locations(),
767 ConstraintCategory::Boring,
772 "bad field access ({:?}: {:?}): {:?}",
779 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
782 "accessed field #{} but variant only has {}",
787 PlaceTy::from_ty(fty)
792 fn error(&mut self) -> Ty<'tcx> {
793 self.errors_reported = true;
794 self.tcx().ty_error()
799 parent: &dyn fmt::Debug,
800 base_ty: PlaceTy<'tcx>,
803 ) -> Result<Ty<'tcx>, FieldAccessError> {
804 let tcx = self.tcx();
806 let (variant, substs) = match base_ty {
807 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
808 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
809 ty::Generator(def_id, substs, _) => {
810 let mut variants = substs.as_generator().state_tys(def_id, tcx);
811 let mut variant = match variants.nth(variant_index.into()) {
814 "variant_index of generator out of range: {:?}/{:?}",
816 substs.as_generator().state_tys(def_id, tcx).count()
819 return match variant.nth(field.index()) {
821 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
824 _ => bug!("can't have downcast of non-adt non-generator type"),
826 PlaceTy { ty, variant_index: None } => match *ty.kind() {
827 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
828 (&adt_def.variants[VariantIdx::new(0)], substs)
830 ty::Closure(_, substs) => {
834 .tuple_element_ty(field.index())
837 None => Err(FieldAccessError::OutOfRange {
838 field_count: substs.as_closure().upvar_tys().count(),
842 ty::Generator(_, substs, _) => {
843 // Only prefix fields (upvars and current state) are
844 // accessible without a variant index.
845 return match substs.as_generator().prefix_tys().nth(field.index()) {
847 None => Err(FieldAccessError::OutOfRange {
848 field_count: substs.as_generator().prefix_tys().count(),
853 return match tys.get(field.index()) {
854 Some(&ty) => Ok(ty.expect_ty()),
855 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
859 return Ok(span_mirbug_and_err!(
862 "can't project out of {:?}",
869 if let Some(field) = variant.fields.get(field.index()) {
870 Ok(self.cx.normalize(field.ty(tcx, substs), location))
872 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
877 /// The MIR type checker. Visits the MIR and enforces all the
878 /// constraints needed for it to be valid and well-typed. Along the
879 /// way, it accrues region constraints -- these can later be used by
880 /// NLL region checking.
881 struct TypeChecker<'a, 'tcx> {
882 infcx: &'a InferCtxt<'a, 'tcx>,
883 param_env: ty::ParamEnv<'tcx>,
885 body: &'a Body<'tcx>,
886 /// User type annotations are shared between the main MIR and the MIR of
887 /// all of the promoted items.
888 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
889 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
890 implicit_region_bound: ty::Region<'tcx>,
891 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
892 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
895 struct BorrowCheckContext<'a, 'tcx> {
896 pub(crate) universal_regions: &'a UniversalRegions<'tcx>,
897 location_table: &'a LocationTable,
898 all_facts: &'a mut Option<AllFacts>,
899 borrow_set: &'a BorrowSet<'tcx>,
900 pub(crate) constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
901 upvars: &'a [Upvar<'tcx>],
904 crate struct MirTypeckResults<'tcx> {
905 crate constraints: MirTypeckRegionConstraints<'tcx>,
906 crate universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
907 crate opaque_type_values: VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>,
910 /// A collection of region constraints that must be satisfied for the
911 /// program to be considered well-typed.
912 crate struct MirTypeckRegionConstraints<'tcx> {
913 /// Maps from a `ty::Placeholder` to the corresponding
914 /// `PlaceholderIndex` bit that we will use for it.
916 /// To keep everything in sync, do not insert this set
917 /// directly. Instead, use the `placeholder_region` helper.
918 crate placeholder_indices: PlaceholderIndices,
920 /// Each time we add a placeholder to `placeholder_indices`, we
921 /// also create a corresponding "representative" region vid for
922 /// that wraps it. This vector tracks those. This way, when we
923 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
924 /// the same underlying `RegionVid`.
925 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
927 /// In general, the type-checker is not responsible for enforcing
928 /// liveness constraints; this job falls to the region inferencer,
929 /// which performs a liveness analysis. However, in some limited
930 /// cases, the MIR type-checker creates temporary regions that do
931 /// not otherwise appear in the MIR -- in particular, the
932 /// late-bound regions that it instantiates at call-sites -- and
933 /// hence it must report on their liveness constraints.
934 crate liveness_constraints: LivenessValues<RegionVid>,
936 crate outlives_constraints: OutlivesConstraintSet<'tcx>,
938 crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
940 crate closure_bounds_mapping:
941 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
943 crate universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
945 crate type_tests: Vec<TypeTest<'tcx>>,
948 impl<'tcx> MirTypeckRegionConstraints<'tcx> {
949 fn placeholder_region(
951 infcx: &InferCtxt<'_, 'tcx>,
952 placeholder: ty::PlaceholderRegion,
953 ) -> ty::Region<'tcx> {
954 let placeholder_index = self.placeholder_indices.insert(placeholder);
955 match self.placeholder_index_to_region.get(placeholder_index) {
958 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
959 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
960 self.placeholder_index_to_region.push(region);
967 /// The `Locations` type summarizes *where* region constraints are
968 /// required to hold. Normally, this is at a particular point which
969 /// created the obligation, but for constraints that the user gave, we
970 /// want the constraint to hold at all points.
971 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
973 /// Indicates that a type constraint should always be true. This
974 /// is particularly important in the new borrowck analysis for
975 /// things like the type of the return slot. Consider this
979 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
981 /// return &y; // error
985 /// Here, we wind up with the signature from the return type being
986 /// something like `&'1 u32` where `'1` is a universal region. But
987 /// the type of the return slot `_0` is something like `&'2 u32`
988 /// where `'2` is an existential region variable. The type checker
989 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
990 /// older NLL analysis, we required this only at the entry point
991 /// to the function. By the nature of the constraints, this wound
992 /// up propagating to all points reachable from start (because
993 /// `'1` -- as a universal region -- is live everywhere). In the
994 /// newer analysis, though, this doesn't work: `_0` is considered
995 /// dead at the start (it has no usable value) and hence this type
996 /// equality is basically a no-op. Then, later on, when we do `_0
997 /// = &'3 y`, that region `'3` never winds up related to the
998 /// universal region `'1` and hence no error occurs. Therefore, we
999 /// use Locations::All instead, which ensures that the `'1` and
1000 /// `'2` are equal everything. We also use this for other
1001 /// user-given type annotations; e.g., if the user wrote `let mut
1002 /// x: &'static u32 = ...`, we would ensure that all values
1003 /// assigned to `x` are of `'static` lifetime.
1005 /// The span points to the place the constraint arose. For example,
1006 /// it points to the type in a user-given type annotation. If
1007 /// there's no sensible span then it's DUMMY_SP.
1010 /// An outlives constraint that only has to hold at a single location,
1011 /// usually it represents a point where references flow from one spot to
1012 /// another (e.g., `x = y`)
1017 pub fn from_location(&self) -> Option<Location> {
1019 Locations::All(_) => None,
1020 Locations::Single(from_location) => Some(*from_location),
1024 /// Gets a span representing the location.
1025 pub fn span(&self, body: &Body<'_>) -> Span {
1027 Locations::All(span) => *span,
1028 Locations::Single(l) => body.source_info(*l).span,
1033 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1035 infcx: &'a InferCtxt<'a, 'tcx>,
1036 body: &'a Body<'tcx>,
1037 param_env: ty::ParamEnv<'tcx>,
1038 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1039 implicit_region_bound: ty::Region<'tcx>,
1040 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1042 let mut checker = Self {
1044 last_span: DUMMY_SP,
1046 user_type_annotations: &body.user_type_annotations,
1049 implicit_region_bound,
1051 reported_errors: Default::default(),
1053 checker.check_user_type_annotations();
1057 fn unsized_feature_enabled(&self) -> bool {
1058 let features = self.tcx().features();
1059 features.unsized_locals || features.unsized_fn_params
1062 /// Equate the inferred type and the annotated type for user type annotations
1063 fn check_user_type_annotations(&mut self) {
1065 "check_user_type_annotations: user_type_annotations={:?}",
1066 self.user_type_annotations
1068 for user_annotation in self.user_type_annotations {
1069 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1070 let inferred_ty = self.normalize(inferred_ty, Locations::All(span));
1071 let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1073 UserType::Ty(mut ty) => {
1074 ty = self.normalize(ty, Locations::All(span));
1076 if let Err(terr) = self.eq_types(
1079 Locations::All(span),
1080 ConstraintCategory::BoringNoLocation,
1085 "bad user type ({:?} = {:?}): {:?}",
1092 self.prove_predicate(
1093 ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into()))
1094 .to_predicate(self.tcx()),
1095 Locations::All(span),
1096 ConstraintCategory::TypeAnnotation,
1099 UserType::TypeOf(def_id, user_substs) => {
1100 if let Err(terr) = self.fully_perform_op(
1101 Locations::All(span),
1102 ConstraintCategory::BoringNoLocation,
1103 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1112 "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}",
1116 self.tcx().type_of(def_id),
1125 #[instrument(skip(self, data), level = "debug")]
1126 fn push_region_constraints(
1128 locations: Locations,
1129 category: ConstraintCategory,
1130 data: &QueryRegionConstraints<'tcx>,
1132 debug!("constraints generated: {:#?}", data);
1134 constraint_conversion::ConstraintConversion::new(
1136 self.borrowck_context.universal_regions,
1137 self.region_bound_pairs,
1138 Some(self.implicit_region_bound),
1142 &mut self.borrowck_context.constraints,
1147 /// Try to relate `sub <: sup`
1152 locations: Locations,
1153 category: ConstraintCategory,
1155 // Use this order of parameters because the sup type is usually the
1156 // "expected" type in diagnostics.
1157 self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
1160 #[instrument(skip(self, category), level = "debug")]
1165 locations: Locations,
1166 category: ConstraintCategory,
1168 self.relate_types(expected, ty::Variance::Invariant, found, locations, category)
1171 #[instrument(skip(self), level = "debug")]
1172 fn relate_type_and_user_type(
1176 user_ty: &UserTypeProjection,
1177 locations: Locations,
1178 category: ConstraintCategory,
1180 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1181 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1183 let tcx = self.infcx.tcx;
1185 for proj in &user_ty.projs {
1186 let projected_ty = curr_projected_ty.projection_ty_core(
1190 |this, field, &()| {
1191 let ty = this.field_ty(tcx, field);
1192 self.normalize(ty, locations)
1195 curr_projected_ty = projected_ty;
1198 "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1199 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1202 let ty = curr_projected_ty.ty;
1203 self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1208 /// Equates a type `anon_ty` that may contain opaque types whose
1209 /// values are to be inferred by the MIR.
1211 /// The type `revealed_ty` contains the same type as `anon_ty`, but with the
1212 /// hidden types for impl traits revealed.
1216 /// Consider a piece of code like
1219 /// type Foo<U> = impl Debug;
1221 /// fn foo<T: Debug>(t: T) -> Box<Foo<T>> {
1222 /// Box::new((t, 22_u32))
1226 /// Here, the function signature would be something like
1227 /// `fn(T) -> Box<impl Debug>`. The MIR return slot would have
1228 /// the type with the opaque type revealed, so `Box<(T, u32)>`.
1230 /// In terms of our function parameters:
1232 /// * `anon_ty` would be `Box<Foo<T>>` where `Foo<T>` is an opaque type
1233 /// scoped to this function (note that it is parameterized by the
1234 /// generics of `foo`). Note that `anon_ty` is not just the opaque type,
1235 /// but the entire return type (which may contain opaque types within it).
1236 /// * `revealed_ty` would be `Box<(T, u32)>`
1237 #[instrument(skip(self), level = "debug")]
1238 fn eq_opaque_type_and_type(
1240 revealed_ty: Ty<'tcx>,
1242 locations: Locations,
1243 category: ConstraintCategory,
1245 // Fast path for the common case.
1246 if !anon_ty.has_opaque_types() {
1247 if let Err(terr) = self.eq_types(anon_ty, revealed_ty, locations, category) {
1251 "eq_opaque_type_and_type: `{:?}=={:?}` failed with `{:?}`",
1260 let param_env = self.param_env;
1261 let body = self.body;
1262 let mir_def_id = body.source.def_id().expect_local();
1264 debug!(?mir_def_id);
1265 self.fully_perform_op(
1270 let mut obligations = ObligationAccumulator::default();
1272 let dummy_body_id = hir::CRATE_HIR_ID;
1274 // Replace the opaque types defined by this function with
1275 // inference variables, creating a map. In our example above,
1276 // this would transform the type `Box<Foo<T>>` (where `Foo` is an opaque type)
1277 // to `Box<?T>`, returning an `opaque_type_map` mapping `{Foo<T> -> ?T}`.
1278 // (Note that the key of the map is both the def-id of `Foo` along with
1279 // any generic parameters.)
1280 let output_ty = obligations.add(infcx.instantiate_opaque_types(
1284 locations.span(body),
1286 debug!(?output_ty, ?revealed_ty);
1288 // Make sure that the inferred types are well-formed. I'm
1289 // not entirely sure this is needed (the HIR type check
1290 // didn't do this) but it seems sensible to prevent opaque
1291 // types hiding ill-formed types.
1292 obligations.obligations.push(traits::Obligation::new(
1293 ObligationCause::dummy(),
1295 ty::Binder::dummy(ty::PredicateKind::WellFormed(revealed_ty.into()))
1296 .to_predicate(infcx.tcx),
1300 .at(&ObligationCause::dummy(), param_env)
1301 .eq(output_ty, revealed_ty)?,
1306 Ok(InferOk { value: (), obligations: obligations.into_vec() })
1308 || "input_output".to_string(),
1312 // Finally, if we instantiated the anon types successfully, we
1313 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1314 // prove that `T: Iterator` where `T` is the type we
1315 // instantiated it with).
1316 let opaque_type_map = self.infcx.inner.borrow().opaque_types.clone();
1317 for (opaque_type_key, opaque_decl) in opaque_type_map {
1318 self.fully_perform_op(
1320 ConstraintCategory::OpaqueType,
1323 infcx.constrain_opaque_type(opaque_type_key, &opaque_decl);
1324 Ok(InferOk { value: (), obligations: vec![] })
1326 || "opaque_type_map".to_string(),
1333 fn tcx(&self) -> TyCtxt<'tcx> {
1337 #[instrument(skip(self, body, location), level = "debug")]
1338 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1339 let tcx = self.tcx();
1341 StatementKind::Assign(box (ref place, ref rv)) => {
1342 // Assignments to temporaries are not "interesting";
1343 // they are not caused by the user, but rather artifacts
1344 // of lowering. Assignments to other sorts of places *are* interesting
1346 let category = match place.as_local() {
1347 Some(RETURN_PLACE) => {
1348 let defining_ty = &self.borrowck_context.universal_regions.defining_ty;
1349 if defining_ty.is_const() {
1350 if tcx.is_static(defining_ty.def_id()) {
1351 ConstraintCategory::UseAsStatic
1353 ConstraintCategory::UseAsConst
1356 ConstraintCategory::Return(ReturnConstraint::Normal)
1361 body.local_decls[l].local_info,
1362 Some(box LocalInfo::AggregateTemp)
1365 ConstraintCategory::Usage
1367 Some(l) if !body.local_decls[l].is_user_variable() => {
1368 ConstraintCategory::Boring
1370 _ => ConstraintCategory::Assignment,
1373 "assignment category: {:?} {:?}",
1375 place.as_local().map(|l| &body.local_decls[l])
1378 let place_ty = place.ty(body, tcx).ty;
1379 let place_ty = self.normalize(place_ty, location);
1380 let rv_ty = rv.ty(body, tcx);
1381 let rv_ty = self.normalize(rv_ty, location);
1383 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1388 "bad assignment ({:?} = {:?}): {:?}",
1395 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1396 if let Err(terr) = self.relate_type_and_user_type(
1398 ty::Variance::Invariant,
1399 &UserTypeProjection { base: annotation_index, projs: vec![] },
1400 location.to_locations(),
1401 ConstraintCategory::Boring,
1403 let annotation = &self.user_type_annotations[annotation_index];
1407 "bad user type on rvalue ({:?} = {:?}): {:?}",
1415 self.check_rvalue(body, rv, location);
1416 if !self.unsized_feature_enabled() {
1417 let trait_ref = ty::TraitRef {
1418 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1419 substs: tcx.mk_substs_trait(place_ty, &[]),
1421 self.prove_trait_ref(
1423 location.to_locations(),
1424 ConstraintCategory::SizedBound,
1428 StatementKind::SetDiscriminant { ref place, variant_index } => {
1429 let place_type = place.ty(body, tcx).ty;
1430 let adt = match place_type.kind() {
1431 ty::Adt(adt, _) if adt.is_enum() => adt,
1434 stmt.source_info.span,
1435 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1441 if variant_index.as_usize() >= adt.variants.len() {
1443 stmt.source_info.span,
1444 "bad set discriminant ({:?} = {:?}): value of of range",
1450 StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1451 let place_ty = place.ty(body, tcx).ty;
1452 if let Err(terr) = self.relate_type_and_user_type(
1456 Locations::All(stmt.source_info.span),
1457 ConstraintCategory::TypeAnnotation,
1459 let annotation = &self.user_type_annotations[projection.base];
1463 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1471 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
1474 stmt.source_info.span,
1475 "Unexpected StatementKind::CopyNonOverlapping, should only appear after lowering_intrinsics",
1477 StatementKind::FakeRead(..)
1478 | StatementKind::StorageLive(..)
1479 | StatementKind::StorageDead(..)
1480 | StatementKind::LlvmInlineAsm { .. }
1481 | StatementKind::Retag { .. }
1482 | StatementKind::Coverage(..)
1483 | StatementKind::Nop => {}
1487 #[instrument(skip(self, body, term_location), level = "debug")]
1488 fn check_terminator(
1491 term: &Terminator<'tcx>,
1492 term_location: Location,
1494 let tcx = self.tcx();
1496 TerminatorKind::Goto { .. }
1497 | TerminatorKind::Resume
1498 | TerminatorKind::Abort
1499 | TerminatorKind::Return
1500 | TerminatorKind::GeneratorDrop
1501 | TerminatorKind::Unreachable
1502 | TerminatorKind::Drop { .. }
1503 | TerminatorKind::FalseEdge { .. }
1504 | TerminatorKind::FalseUnwind { .. }
1505 | TerminatorKind::InlineAsm { .. } => {
1506 // no checks needed for these
1509 TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1510 let place_ty = place.ty(body, tcx).ty;
1511 let rv_ty = value.ty(body, tcx);
1513 let locations = term_location.to_locations();
1515 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1520 "bad DropAndReplace ({:?} = {:?}): {:?}",
1527 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1528 self.check_operand(discr, term_location);
1530 let discr_ty = discr.ty(body, tcx);
1531 if let Err(terr) = self.sub_types(
1534 term_location.to_locations(),
1535 ConstraintCategory::Assignment,
1540 "bad SwitchInt ({:?} on {:?}): {:?}",
1546 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1547 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1549 // FIXME: check the values
1551 TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1552 self.check_operand(func, term_location);
1554 self.check_operand(arg, term_location);
1557 let func_ty = func.ty(body, tcx);
1558 debug!("check_terminator: call, func_ty={:?}", func_ty);
1559 let sig = match func_ty.kind() {
1560 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1562 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1566 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1567 term.source_info.span,
1568 LateBoundRegionConversionTime::FnCall,
1571 let sig = self.normalize(sig, term_location);
1572 self.check_call_dest(body, term, &sig, destination, term_location);
1574 self.prove_predicates(
1575 sig.inputs_and_output
1577 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1578 term_location.to_locations(),
1579 ConstraintCategory::Boring,
1582 // The ordinary liveness rules will ensure that all
1583 // regions in the type of the callee are live here. We
1584 // then further constrain the late-bound regions that
1585 // were instantiated at the call site to be live as
1586 // well. The resulting is that all the input (and
1587 // output) types in the signature must be live, since
1588 // all the inputs that fed into it were live.
1589 for &late_bound_region in map.values() {
1591 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1592 self.borrowck_context
1594 .liveness_constraints
1595 .add_element(region_vid, term_location);
1598 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1600 TerminatorKind::Assert { ref cond, ref msg, .. } => {
1601 self.check_operand(cond, term_location);
1603 let cond_ty = cond.ty(body, tcx);
1604 if cond_ty != tcx.types.bool {
1605 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1608 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1609 if len.ty(body, tcx) != tcx.types.usize {
1610 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1612 if index.ty(body, tcx) != tcx.types.usize {
1613 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1617 TerminatorKind::Yield { ref value, .. } => {
1618 self.check_operand(value, term_location);
1620 let value_ty = value.ty(body, tcx);
1621 match body.yield_ty() {
1622 None => span_mirbug!(self, term, "yield in non-generator"),
1624 if let Err(terr) = self.sub_types(
1627 term_location.to_locations(),
1628 ConstraintCategory::Yield,
1633 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1648 term: &Terminator<'tcx>,
1649 sig: &ty::FnSig<'tcx>,
1650 destination: &Option<(Place<'tcx>, BasicBlock)>,
1651 term_location: Location,
1653 let tcx = self.tcx();
1654 match *destination {
1655 Some((ref dest, _target_block)) => {
1656 let dest_ty = dest.ty(body, tcx).ty;
1657 let dest_ty = self.normalize(dest_ty, term_location);
1658 let category = match dest.as_local() {
1659 Some(RETURN_PLACE) => {
1660 if let BorrowCheckContext {
1664 DefiningTy::Const(def_id, _)
1665 | DefiningTy::InlineConst(def_id, _),
1669 } = self.borrowck_context
1671 if tcx.is_static(*def_id) {
1672 ConstraintCategory::UseAsStatic
1674 ConstraintCategory::UseAsConst
1677 ConstraintCategory::Return(ReturnConstraint::Normal)
1680 Some(l) if !body.local_decls[l].is_user_variable() => {
1681 ConstraintCategory::Boring
1683 _ => ConstraintCategory::Assignment,
1686 let locations = term_location.to_locations();
1688 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1692 "call dest mismatch ({:?} <- {:?}): {:?}",
1699 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1700 // this check is done at `check_local`.
1701 if self.unsized_feature_enabled() {
1702 let span = term.source_info.span;
1703 self.ensure_place_sized(dest_ty, span);
1709 .conservative_is_privately_uninhabited(self.param_env.and(sig.output()))
1711 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1717 fn check_call_inputs(
1720 term: &Terminator<'tcx>,
1721 sig: &ty::FnSig<'tcx>,
1722 args: &[Operand<'tcx>],
1723 term_location: Location,
1724 from_hir_call: bool,
1726 debug!("check_call_inputs({:?}, {:?})", sig, args);
1727 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1728 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1730 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1731 let op_arg_ty = op_arg.ty(body, self.tcx());
1732 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1733 let category = if from_hir_call {
1734 ConstraintCategory::CallArgument
1736 ConstraintCategory::Boring
1739 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1744 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1754 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1755 let is_cleanup = block_data.is_cleanup;
1756 self.last_span = block_data.terminator().source_info.span;
1757 match block_data.terminator().kind {
1758 TerminatorKind::Goto { target } => {
1759 self.assert_iscleanup(body, block_data, target, is_cleanup)
1761 TerminatorKind::SwitchInt { ref targets, .. } => {
1762 for target in targets.all_targets() {
1763 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1766 TerminatorKind::Resume => {
1768 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1771 TerminatorKind::Abort => {
1773 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1776 TerminatorKind::Return => {
1778 span_mirbug!(self, block_data, "return on cleanup block")
1781 TerminatorKind::GeneratorDrop { .. } => {
1783 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1786 TerminatorKind::Yield { resume, drop, .. } => {
1788 span_mirbug!(self, block_data, "yield in cleanup block")
1790 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1791 if let Some(drop) = drop {
1792 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1795 TerminatorKind::Unreachable => {}
1796 TerminatorKind::Drop { target, unwind, .. }
1797 | TerminatorKind::DropAndReplace { target, unwind, .. }
1798 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1799 self.assert_iscleanup(body, block_data, target, is_cleanup);
1800 if let Some(unwind) = unwind {
1802 span_mirbug!(self, block_data, "unwind on cleanup block")
1804 self.assert_iscleanup(body, block_data, unwind, true);
1807 TerminatorKind::Call { ref destination, cleanup, .. } => {
1808 if let &Some((_, target)) = destination {
1809 self.assert_iscleanup(body, block_data, target, is_cleanup);
1811 if let Some(cleanup) = cleanup {
1813 span_mirbug!(self, block_data, "cleanup on cleanup block")
1815 self.assert_iscleanup(body, block_data, cleanup, true);
1818 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1819 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1820 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1822 TerminatorKind::FalseUnwind { real_target, unwind } => {
1823 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1824 if let Some(unwind) = unwind {
1826 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1828 self.assert_iscleanup(body, block_data, unwind, true);
1831 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
1832 if let Some(target) = destination {
1833 self.assert_iscleanup(body, block_data, target, is_cleanup);
1835 if let Some(cleanup) = cleanup {
1837 span_mirbug!(self, block_data, "cleanup on cleanup block")
1839 self.assert_iscleanup(body, block_data, cleanup, true);
1845 fn assert_iscleanup(
1848 ctxt: &dyn fmt::Debug,
1852 if body[bb].is_cleanup != iscleanuppad {
1853 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1857 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1858 match body.local_kind(local) {
1859 LocalKind::ReturnPointer | LocalKind::Arg => {
1860 // return values of normal functions are required to be
1861 // sized by typeck, but return values of ADT constructors are
1862 // not because we don't include a `Self: Sized` bounds on them.
1864 // Unbound parts of arguments were never required to be Sized
1865 // - maybe we should make that a warning.
1868 LocalKind::Var | LocalKind::Temp => {}
1871 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1872 // and nullary ops are checked in `check_call_dest`.
1873 if !self.unsized_feature_enabled() {
1874 let span = local_decl.source_info.span;
1875 let ty = local_decl.ty;
1876 self.ensure_place_sized(ty, span);
1880 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1881 let tcx = self.tcx();
1883 // Erase the regions from `ty` to get a global type. The
1884 // `Sized` bound in no way depends on precise regions, so this
1885 // shouldn't affect `is_sized`.
1886 let erased_ty = tcx.erase_regions(ty);
1887 if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1888 // in current MIR construction, all non-control-flow rvalue
1889 // expressions evaluate through `as_temp` or `into` a return
1890 // slot or local, so to find all unsized rvalues it is enough
1891 // to check all temps, return slots and locals.
1892 if self.reported_errors.replace((ty, span)).is_none() {
1893 let mut diag = struct_span_err!(
1897 "cannot move a value of type {0}: the size of {0} \
1898 cannot be statically determined",
1902 // While this is located in `nll::typeck` this error is not
1903 // an NLL error, it's a required check to prevent creation
1904 // of unsized rvalues in a call expression.
1910 fn aggregate_field_ty(
1912 ak: &AggregateKind<'tcx>,
1915 ) -> Result<Ty<'tcx>, FieldAccessError> {
1916 let tcx = self.tcx();
1919 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1920 let variant = &def.variants[variant_index];
1921 let adj_field_index = active_field_index.unwrap_or(field_index);
1922 if let Some(field) = variant.fields.get(adj_field_index) {
1923 Ok(self.normalize(field.ty(tcx, substs), location))
1925 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1928 AggregateKind::Closure(_, substs) => {
1929 match substs.as_closure().upvar_tys().nth(field_index) {
1931 None => Err(FieldAccessError::OutOfRange {
1932 field_count: substs.as_closure().upvar_tys().count(),
1936 AggregateKind::Generator(_, substs, _) => {
1937 // It doesn't make sense to look at a field beyond the prefix;
1938 // these require a variant index, and are not initialized in
1939 // aggregate rvalues.
1940 match substs.as_generator().prefix_tys().nth(field_index) {
1942 None => Err(FieldAccessError::OutOfRange {
1943 field_count: substs.as_generator().prefix_tys().count(),
1947 AggregateKind::Array(ty) => Ok(ty),
1948 AggregateKind::Tuple => {
1949 unreachable!("This should have been covered in check_rvalues");
1954 fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1955 if let Operand::Constant(constant) = op {
1956 let maybe_uneval = match constant.literal {
1957 ConstantKind::Ty(ct) => match ct.val {
1958 ty::ConstKind::Unevaluated(uv) => Some(uv),
1963 if let Some(uv) = maybe_uneval {
1964 if uv.promoted.is_none() {
1965 let tcx = self.tcx();
1966 let def_id = uv.def.def_id_for_type_of();
1967 if tcx.def_kind(def_id) == DefKind::InlineConst {
1968 let predicates = self.prove_closure_bounds(
1970 def_id.expect_local(),
1974 self.normalize_and_prove_instantiated_predicates(
1977 location.to_locations(),
1985 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1986 let tcx = self.tcx();
1989 Rvalue::Aggregate(ak, ops) => {
1991 self.check_operand(op, location);
1993 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1996 Rvalue::Repeat(operand, len) => {
1997 self.check_operand(operand, location);
1999 // If the length cannot be evaluated we must assume that the length can be larger
2001 // If the length is larger than 1, the repeat expression will need to copy the
2002 // element, so we require the `Copy` trait.
2003 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
2005 Operand::Copy(..) | Operand::Constant(..) => {
2006 // These are always okay: direct use of a const, or a value that can evidently be copied.
2008 Operand::Move(place) => {
2009 // Make sure that repeated elements implement `Copy`.
2010 let span = body.source_info(location).span;
2011 let ty = operand.ty(body, tcx);
2012 if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
2013 let ccx = ConstCx::new_with_param_env(tcx, body, self.param_env);
2015 is_const_fn_in_array_repeat_expression(&ccx, &place, &body);
2017 debug!("check_rvalue: is_const_fn={:?}", is_const_fn);
2019 let def_id = body.source.def_id().expect_local();
2020 let obligation = traits::Obligation::new(
2021 ObligationCause::new(
2023 self.tcx().hir().local_def_id_to_hir_id(def_id),
2024 traits::ObligationCauseCode::RepeatVec(is_const_fn),
2027 ty::Binder::dummy(ty::TraitRef::new(
2028 self.tcx().require_lang_item(
2030 Some(self.last_span),
2032 tcx.mk_substs_trait(ty, &[]),
2035 .to_predicate(self.tcx()),
2037 self.infcx.report_selection_error(
2040 &traits::SelectionError::Unimplemented,
2049 Rvalue::NullaryOp(_, ty) => {
2050 let trait_ref = ty::TraitRef {
2051 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
2052 substs: tcx.mk_substs_trait(ty, &[]),
2055 self.prove_trait_ref(
2057 location.to_locations(),
2058 ConstraintCategory::SizedBound,
2062 Rvalue::ShallowInitBox(operand, ty) => {
2063 self.check_operand(operand, location);
2065 let trait_ref = ty::TraitRef {
2066 def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
2067 substs: tcx.mk_substs_trait(ty, &[]),
2070 self.prove_trait_ref(
2072 location.to_locations(),
2073 ConstraintCategory::SizedBound,
2077 Rvalue::Cast(cast_kind, op, ty) => {
2078 self.check_operand(op, location);
2081 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2082 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2084 // The type that we see in the fcx is like
2085 // `foo::<'a, 'b>`, where `foo` is the path to a
2086 // function definition. When we extract the
2087 // signature, it comes from the `fn_sig` query,
2088 // and hence may contain unnormalized results.
2089 let fn_sig = self.normalize(fn_sig, location);
2091 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2093 if let Err(terr) = self.eq_types(
2096 location.to_locations(),
2097 ConstraintCategory::Cast,
2102 "equating {:?} with {:?} yields {:?}",
2110 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2111 let sig = match op.ty(body, tcx).kind() {
2112 ty::Closure(_, substs) => substs.as_closure().sig(),
2115 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
2117 if let Err(terr) = self.eq_types(
2120 location.to_locations(),
2121 ConstraintCategory::Cast,
2126 "equating {:?} with {:?} yields {:?}",
2134 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2135 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2137 // The type that we see in the fcx is like
2138 // `foo::<'a, 'b>`, where `foo` is the path to a
2139 // function definition. When we extract the
2140 // signature, it comes from the `fn_sig` query,
2141 // and hence may contain unnormalized results.
2142 let fn_sig = self.normalize(fn_sig, location);
2144 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2146 if let Err(terr) = self.eq_types(
2149 location.to_locations(),
2150 ConstraintCategory::Cast,
2155 "equating {:?} with {:?} yields {:?}",
2163 CastKind::Pointer(PointerCast::Unsize) => {
2165 let trait_ref = ty::TraitRef {
2167 .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2168 substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2171 self.prove_trait_ref(
2173 location.to_locations(),
2174 ConstraintCategory::Cast,
2178 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2179 let ty_from = match op.ty(body, tcx).kind() {
2180 ty::RawPtr(ty::TypeAndMut {
2182 mutbl: hir::Mutability::Mut,
2188 "unexpected base type for cast {:?}",
2194 let ty_to = match ty.kind() {
2195 ty::RawPtr(ty::TypeAndMut {
2197 mutbl: hir::Mutability::Not,
2203 "unexpected target type for cast {:?}",
2209 if let Err(terr) = self.sub_types(
2212 location.to_locations(),
2213 ConstraintCategory::Cast,
2218 "relating {:?} with {:?} yields {:?}",
2226 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2227 let ty_from = op.ty(body, tcx);
2229 let opt_ty_elem_mut = match ty_from.kind() {
2230 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2231 match array_ty.kind() {
2232 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2239 let (ty_elem, ty_mut) = match opt_ty_elem_mut {
2240 Some(ty_elem_mut) => ty_elem_mut,
2245 "ArrayToPointer cast from unexpected type {:?}",
2252 let (ty_to, ty_to_mut) = match ty.kind() {
2253 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2260 "ArrayToPointer cast to unexpected type {:?}",
2267 if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2271 "ArrayToPointer cast from const {:?} to mut {:?}",
2278 if let Err(terr) = self.sub_types(
2281 location.to_locations(),
2282 ConstraintCategory::Cast,
2287 "relating {:?} with {:?} yields {:?}",
2296 let ty_from = op.ty(body, tcx);
2297 let cast_ty_from = CastTy::from_ty(ty_from);
2298 let cast_ty_to = CastTy::from_ty(ty);
2299 match (cast_ty_from, cast_ty_to) {
2301 | (_, None | Some(CastTy::FnPtr))
2302 | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2303 | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => {
2304 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2307 Some(CastTy::Int(_)),
2308 Some(CastTy::Int(_) | CastTy::Float | CastTy::Ptr(_)),
2310 | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float))
2311 | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_)))
2312 | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (),
2318 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2319 self.add_reborrow_constraint(&body, location, region, borrowed_place);
2323 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2326 self.check_operand(left, location);
2327 self.check_operand(right, location);
2329 let ty_left = left.ty(body, tcx);
2330 match ty_left.kind() {
2331 // Types with regions are comparable if they have a common super-type.
2332 ty::RawPtr(_) | ty::FnPtr(_) => {
2333 let ty_right = right.ty(body, tcx);
2334 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2335 kind: TypeVariableOriginKind::MiscVariable,
2336 span: body.source_info(location).span,
2341 location.to_locations(),
2342 ConstraintCategory::Boring,
2344 .unwrap_or_else(|err| {
2345 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2347 if let Err(terr) = self.sub_types(
2350 location.to_locations(),
2351 ConstraintCategory::Boring,
2356 "unexpected comparison types {:?} and {:?} yields {:?}",
2363 // For types with no regions we can just check that the
2364 // both operands have the same type.
2365 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2366 if ty_left == right.ty(body, tcx) => {}
2367 // Other types are compared by trait methods, not by
2368 // `Rvalue::BinaryOp`.
2372 "unexpected comparison types {:?} and {:?}",
2379 Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => {
2380 self.check_operand(operand, location);
2383 Rvalue::BinaryOp(_, box (left, right))
2384 | Rvalue::CheckedBinaryOp(_, box (left, right)) => {
2385 self.check_operand(left, location);
2386 self.check_operand(right, location);
2389 Rvalue::AddressOf(..)
2390 | Rvalue::ThreadLocalRef(..)
2392 | Rvalue::Discriminant(..) => {}
2396 /// If this rvalue supports a user-given type annotation, then
2397 /// extract and return it. This represents the final type of the
2398 /// rvalue and will be unified with the inferred type.
2399 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2402 | Rvalue::ThreadLocalRef(_)
2403 | Rvalue::Repeat(..)
2405 | Rvalue::AddressOf(..)
2408 | Rvalue::ShallowInitBox(..)
2409 | Rvalue::BinaryOp(..)
2410 | Rvalue::CheckedBinaryOp(..)
2411 | Rvalue::NullaryOp(..)
2412 | Rvalue::UnaryOp(..)
2413 | Rvalue::Discriminant(..) => None,
2415 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2416 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2417 AggregateKind::Array(_) => None,
2418 AggregateKind::Tuple => None,
2419 AggregateKind::Closure(_, _) => None,
2420 AggregateKind::Generator(_, _, _) => None,
2425 fn check_aggregate_rvalue(
2428 rvalue: &Rvalue<'tcx>,
2429 aggregate_kind: &AggregateKind<'tcx>,
2430 operands: &[Operand<'tcx>],
2433 let tcx = self.tcx();
2435 self.prove_aggregate_predicates(aggregate_kind, location);
2437 if *aggregate_kind == AggregateKind::Tuple {
2438 // tuple rvalue field type is always the type of the op. Nothing to check here.
2442 for (i, operand) in operands.iter().enumerate() {
2443 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2444 Ok(field_ty) => field_ty,
2445 Err(FieldAccessError::OutOfRange { field_count }) => {
2449 "accessed field #{} but variant only has {}",
2456 let operand_ty = operand.ty(body, tcx);
2457 let operand_ty = self.normalize(operand_ty, location);
2459 if let Err(terr) = self.sub_types(
2462 location.to_locations(),
2463 ConstraintCategory::Boring,
2468 "{:?} is not a subtype of {:?}: {:?}",
2477 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2481 /// - `location`: the location `L` where the borrow expression occurs
2482 /// - `borrow_region`: the region `'a` associated with the borrow
2483 /// - `borrowed_place`: the place `P` being borrowed
2484 fn add_reborrow_constraint(
2488 borrow_region: ty::Region<'tcx>,
2489 borrowed_place: &Place<'tcx>,
2491 // These constraints are only meaningful during borrowck:
2492 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2493 self.borrowck_context;
2495 // In Polonius mode, we also push a `loan_issued_at` fact
2496 // linking the loan to the region (in some cases, though,
2497 // there is no loan associated with this borrow expression --
2498 // that occurs when we are borrowing an unsafe place, for
2500 if let Some(all_facts) = all_facts {
2501 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2502 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2503 let region_vid = borrow_region.to_region_vid();
2504 all_facts.loan_issued_at.push((
2507 location_table.mid_index(location),
2512 // If we are reborrowing the referent of another reference, we
2513 // need to add outlives relationships. In a case like `&mut
2514 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2515 // need to ensure that `'b: 'a`.
2518 "add_reborrow_constraint({:?}, {:?}, {:?})",
2519 location, borrow_region, borrowed_place
2522 let mut cursor = borrowed_place.projection.as_ref();
2523 let tcx = self.infcx.tcx;
2524 let field = path_utils::is_upvar_field_projection(
2526 &self.borrowck_context.upvars,
2527 borrowed_place.as_ref(),
2530 let category = if let Some(field) = field {
2531 let var_hir_id = self.borrowck_context.upvars[field.index()].place.get_root_variable();
2532 // FIXME(project-rfc-2229#8): Use Place for better diagnostics
2533 ConstraintCategory::ClosureUpvar(var_hir_id)
2535 ConstraintCategory::Boring
2538 while let [proj_base @ .., elem] = cursor {
2541 debug!("add_reborrow_constraint - iteration {:?}", elem);
2544 ProjectionElem::Deref => {
2545 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2547 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2548 match base_ty.kind() {
2549 ty::Ref(ref_region, _, mutbl) => {
2550 constraints.outlives_constraints.push(OutlivesConstraint {
2551 sup: ref_region.to_region_vid(),
2552 sub: borrow_region.to_region_vid(),
2553 locations: location.to_locations(),
2555 variance_info: ty::VarianceDiagInfo::default(),
2559 hir::Mutability::Not => {
2560 // Immutable reference. We don't need the base
2561 // to be valid for the entire lifetime of
2565 hir::Mutability::Mut => {
2566 // Mutable reference. We *do* need the base
2567 // to be valid, because after the base becomes
2568 // invalid, someone else can use our mutable deref.
2570 // This is in order to make the following function
2573 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2578 // As otherwise you could clone `&mut T` using the
2579 // following function:
2581 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2582 // let my_clone = unsafe_deref(&'a x);
2591 // deref of raw pointer, guaranteed to be valid
2594 ty::Adt(def, _) if def.is_box() => {
2595 // deref of `Box`, need the base to be valid - propagate
2597 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2600 ProjectionElem::Field(..)
2601 | ProjectionElem::Downcast(..)
2602 | ProjectionElem::Index(..)
2603 | ProjectionElem::ConstantIndex { .. }
2604 | ProjectionElem::Subslice { .. } => {
2605 // other field access
2611 fn prove_aggregate_predicates(
2613 aggregate_kind: &AggregateKind<'tcx>,
2616 let tcx = self.tcx();
2619 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2620 aggregate_kind, location
2623 let (def_id, instantiated_predicates) = match aggregate_kind {
2624 AggregateKind::Adt(def, _, substs, _, _) => {
2625 (def.did, tcx.predicates_of(def.did).instantiate(tcx, substs))
2628 // For closures, we have some **extra requirements** we
2630 // have to check. In particular, in their upvars and
2631 // signatures, closures often reference various regions
2632 // from the surrounding function -- we call those the
2633 // closure's free regions. When we borrow-check (and hence
2634 // region-check) closures, we may find that the closure
2635 // requires certain relationships between those free
2636 // regions. However, because those free regions refer to
2637 // portions of the CFG of their caller, the closure is not
2638 // in a position to verify those relationships. In that
2639 // case, the requirements get "propagated" to us, and so
2640 // we have to solve them here where we instantiate the
2643 // Despite the opacity of the previous parapgrah, this is
2644 // actually relatively easy to understand in terms of the
2645 // desugaring. A closure gets desugared to a struct, and
2646 // these extra requirements are basically like where
2647 // clauses on the struct.
2648 AggregateKind::Closure(def_id, substs)
2649 | AggregateKind::Generator(def_id, substs, _) => {
2650 (*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location))
2653 AggregateKind::Array(_) | AggregateKind::Tuple => {
2654 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2658 self.normalize_and_prove_instantiated_predicates(
2660 instantiated_predicates,
2661 location.to_locations(),
2665 fn prove_closure_bounds(
2669 substs: SubstsRef<'tcx>,
2671 ) -> ty::InstantiatedPredicates<'tcx> {
2672 if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2674 let closure_constraints = QueryRegionConstraints {
2675 outlives: closure_region_requirements.apply_requirements(
2681 // Presently, closures never propagate member
2682 // constraints to their parents -- they are enforced
2683 // locally. This is largely a non-issue as member
2684 // constraints only come from `-> impl Trait` and
2685 // friends which don't appear (thus far...) in
2687 member_constraints: vec![],
2690 let bounds_mapping = closure_constraints
2694 .filter_map(|(idx, constraint)| {
2695 let ty::OutlivesPredicate(k1, r2) =
2696 constraint.no_bound_vars().unwrap_or_else(|| {
2697 bug!("query_constraint {:?} contained bound vars", constraint,);
2701 GenericArgKind::Lifetime(r1) => {
2702 // constraint is r1: r2
2703 let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2704 let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2705 let outlives_requirements =
2706 &closure_region_requirements.outlives_requirements[idx];
2709 (outlives_requirements.category, outlives_requirements.blame_span),
2712 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2720 .closure_bounds_mapping
2721 .insert(location, bounds_mapping);
2722 assert!(existing.is_none(), "Multiple closures at the same location.");
2724 self.push_region_constraints(
2725 location.to_locations(),
2726 ConstraintCategory::ClosureBounds,
2727 &closure_constraints,
2731 tcx.predicates_of(def_id).instantiate(tcx, substs)
2734 #[instrument(skip(self, body), level = "debug")]
2735 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2736 self.last_span = body.span;
2739 for (local, local_decl) in body.local_decls.iter_enumerated() {
2740 self.check_local(&body, local, local_decl);
2743 for (block, block_data) in body.basic_blocks().iter_enumerated() {
2744 let mut location = Location { block, statement_index: 0 };
2745 for stmt in &block_data.statements {
2746 if !stmt.source_info.span.is_dummy() {
2747 self.last_span = stmt.source_info.span;
2749 self.check_stmt(body, stmt, location);
2750 location.statement_index += 1;
2753 self.check_terminator(&body, block_data.terminator(), location);
2754 self.check_iscleanup(&body, block_data);
2759 trait NormalizeLocation: fmt::Debug + Copy {
2760 fn to_locations(self) -> Locations;
2763 impl NormalizeLocation for Locations {
2764 fn to_locations(self) -> Locations {
2769 impl NormalizeLocation for Location {
2770 fn to_locations(self) -> Locations {
2771 Locations::Single(self)
2775 #[derive(Debug, Default)]
2776 struct ObligationAccumulator<'tcx> {
2777 obligations: PredicateObligations<'tcx>,
2780 impl<'tcx> ObligationAccumulator<'tcx> {
2781 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2782 let InferOk { value, obligations } = value;
2783 self.obligations.extend(obligations);
2787 fn into_vec(self) -> PredicateObligations<'tcx> {