1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This pass type-checks the MIR to ensure it is not broken.
13 #![allow(unreachable_code)]
15 use borrow_check::borrow_set::BorrowSet;
16 use borrow_check::location::LocationTable;
17 use borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
18 use borrow_check::nll::facts::AllFacts;
19 use borrow_check::nll::region_infer::values::LivenessValues;
20 use borrow_check::nll::region_infer::values::PlaceholderIndex;
21 use borrow_check::nll::region_infer::values::PlaceholderIndices;
22 use borrow_check::nll::region_infer::values::RegionValueElements;
23 use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
24 use borrow_check::nll::renumber;
25 use borrow_check::nll::type_check::free_region_relations::{
26 CreateResult, UniversalRegionRelations,
28 use borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
29 use borrow_check::nll::ToRegionVid;
30 use dataflow::move_paths::MoveData;
31 use dataflow::FlowAtLocation;
32 use dataflow::MaybeInitializedPlaces;
35 use rustc::hir::def_id::DefId;
36 use rustc::infer::canonical::QueryRegionConstraint;
37 use rustc::infer::outlives::env::RegionBoundPairs;
38 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
39 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
40 use rustc::mir::tcx::PlaceTy;
41 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
43 use rustc::traits::query::type_op;
44 use rustc::traits::query::type_op::custom::CustomTypeOp;
45 use rustc::traits::query::{Fallible, NoSolution};
46 use rustc::traits::{ObligationCause, PredicateObligations};
47 use rustc::ty::fold::TypeFoldable;
48 use rustc::ty::subst::{Subst, Substs, UnpackedKind};
49 use rustc::ty::{self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TyKind};
50 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
51 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
52 use rustc::ty::layout::VariantIdx;
55 use syntax_pos::{Span, DUMMY_SP};
56 use transform::{MirPass, MirSource};
58 macro_rules! span_mirbug {
59 ($context:expr, $elem:expr, $($message:tt)*) => ({
60 $crate::borrow_check::nll::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<'gcx, 'tcx>(
118 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
119 param_env: ty::ParamEnv<'gcx>,
122 universal_regions: &Rc<UniversalRegions<'tcx>>,
123 location_table: &LocationTable,
124 borrow_set: &BorrowSet<'tcx>,
125 all_facts: &mut Option<AllFacts>,
126 flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
127 move_data: &MoveData<'tcx>,
128 elements: &Rc<RegionValueElements>,
129 ) -> MirTypeckResults<'tcx> {
130 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
131 let mut constraints = MirTypeckRegionConstraints {
132 placeholder_indices: PlaceholderIndices::default(),
133 placeholder_index_to_region: IndexVec::default(),
134 liveness_constraints: LivenessValues::new(elements),
135 outlives_constraints: ConstraintSet::default(),
136 closure_bounds_mapping: Default::default(),
137 type_tests: Vec::default(),
141 universal_region_relations,
143 normalized_inputs_and_output,
144 } = free_region_relations::create(
147 Some(implicit_region_bound),
152 let mut borrowck_context = BorrowCheckContext {
157 constraints: &mut constraints,
166 Some(implicit_region_bound),
167 Some(&mut borrowck_context),
168 Some(&universal_region_relations),
170 cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
171 liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
175 .map(|bcx| translate_outlives_facts(bcx));
181 universal_region_relations,
185 fn type_check_internal<'a, 'gcx, 'tcx, R>(
186 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
188 param_env: ty::ParamEnv<'gcx>,
190 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
191 implicit_region_bound: Option<ty::Region<'tcx>>,
192 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
193 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
194 mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
196 let mut checker = TypeChecker::new(
202 implicit_region_bound,
204 universal_region_relations,
206 let errors_reported = {
207 let mut verifier = TypeVerifier::new(&mut checker, mir);
208 verifier.visit_mir(mir);
209 verifier.errors_reported
212 if !errors_reported {
213 // if verifier failed, don't do further checks to avoid ICEs
214 checker.typeck_mir(mir);
220 fn translate_outlives_facts(cx: &mut BorrowCheckContext) {
221 if let Some(facts) = cx.all_facts {
222 let location_table = cx.location_table;
225 .extend(cx.constraints.outlives_constraints.iter().flat_map(
226 |constraint: &OutlivesConstraint| {
227 if let Some(from_location) = constraint.locations.from_location() {
228 Either::Left(iter::once((
231 location_table.mid_index(from_location),
237 .map(move |location| (constraint.sup, constraint.sub, location)),
245 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
246 // We sometimes see MIR failures (notably predicate failures) due to
247 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
248 // to avoid reporting bugs in those cases.
249 tcx.sess.diagnostic().delay_span_bug(span, msg);
252 enum FieldAccessError {
253 OutOfRange { field_count: usize },
256 /// Verifies that MIR types are sane to not crash further checks.
258 /// The sanitize_XYZ methods here take an MIR object and compute its
259 /// type, calling `span_mirbug` and returning an error type if there
261 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
262 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
266 errors_reported: bool,
269 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, '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 self.sanitize_constant(constant, location);
283 self.sanitize_type(constant, constant.ty);
285 if let Some(user_ty) = constant.user_ty {
286 if let Err(terr) = self.cx.relate_type_and_user_type(
288 ty::Variance::Invariant,
289 &UserTypeProjection { base: user_ty, projs: vec![], },
290 location.to_locations(),
291 ConstraintCategory::Boring,
296 "bad constant user type {:?} vs {:?}: {:?}",
305 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
306 self.super_rvalue(rvalue, location);
307 let rval_ty = rvalue.ty(self.mir, self.tcx());
308 self.sanitize_type(rvalue, rval_ty);
311 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
312 self.super_local_decl(local, local_decl);
313 self.sanitize_type(local_decl, local_decl.ty);
315 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
316 if let Err(terr) = self.cx.relate_type_and_user_type(
318 ty::Variance::Invariant,
320 Locations::All(*span),
321 ConstraintCategory::TypeAnnotation,
326 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
336 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
337 self.sanitize_type(&"return type", mir.return_ty());
338 for local_decl in &mir.local_decls {
339 self.sanitize_type(local_decl, local_decl.ty);
341 if self.errors_reported {
348 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
349 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
352 mir_def_id: cx.mir_def_id,
355 errors_reported: false,
359 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
363 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
364 if ty.has_escaping_bound_vars() || ty.references_error() {
365 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
371 /// Checks that the constant's `ty` field matches up with what
372 /// would be expected from its literal.
373 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
375 "sanitize_constant(constant={:?}, location={:?})",
379 // FIXME(#46702) -- We need some way to get the predicates
380 // associated with the "pre-evaluated" form of the
381 // constant. For example, consider that the constant
382 // may have associated constant projections (`<Foo as
383 // Trait<'a, 'b>>::SOME_CONST`) that impose
384 // constraints on `'a` and `'b`. These constraints
385 // would be lost if we just look at the normalized
387 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
388 let tcx = self.tcx();
389 let type_checker = &mut self.cx;
391 // FIXME -- For now, use the substitutions from
392 // `value.ty` rather than `value.val`. The
393 // renumberer will rewrite them to independent
394 // sets of regions; in principle, we ought to
395 // derive the type of the `value.val` from "first
396 // principles" and equate with value.ty, but as we
397 // are transitioning to the miri-based system, we
398 // don't have a handy function for that, so for
399 // now we just ignore `value.val` regions.
401 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
402 type_checker.normalize_and_prove_instantiated_predicates(
403 instantiated_predicates,
404 location.to_locations(),
408 debug!("sanitize_constant: expected_ty={:?}", constant.literal.ty);
410 if let Err(terr) = self.cx.eq_types(
413 location.to_locations(),
414 ConstraintCategory::Boring,
419 "constant {:?} should have type {:?} but has {:?} ({:?})",
428 /// Checks that the types internal to the `place` match up with
429 /// what would be expected.
434 context: PlaceContext,
436 debug!("sanitize_place: {:?}", place);
437 let place_ty = match *place {
438 Place::Local(index) => PlaceTy::Ty {
439 ty: self.mir.local_decls[index].ty,
441 Place::Promoted(box (_index, sty)) => {
442 let sty = self.sanitize_type(place, sty);
443 // FIXME -- promoted MIR return types reference
444 // various "free regions" (e.g., scopes and things)
445 // that they ought not to do. We have to figure out
446 // how best to handle that -- probably we want treat
447 // promoted MIR much like closures, renumbering all
448 // their free regions and propagating constraints
449 // upwards. We have the same acyclic guarantees, so
450 // that should be possible. But for now, ignore them.
452 // let promoted_mir = &self.mir.promoted[index];
453 // promoted_mir.return_ty()
454 PlaceTy::Ty { ty: sty }
456 Place::Static(box Static { def_id, ty: sty }) => {
457 let sty = self.sanitize_type(place, sty);
458 let ty = self.tcx().type_of(def_id);
459 let ty = self.cx.normalize(ty, location);
462 .eq_types(ty, sty, location.to_locations(), ConstraintCategory::Boring)
467 "bad static type ({:?}: {:?}): {:?}",
473 PlaceTy::Ty { ty: sty }
475 Place::Projection(ref proj) => {
476 let base_context = if context.is_mutating_use() {
477 PlaceContext::MutatingUse(MutatingUseContext::Projection)
479 PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
481 let base_ty = self.sanitize_place(&proj.base, location, base_context);
482 if let PlaceTy::Ty { ty } = base_ty {
483 if ty.references_error() {
484 assert!(self.errors_reported);
486 ty: self.tcx().types.err,
490 self.sanitize_projection(base_ty, &proj.elem, place, location)
493 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
494 let tcx = self.tcx();
495 let trait_ref = ty::TraitRef {
496 def_id: tcx.lang_items().copy_trait().unwrap(),
497 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
500 // In order to have a Copy operand, the type T of the value must be Copy. Note that we
501 // prove that T: Copy, rather than using the type_moves_by_default test. This is
502 // important because type_moves_by_default ignores the resulting region obligations and
503 // assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
504 // (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
505 // fully apply: in effect, the rule is that if a value of some type could implement
506 // Copy, then it must.
507 self.cx.prove_trait_ref(
509 location.to_locations(),
510 ConstraintCategory::CopyBound,
516 fn sanitize_projection(
519 pi: &PlaceElem<'tcx>,
523 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
524 let tcx = self.tcx();
525 let base_ty = base.to_ty(tcx);
527 ProjectionElem::Deref => {
528 let deref_ty = base_ty.builtin_deref(true);
530 ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
531 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
535 ProjectionElem::Index(i) => {
536 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
537 if index_ty != tcx.types.usize {
539 ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
543 ty: base_ty.builtin_index().unwrap_or_else(|| {
544 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
549 ProjectionElem::ConstantIndex { .. } => {
550 // consider verifying in-bounds
552 ty: base_ty.builtin_index().unwrap_or_else(|| {
553 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
557 ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
558 ty: match base_ty.sty {
559 ty::Array(inner, size) => {
560 let size = size.unwrap_usize(tcx);
561 let min_size = (from as u64) + (to as u64);
562 if let Some(rest_size) = size.checked_sub(min_size) {
563 tcx.mk_array(inner, rest_size)
565 span_mirbug_and_err!(
568 "taking too-small slice of {:?}",
573 ty::Slice(..) => base_ty,
574 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
577 ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
578 ty::Adt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
579 if index.as_usize() >= adt_def.variants.len() {
581 ty: span_mirbug_and_err!(
584 "cast to variant #{:?} but enum only has {:?}",
586 adt_def.variants.len()
593 variant_index: index,
598 ty: span_mirbug_and_err!(
601 "can't downcast {:?} as {:?}",
607 ProjectionElem::Field(field, fty) => {
608 let fty = self.sanitize_type(place, fty);
609 match self.field_ty(place, base, field, location) {
610 Ok(ty) => if let Err(terr) = self.cx.eq_types(
613 location.to_locations(),
614 ConstraintCategory::Boring,
619 "bad field access ({:?}: {:?}): {:?}",
625 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
628 "accessed field #{} but variant only has {}",
633 PlaceTy::Ty { ty: fty }
638 fn error(&mut self) -> Ty<'tcx> {
639 self.errors_reported = true;
645 parent: &dyn fmt::Debug,
646 base_ty: PlaceTy<'tcx>,
649 ) -> Result<Ty<'tcx>, FieldAccessError> {
650 let tcx = self.tcx();
652 let (variant, substs) = match base_ty {
657 } => (&adt_def.variants[variant_index], substs),
658 PlaceTy::Ty { ty } => match ty.sty {
659 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
660 (&adt_def.variants[VariantIdx::new(0)], substs),
661 ty::Closure(def_id, substs) => {
662 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
664 None => Err(FieldAccessError::OutOfRange {
665 field_count: substs.upvar_tys(def_id, tcx).count(),
669 ty::Generator(def_id, substs, _) => {
670 // Try pre-transform fields first (upvars and current state)
671 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
675 // Then try `field_tys` which contains all the fields, but it
676 // requires the final optimized MIR.
677 return match substs.field_tys(def_id, tcx).nth(field.index()) {
679 None => Err(FieldAccessError::OutOfRange {
680 field_count: substs.field_tys(def_id, tcx).count(),
685 return match tys.get(field.index()) {
687 None => Err(FieldAccessError::OutOfRange {
688 field_count: tys.len(),
693 return Ok(span_mirbug_and_err!(
696 "can't project out of {:?}",
703 if let Some(field) = variant.fields.get(field.index()) {
704 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
706 Err(FieldAccessError::OutOfRange {
707 field_count: variant.fields.len(),
713 /// The MIR type checker. Visits the MIR and enforces all the
714 /// constraints needed for it to be valid and well-typed. Along the
715 /// way, it accrues region constraints -- these can later be used by
716 /// NLL region checking.
717 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
718 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
719 param_env: ty::ParamEnv<'gcx>,
723 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
724 implicit_region_bound: Option<ty::Region<'tcx>>,
725 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
726 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
727 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
730 struct BorrowCheckContext<'a, 'tcx: 'a> {
731 universal_regions: &'a UniversalRegions<'tcx>,
732 location_table: &'a LocationTable,
733 all_facts: &'a mut Option<AllFacts>,
734 borrow_set: &'a BorrowSet<'tcx>,
735 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
738 crate struct MirTypeckResults<'tcx> {
739 crate constraints: MirTypeckRegionConstraints<'tcx>,
740 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
743 /// A collection of region constraints that must be satisfied for the
744 /// program to be considered well-typed.
745 crate struct MirTypeckRegionConstraints<'tcx> {
746 /// Maps from a `ty::Placeholder` to the corresponding
747 /// `PlaceholderIndex` bit that we will use for it.
749 /// To keep everything in sync, do not insert this set
750 /// directly. Instead, use the `placeholder_region` helper.
751 crate placeholder_indices: PlaceholderIndices,
753 /// Each time we add a placeholder to `placeholder_indices`, we
754 /// also create a corresponding "representative" region vid for
755 /// that wraps it. This vector tracks those. This way, when we
756 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
757 /// the same underlying `RegionVid`.
758 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
760 /// In general, the type-checker is not responsible for enforcing
761 /// liveness constraints; this job falls to the region inferencer,
762 /// which performs a liveness analysis. However, in some limited
763 /// cases, the MIR type-checker creates temporary regions that do
764 /// not otherwise appear in the MIR -- in particular, the
765 /// late-bound regions that it instantiates at call-sites -- and
766 /// hence it must report on their liveness constraints.
767 crate liveness_constraints: LivenessValues<RegionVid>,
769 crate outlives_constraints: ConstraintSet,
771 crate closure_bounds_mapping:
772 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
774 crate type_tests: Vec<TypeTest<'tcx>>,
777 impl MirTypeckRegionConstraints<'tcx> {
778 fn placeholder_region(
780 infcx: &InferCtxt<'_, '_, 'tcx>,
781 placeholder: ty::PlaceholderRegion,
782 ) -> ty::Region<'tcx> {
783 let placeholder_index = self.placeholder_indices.insert(placeholder);
784 match self.placeholder_index_to_region.get(placeholder_index) {
787 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
788 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
789 self.placeholder_index_to_region.push(region);
796 /// The `Locations` type summarizes *where* region constraints are
797 /// required to hold. Normally, this is at a particular point which
798 /// created the obligation, but for constraints that the user gave, we
799 /// want the constraint to hold at all points.
800 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
802 /// Indicates that a type constraint should always be true. This
803 /// is particularly important in the new borrowck analysis for
804 /// things like the type of the return slot. Consider this
808 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
810 /// return &y; // error
814 /// Here, we wind up with the signature from the return type being
815 /// something like `&'1 u32` where `'1` is a universal region. But
816 /// the type of the return slot `_0` is something like `&'2 u32`
817 /// where `'2` is an existential region variable. The type checker
818 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
819 /// older NLL analysis, we required this only at the entry point
820 /// to the function. By the nature of the constraints, this wound
821 /// up propagating to all points reachable from start (because
822 /// `'1` -- as a universal region -- is live everywhere). In the
823 /// newer analysis, though, this doesn't work: `_0` is considered
824 /// dead at the start (it has no usable value) and hence this type
825 /// equality is basically a no-op. Then, later on, when we do `_0
826 /// = &'3 y`, that region `'3` never winds up related to the
827 /// universal region `'1` and hence no error occurs. Therefore, we
828 /// use Locations::All instead, which ensures that the `'1` and
829 /// `'2` are equal everything. We also use this for other
830 /// user-given type annotations; e.g., if the user wrote `let mut
831 /// x: &'static u32 = ...`, we would ensure that all values
832 /// assigned to `x` are of `'static` lifetime.
834 /// The span points to the place the constraint arose. For example,
835 /// it points to the type in a user-given type annotation. If
836 /// there's no sensible span then it's DUMMY_SP.
839 /// An outlives constraint that only has to hold at a single location,
840 /// usually it represents a point where references flow from one spot to
841 /// another (e.g., `x = y`)
846 pub fn from_location(&self) -> Option<Location> {
848 Locations::All(_) => None,
849 Locations::Single(from_location) => Some(*from_location),
853 /// Gets a span representing the location.
854 pub fn span(&self, mir: &Mir<'_>) -> Span {
856 Locations::All(span) => *span,
857 Locations::Single(l) => mir.source_info(*l).span,
862 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
864 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
867 param_env: ty::ParamEnv<'gcx>,
868 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
869 implicit_region_bound: Option<ty::Region<'tcx>>,
870 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
871 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
880 implicit_region_bound,
882 reported_errors: Default::default(),
883 universal_region_relations,
887 /// Given some operation `op` that manipulates types, proves
888 /// predicates, or otherwise uses the inference context, executes
889 /// `op` and then executes all the further obligations that `op`
890 /// returns. This will yield a set of outlives constraints amongst
891 /// regions which are extracted and stored as having occurred at
894 /// **Any `rustc::infer` operations that might generate region
895 /// constraints should occur within this method so that those
896 /// constraints can be properly localized!**
897 fn fully_perform_op<R>(
899 locations: Locations,
900 category: ConstraintCategory,
901 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
903 let (r, opt_data) = op.fully_perform(self.infcx)?;
905 if let Some(data) = &opt_data {
906 self.push_region_constraints(locations, category, data);
912 fn push_region_constraints(
914 locations: Locations,
915 category: ConstraintCategory,
916 data: &[QueryRegionConstraint<'tcx>],
919 "push_region_constraints: constraints generated at {:?} are {:#?}",
923 if let Some(ref mut borrowck_context) = self.borrowck_context {
924 constraint_conversion::ConstraintConversion::new(
926 borrowck_context.universal_regions,
927 self.region_bound_pairs,
928 self.implicit_region_bound,
932 &mut borrowck_context.constraints,
933 ).convert_all(&data);
937 /// Convenient wrapper around `relate_tys::relate_types` -- see
938 /// that fn for docs.
944 locations: Locations,
945 category: ConstraintCategory,
947 relate_tys::relate_types(
954 self.borrowck_context.as_mut().map(|x| &mut **x),
962 locations: Locations,
963 category: ConstraintCategory,
965 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
968 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
969 /// variables in `sub` with their inferred definitions and try
970 /// again. This is used for opaque types in places (e.g., `let x:
972 fn sub_types_or_anon(
976 locations: Locations,
977 category: ConstraintCategory,
979 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
980 if let TyKind::Opaque(..) = sup.sty {
981 // When you have `let x: impl Foo = ...` in a closure,
982 // the resulting inferend values are stored with the
983 // def-id of the base function.
984 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
985 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
997 locations: Locations,
998 category: ConstraintCategory,
1000 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1003 fn relate_type_and_user_type(
1007 user_ty: &UserTypeProjection<'tcx>,
1008 locations: Locations,
1009 category: ConstraintCategory,
1012 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1013 a, v, user_ty, locations,
1016 match user_ty.base {
1017 UserTypeAnnotation::Ty(canonical_ty) => {
1018 let (ty, _) = self.infcx
1019 .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_ty);
1021 // The `TypeRelating` code assumes that "unresolved inference
1022 // variables" appear in the "a" side, so flip `Contravariant`
1023 // ambient variance to get the right relationship.
1024 let v1 = ty::Contravariant.xform(v);
1026 let tcx = self.infcx.tcx;
1027 let ty = self.normalize(ty, locations);
1029 // We need to follow any provided projetions into the type.
1031 // if we hit a ty var as we descend, then just skip the
1032 // attempt to relate the mir local with any type.
1033 #[derive(Debug)] struct HitTyVar;
1034 let mut curr_projected_ty: Result<PlaceTy, HitTyVar>;
1036 curr_projected_ty = Ok(PlaceTy::from_ty(ty));
1037 for proj in &user_ty.projs {
1038 let projected_ty = if let Ok(projected_ty) = curr_projected_ty {
1043 curr_projected_ty = projected_ty.projection_ty_core(
1044 tcx, proj, |this, field, &()| {
1045 if this.to_ty(tcx).is_ty_var() {
1048 let ty = this.field_ty(tcx, field);
1049 Ok(self.normalize(ty, locations))
1053 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1054 user_ty.base, ty, user_ty.projs, curr_projected_ty);
1056 if let Ok(projected_ty) = curr_projected_ty {
1057 let ty = projected_ty.to_ty(tcx);
1058 self.relate_types(ty, v1, a, locations, category)?;
1061 UserTypeAnnotation::TypeOf(def_id, canonical_substs) => {
1066 .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
1068 let projs = self.infcx.tcx.intern_projs(&user_ty.projs);
1069 self.fully_perform_op(
1072 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1073 a, v, def_id, user_substs, projs,
1082 fn eq_opaque_type_and_type(
1084 revealed_ty: Ty<'tcx>,
1086 anon_owner_def_id: DefId,
1087 locations: Locations,
1088 category: ConstraintCategory,
1091 "eq_opaque_type_and_type( \
1094 revealed_ty, anon_ty
1096 let infcx = self.infcx;
1097 let tcx = infcx.tcx;
1098 let param_env = self.param_env;
1099 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1100 let opaque_type_map = self.fully_perform_op(
1105 let mut obligations = ObligationAccumulator::default();
1107 let dummy_body_id = ObligationCause::dummy().body_id;
1108 let (output_ty, opaque_type_map) =
1109 obligations.add(infcx.instantiate_opaque_types(
1116 "eq_opaque_type_and_type: \
1117 instantiated output_ty={:?} \
1118 opaque_type_map={:#?} \
1120 output_ty, opaque_type_map, revealed_ty
1122 obligations.add(infcx
1123 .at(&ObligationCause::dummy(), param_env)
1124 .eq(output_ty, revealed_ty)?);
1126 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1127 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1128 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1129 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1131 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1132 opaque_decl.concrete_ty,
1133 infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1136 obligations.add(infcx
1137 .at(&ObligationCause::dummy(), param_env)
1138 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1141 debug!("eq_opaque_type_and_type: equated");
1144 value: Some(opaque_type_map),
1145 obligations: obligations.into_vec(),
1148 || "input_output".to_string(),
1152 let universal_region_relations = match self.universal_region_relations {
1154 None => return Ok(()),
1157 // Finally, if we instantiated the anon types successfully, we
1158 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1159 // prove that `T: Iterator` where `T` is the type we
1160 // instantiated it with).
1161 if let Some(opaque_type_map) = opaque_type_map {
1162 for (opaque_def_id, opaque_decl) in opaque_type_map {
1163 self.fully_perform_op(
1165 ConstraintCategory::OpaqueType,
1168 infcx.constrain_opaque_type(
1171 universal_region_relations,
1175 obligations: vec![],
1178 || "opaque_type_map".to_string(),
1186 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1190 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1191 debug!("check_stmt: {:?}", stmt);
1192 let tcx = self.tcx();
1194 StatementKind::Assign(ref place, ref rv) => {
1195 // Assignments to temporaries are not "interesting";
1196 // they are not caused by the user, but rather artifacts
1197 // of lowering. Assignments to other sorts of places *are* interesting
1199 let category = match *place {
1200 Place::Local(RETURN_PLACE) => if let Some(BorrowCheckContext {
1203 defining_ty: DefiningTy::Const(def_id, _),
1207 }) = self.borrowck_context
1209 if tcx.is_static(*def_id).is_some() {
1210 ConstraintCategory::UseAsStatic
1212 ConstraintCategory::UseAsConst
1215 ConstraintCategory::Return
1217 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1218 ConstraintCategory::Boring
1220 _ => ConstraintCategory::Assignment,
1223 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1224 let rv_ty = rv.ty(mir, tcx);
1226 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1231 "bad assignment ({:?} = {:?}): {:?}",
1238 if let Some(user_ty) = self.rvalue_user_ty(rv) {
1239 if let Err(terr) = self.relate_type_and_user_type(
1241 ty::Variance::Invariant,
1242 &UserTypeProjection { base: user_ty, projs: vec![], },
1243 location.to_locations(),
1244 ConstraintCategory::Boring,
1249 "bad user type on rvalue ({:?} = {:?}): {:?}",
1257 self.check_rvalue(mir, rv, location);
1258 if !self.tcx().features().unsized_locals {
1259 let trait_ref = ty::TraitRef {
1260 def_id: tcx.lang_items().sized_trait().unwrap(),
1261 substs: tcx.mk_substs_trait(place_ty, &[]),
1263 self.prove_trait_ref(
1265 location.to_locations(),
1266 ConstraintCategory::SizedBound,
1270 StatementKind::SetDiscriminant {
1274 let place_type = place.ty(mir, tcx).to_ty(tcx);
1275 let adt = match place_type.sty {
1276 TyKind::Adt(adt, _) if adt.is_enum() => adt,
1279 stmt.source_info.span,
1280 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1286 if variant_index.as_usize() >= adt.variants.len() {
1288 stmt.source_info.span,
1289 "bad set discriminant ({:?} = {:?}): value of of range",
1295 StatementKind::AscribeUserType(ref place, variance, box ref c_ty) => {
1296 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1297 if let Err(terr) = self.relate_type_and_user_type(
1301 Locations::All(stmt.source_info.span),
1302 ConstraintCategory::TypeAnnotation,
1307 "bad type assert ({:?} <: {:?}): {:?}",
1314 StatementKind::FakeRead(..)
1315 | StatementKind::StorageLive(..)
1316 | StatementKind::StorageDead(..)
1317 | StatementKind::InlineAsm { .. }
1318 | StatementKind::Retag { .. }
1319 | StatementKind::EscapeToRaw { .. }
1320 | StatementKind::Nop => {}
1324 fn check_terminator(
1327 term: &Terminator<'tcx>,
1328 term_location: Location,
1330 debug!("check_terminator: {:?}", term);
1331 let tcx = self.tcx();
1333 TerminatorKind::Goto { .. }
1334 | TerminatorKind::Resume
1335 | TerminatorKind::Abort
1336 | TerminatorKind::Return
1337 | TerminatorKind::GeneratorDrop
1338 | TerminatorKind::Unreachable
1339 | TerminatorKind::Drop { .. }
1340 | TerminatorKind::FalseEdges { .. }
1341 | TerminatorKind::FalseUnwind { .. } => {
1342 // no checks needed for these
1345 TerminatorKind::DropAndReplace {
1351 let place_ty = location.ty(mir, tcx).to_ty(tcx);
1352 let rv_ty = value.ty(mir, tcx);
1354 let locations = term_location.to_locations();
1356 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1361 "bad DropAndReplace ({:?} = {:?}): {:?}",
1368 TerminatorKind::SwitchInt {
1373 let discr_ty = discr.ty(mir, tcx);
1374 if let Err(terr) = self.sub_types(
1377 term_location.to_locations(),
1378 ConstraintCategory::Assignment,
1383 "bad SwitchInt ({:?} on {:?}): {:?}",
1389 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1390 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1392 // FIXME: check the values
1394 TerminatorKind::Call {
1401 let func_ty = func.ty(mir, tcx);
1402 debug!("check_terminator: call, func_ty={:?}", func_ty);
1403 let sig = match func_ty.sty {
1404 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1406 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1410 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1411 term.source_info.span,
1412 LateBoundRegionConversionTime::FnCall,
1415 let sig = self.normalize(sig, term_location);
1416 self.check_call_dest(mir, term, &sig, destination, term_location);
1418 self.prove_predicates(
1419 sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1420 term_location.to_locations(),
1421 ConstraintCategory::Boring,
1424 // The ordinary liveness rules will ensure that all
1425 // regions in the type of the callee are live here. We
1426 // then further constrain the late-bound regions that
1427 // were instantiated at the call site to be live as
1428 // well. The resulting is that all the input (and
1429 // output) types in the signature must be live, since
1430 // all the inputs that fed into it were live.
1431 for &late_bound_region in map.values() {
1432 if let Some(ref mut borrowck_context) = self.borrowck_context {
1433 let region_vid = borrowck_context
1435 .to_region_vid(late_bound_region);
1438 .liveness_constraints
1439 .add_element(region_vid, term_location);
1443 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1445 TerminatorKind::Assert {
1446 ref cond, ref msg, ..
1448 let cond_ty = cond.ty(mir, tcx);
1449 if cond_ty != tcx.types.bool {
1450 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1453 if let BoundsCheck { ref len, ref index } = *msg {
1454 if len.ty(mir, tcx) != tcx.types.usize {
1455 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1457 if index.ty(mir, tcx) != tcx.types.usize {
1458 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1462 TerminatorKind::Yield { ref value, .. } => {
1463 let value_ty = value.ty(mir, tcx);
1464 match mir.yield_ty {
1465 None => span_mirbug!(self, term, "yield in non-generator"),
1467 if let Err(terr) = self.sub_types(
1470 term_location.to_locations(),
1471 ConstraintCategory::Yield,
1476 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1491 term: &Terminator<'tcx>,
1492 sig: &ty::FnSig<'tcx>,
1493 destination: &Option<(Place<'tcx>, BasicBlock)>,
1494 term_location: Location,
1496 let tcx = self.tcx();
1497 match *destination {
1498 Some((ref dest, _target_block)) => {
1499 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1500 let category = match *dest {
1501 Place::Local(RETURN_PLACE) => {
1502 if let Some(BorrowCheckContext {
1505 defining_ty: DefiningTy::Const(def_id, _),
1509 }) = self.borrowck_context
1511 if tcx.is_static(*def_id).is_some() {
1512 ConstraintCategory::UseAsStatic
1514 ConstraintCategory::UseAsConst
1517 ConstraintCategory::Return
1520 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1521 ConstraintCategory::Boring
1523 _ => ConstraintCategory::Assignment,
1526 let locations = term_location.to_locations();
1529 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1534 "call dest mismatch ({:?} <- {:?}): {:?}",
1541 // When `#![feature(unsized_locals)]` is not enabled,
1542 // this check is done at `check_local`.
1543 if self.tcx().features().unsized_locals {
1544 let span = term.source_info.span;
1545 self.ensure_place_sized(dest_ty, span);
1549 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1550 if !sig.output().is_never() {
1551 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1557 fn check_call_inputs(
1560 term: &Terminator<'tcx>,
1561 sig: &ty::FnSig<'tcx>,
1562 args: &[Operand<'tcx>],
1563 term_location: Location,
1564 from_hir_call: bool,
1566 debug!("check_call_inputs({:?}, {:?})", sig, args);
1567 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1568 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1570 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1571 let op_arg_ty = op_arg.ty(mir, self.tcx());
1572 let category = if from_hir_call {
1573 ConstraintCategory::CallArgument
1575 ConstraintCategory::Boring
1578 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1583 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1593 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1594 let is_cleanup = block_data.is_cleanup;
1595 self.last_span = block_data.terminator().source_info.span;
1596 match block_data.terminator().kind {
1597 TerminatorKind::Goto { target } => {
1598 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1600 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1601 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1603 TerminatorKind::Resume => if !is_cleanup {
1604 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1606 TerminatorKind::Abort => if !is_cleanup {
1607 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1609 TerminatorKind::Return => if is_cleanup {
1610 span_mirbug!(self, block_data, "return on cleanup block")
1612 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1613 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1615 TerminatorKind::Yield { resume, drop, .. } => {
1617 span_mirbug!(self, block_data, "yield in cleanup block")
1619 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1620 if let Some(drop) = drop {
1621 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1624 TerminatorKind::Unreachable => {}
1625 TerminatorKind::Drop { target, unwind, .. }
1626 | TerminatorKind::DropAndReplace { target, unwind, .. }
1627 | TerminatorKind::Assert {
1632 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1633 if let Some(unwind) = unwind {
1635 span_mirbug!(self, block_data, "unwind on cleanup block")
1637 self.assert_iscleanup(mir, block_data, unwind, true);
1640 TerminatorKind::Call {
1645 if let &Some((_, target)) = destination {
1646 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1648 if let Some(cleanup) = cleanup {
1650 span_mirbug!(self, block_data, "cleanup on cleanup block")
1652 self.assert_iscleanup(mir, block_data, cleanup, true);
1655 TerminatorKind::FalseEdges {
1657 ref imaginary_targets,
1659 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1660 for target in imaginary_targets {
1661 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1664 TerminatorKind::FalseUnwind {
1668 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1669 if let Some(unwind) = unwind {
1674 "cleanup in cleanup block via false unwind"
1677 self.assert_iscleanup(mir, block_data, unwind, true);
1683 fn assert_iscleanup(
1686 ctxt: &dyn fmt::Debug,
1690 if mir[bb].is_cleanup != iscleanuppad {
1694 "cleanuppad mismatch: {:?} should be {:?}",
1701 fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1702 match mir.local_kind(local) {
1703 LocalKind::ReturnPointer | LocalKind::Arg => {
1704 // return values of normal functions are required to be
1705 // sized by typeck, but return values of ADT constructors are
1706 // not because we don't include a `Self: Sized` bounds on them.
1708 // Unbound parts of arguments were never required to be Sized
1709 // - maybe we should make that a warning.
1712 LocalKind::Var | LocalKind::Temp => {}
1715 // When `#![feature(unsized_locals)]` is enabled, only function calls
1716 // and nullary ops are checked in `check_call_dest`.
1717 if !self.tcx().features().unsized_locals {
1718 let span = local_decl.source_info.span;
1719 let ty = local_decl.ty;
1720 self.ensure_place_sized(ty, span);
1724 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1725 let tcx = self.tcx();
1727 // Erase the regions from `ty` to get a global type. The
1728 // `Sized` bound in no way depends on precise regions, so this
1729 // shouldn't affect `is_sized`.
1730 let gcx = tcx.global_tcx();
1731 let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1732 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1733 // in current MIR construction, all non-control-flow rvalue
1734 // expressions evaluate through `as_temp` or `into` a return
1735 // slot or local, so to find all unsized rvalues it is enough
1736 // to check all temps, return slots and locals.
1737 if let None = self.reported_errors.replace((ty, span)) {
1738 let mut diag = struct_span_err!(
1742 "cannot move a value of type {0}: the size of {0} \
1743 cannot be statically determined",
1747 // While this is located in `nll::typeck` this error is not
1748 // an NLL error, it's a required check to prevent creation
1749 // of unsized rvalues in certain cases:
1750 // * operand of a box expression
1751 // * callee in a call expression
1757 fn aggregate_field_ty(
1759 ak: &AggregateKind<'tcx>,
1762 ) -> Result<Ty<'tcx>, FieldAccessError> {
1763 let tcx = self.tcx();
1766 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1767 let variant = &def.variants[variant_index];
1768 let adj_field_index = active_field_index.unwrap_or(field_index);
1769 if let Some(field) = variant.fields.get(adj_field_index) {
1770 Ok(self.normalize(field.ty(tcx, substs), location))
1772 Err(FieldAccessError::OutOfRange {
1773 field_count: variant.fields.len(),
1777 AggregateKind::Closure(def_id, substs) => {
1778 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1780 None => Err(FieldAccessError::OutOfRange {
1781 field_count: substs.upvar_tys(def_id, tcx).count(),
1785 AggregateKind::Generator(def_id, substs, _) => {
1786 // Try pre-transform fields first (upvars and current state)
1787 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1790 // Then try `field_tys` which contains all the fields, but it
1791 // requires the final optimized MIR.
1792 match substs.field_tys(def_id, tcx).nth(field_index) {
1794 None => Err(FieldAccessError::OutOfRange {
1795 field_count: substs.field_tys(def_id, tcx).count(),
1800 AggregateKind::Array(ty) => Ok(ty),
1801 AggregateKind::Tuple => {
1802 unreachable!("This should have been covered in check_rvalues");
1807 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1808 let tcx = self.tcx();
1811 Rvalue::Aggregate(ak, ops) => {
1812 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1815 Rvalue::Repeat(operand, len) => if *len > 1 {
1816 let operand_ty = operand.ty(mir, tcx);
1818 let trait_ref = ty::TraitRef {
1819 def_id: tcx.lang_items().copy_trait().unwrap(),
1820 substs: tcx.mk_substs_trait(operand_ty, &[]),
1823 self.prove_trait_ref(
1825 location.to_locations(),
1826 ConstraintCategory::CopyBound,
1830 Rvalue::NullaryOp(_, ty) => {
1831 // Even with unsized locals cannot box an unsized value.
1832 if self.tcx().features().unsized_locals {
1833 let span = mir.source_info(location).span;
1834 self.ensure_place_sized(ty, span);
1837 let trait_ref = ty::TraitRef {
1838 def_id: tcx.lang_items().sized_trait().unwrap(),
1839 substs: tcx.mk_substs_trait(ty, &[]),
1842 self.prove_trait_ref(
1844 location.to_locations(),
1845 ConstraintCategory::SizedBound,
1849 Rvalue::Cast(cast_kind, op, ty) => {
1851 CastKind::ReifyFnPointer => {
1852 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1854 // The type that we see in the fcx is like
1855 // `foo::<'a, 'b>`, where `foo` is the path to a
1856 // function definition. When we extract the
1857 // signature, it comes from the `fn_sig` query,
1858 // and hence may contain unnormalized results.
1859 let fn_sig = self.normalize(fn_sig, location);
1861 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1863 if let Err(terr) = self.eq_types(
1866 location.to_locations(),
1867 ConstraintCategory::Cast,
1872 "equating {:?} with {:?} yields {:?}",
1880 CastKind::ClosureFnPointer => {
1881 let sig = match op.ty(mir, tcx).sty {
1882 ty::Closure(def_id, substs) => {
1883 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1887 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1889 if let Err(terr) = self.eq_types(
1892 location.to_locations(),
1893 ConstraintCategory::Cast,
1898 "equating {:?} with {:?} yields {:?}",
1906 CastKind::UnsafeFnPointer => {
1907 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1909 // The type that we see in the fcx is like
1910 // `foo::<'a, 'b>`, where `foo` is the path to a
1911 // function definition. When we extract the
1912 // signature, it comes from the `fn_sig` query,
1913 // and hence may contain unnormalized results.
1914 let fn_sig = self.normalize(fn_sig, location);
1916 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1918 if let Err(terr) = self.eq_types(
1921 location.to_locations(),
1922 ConstraintCategory::Cast,
1927 "equating {:?} with {:?} yields {:?}",
1935 CastKind::Unsize => {
1937 let trait_ref = ty::TraitRef {
1938 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1939 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1942 self.prove_trait_ref(
1944 location.to_locations(),
1945 ConstraintCategory::Cast,
1949 CastKind::Misc => {}
1953 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1954 self.add_reborrow_constraint(location, region, borrowed_place);
1957 // FIXME: These other cases have to be implemented in future PRs
1960 | Rvalue::BinaryOp(..)
1961 | Rvalue::CheckedBinaryOp(..)
1962 | Rvalue::UnaryOp(..)
1963 | Rvalue::Discriminant(..) => {}
1967 /// If this rvalue supports a user-given type annotation, then
1968 /// extract and return it. This represents the final type of the
1969 /// rvalue and will be unified with the inferred type.
1970 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotation<'tcx>> {
1973 | Rvalue::Repeat(..)
1977 | Rvalue::BinaryOp(..)
1978 | Rvalue::CheckedBinaryOp(..)
1979 | Rvalue::NullaryOp(..)
1980 | Rvalue::UnaryOp(..)
1981 | Rvalue::Discriminant(..) => None,
1983 Rvalue::Aggregate(aggregate, _) => match **aggregate {
1984 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
1985 AggregateKind::Array(_) => None,
1986 AggregateKind::Tuple => None,
1987 AggregateKind::Closure(_, _) => None,
1988 AggregateKind::Generator(_, _, _) => None,
1993 fn check_aggregate_rvalue(
1996 rvalue: &Rvalue<'tcx>,
1997 aggregate_kind: &AggregateKind<'tcx>,
1998 operands: &[Operand<'tcx>],
2001 let tcx = self.tcx();
2003 self.prove_aggregate_predicates(aggregate_kind, location);
2005 if *aggregate_kind == AggregateKind::Tuple {
2006 // tuple rvalue field type is always the type of the op. Nothing to check here.
2010 for (i, operand) in operands.iter().enumerate() {
2011 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2012 Ok(field_ty) => field_ty,
2013 Err(FieldAccessError::OutOfRange { field_count }) => {
2017 "accessed field #{} but variant only has {}",
2024 let operand_ty = operand.ty(mir, tcx);
2026 if let Err(terr) = self.sub_types(
2029 location.to_locations(),
2030 ConstraintCategory::Boring,
2035 "{:?} is not a subtype of {:?}: {:?}",
2044 /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
2048 /// - `location`: the location `L` where the borrow expression occurs
2049 /// - `borrow_region`: the region `'a` associated with the borrow
2050 /// - `borrowed_place`: the place `P` being borrowed
2051 fn add_reborrow_constraint(
2054 borrow_region: ty::Region<'tcx>,
2055 borrowed_place: &Place<'tcx>,
2057 // These constraints are only meaningful during borrowck:
2058 let BorrowCheckContext {
2064 } = match self.borrowck_context {
2065 Some(ref mut borrowck_context) => borrowck_context,
2069 // In Polonius mode, we also push a `borrow_region` fact
2070 // linking the loan to the region (in some cases, though,
2071 // there is no loan associated with this borrow expression --
2072 // that occurs when we are borrowing an unsafe place, for
2074 if let Some(all_facts) = all_facts {
2075 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2076 let region_vid = borrow_region.to_region_vid();
2077 all_facts.borrow_region.push((
2080 location_table.mid_index(location),
2085 // If we are reborrowing the referent of another reference, we
2086 // need to add outlives relationships. In a case like `&mut
2087 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2088 // need to ensure that `'b: 'a`.
2090 let mut borrowed_place = borrowed_place;
2093 "add_reborrow_constraint({:?}, {:?}, {:?})",
2094 location, borrow_region, borrowed_place
2096 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2097 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2100 ProjectionElem::Deref => {
2101 let tcx = self.infcx.tcx;
2102 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
2104 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2106 ty::Ref(ref_region, _, mutbl) => {
2107 constraints.outlives_constraints.push(OutlivesConstraint {
2108 sup: ref_region.to_region_vid(),
2109 sub: borrow_region.to_region_vid(),
2110 locations: location.to_locations(),
2111 category: ConstraintCategory::Boring,
2115 hir::Mutability::MutImmutable => {
2116 // Immutable reference. We don't need the base
2117 // to be valid for the entire lifetime of
2121 hir::Mutability::MutMutable => {
2122 // Mutable reference. We *do* need the base
2123 // to be valid, because after the base becomes
2124 // invalid, someone else can use our mutable deref.
2126 // This is in order to make the following function
2129 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2134 // As otherwise you could clone `&mut T` using the
2135 // following function:
2137 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2138 // let my_clone = unsafe_deref(&'a x);
2147 // deref of raw pointer, guaranteed to be valid
2150 ty::Adt(def, _) if def.is_box() => {
2151 // deref of `Box`, need the base to be valid - propagate
2153 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2156 ProjectionElem::Field(..)
2157 | ProjectionElem::Downcast(..)
2158 | ProjectionElem::Index(..)
2159 | ProjectionElem::ConstantIndex { .. }
2160 | ProjectionElem::Subslice { .. } => {
2161 // other field access
2165 // The "propagate" case. We need to check that our base is valid
2166 // for the borrow's lifetime.
2167 borrowed_place = base;
2171 fn prove_aggregate_predicates(
2173 aggregate_kind: &AggregateKind<'tcx>,
2176 let tcx = self.tcx();
2179 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2180 aggregate_kind, location
2183 let instantiated_predicates = match aggregate_kind {
2184 AggregateKind::Adt(def, _, substs, _, _) => {
2185 tcx.predicates_of(def.did).instantiate(tcx, substs)
2188 // For closures, we have some **extra requirements** we
2190 // have to check. In particular, in their upvars and
2191 // signatures, closures often reference various regions
2192 // from the surrounding function -- we call those the
2193 // closure's free regions. When we borrow-check (and hence
2194 // region-check) closures, we may find that the closure
2195 // requires certain relationships between those free
2196 // regions. However, because those free regions refer to
2197 // portions of the CFG of their caller, the closure is not
2198 // in a position to verify those relationships. In that
2199 // case, the requirements get "propagated" to us, and so
2200 // we have to solve them here where we instantiate the
2203 // Despite the opacity of the previous parapgrah, this is
2204 // actually relatively easy to understand in terms of the
2205 // desugaring. A closure gets desugared to a struct, and
2206 // these extra requirements are basically like where
2207 // clauses on the struct.
2208 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2209 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2210 self.prove_closure_bounds(tcx, *def_id, substs, location)
2213 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2216 self.normalize_and_prove_instantiated_predicates(
2217 instantiated_predicates,
2218 location.to_locations(),
2222 fn prove_closure_bounds(
2224 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2226 substs: &'tcx Substs<'tcx>,
2228 ) -> ty::InstantiatedPredicates<'tcx> {
2229 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2230 let closure_constraints =
2231 closure_region_requirements.apply_requirements(tcx, location, def_id, substs);
2233 if let Some(ref mut borrowck_context) = self.borrowck_context {
2234 let bounds_mapping = closure_constraints
2237 .filter_map(|(idx, constraint)| {
2238 let ty::OutlivesPredicate(k1, r2) =
2239 constraint.no_bound_vars().unwrap_or_else(|| {
2240 bug!("query_constraint {:?} contained bound vars", constraint,);
2244 UnpackedKind::Lifetime(r1) => {
2245 // constraint is r1: r2
2246 let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
2247 let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
2248 let outlives_requirements =
2249 &closure_region_requirements.outlives_requirements[idx];
2253 outlives_requirements.category,
2254 outlives_requirements.blame_span,
2258 UnpackedKind::Type(_) => None,
2263 let existing = borrowck_context
2265 .closure_bounds_mapping
2266 .insert(location, bounds_mapping);
2269 "Multiple closures at the same location."
2273 self.push_region_constraints(
2274 location.to_locations(),
2275 ConstraintCategory::ClosureBounds,
2276 &closure_constraints,
2280 tcx.predicates_of(def_id).instantiate(tcx, substs)
2285 trait_ref: ty::TraitRef<'tcx>,
2286 locations: Locations,
2287 category: ConstraintCategory,
2289 self.prove_predicates(
2290 Some(ty::Predicate::Trait(
2291 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2298 fn normalize_and_prove_instantiated_predicates(
2300 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2301 locations: Locations,
2303 for predicate in instantiated_predicates.predicates {
2304 let predicate = self.normalize(predicate, locations);
2305 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2309 fn prove_predicates(
2311 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2312 locations: Locations,
2313 category: ConstraintCategory,
2315 for predicate in predicates {
2317 "prove_predicates(predicate={:?}, locations={:?})",
2318 predicate, locations,
2321 self.prove_predicate(predicate, locations, category);
2327 predicate: ty::Predicate<'tcx>,
2328 locations: Locations,
2329 category: ConstraintCategory,
2332 "prove_predicate(predicate={:?}, location={:?})",
2333 predicate, locations,
2336 let param_env = self.param_env;
2337 self.fully_perform_op(
2340 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2341 ).unwrap_or_else(|NoSolution| {
2342 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2346 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2347 self.last_span = mir.span;
2348 debug!("run_on_mir: {:?}", mir.span);
2350 for (local, local_decl) in mir.local_decls.iter_enumerated() {
2351 self.check_local(mir, local, local_decl);
2354 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2355 let mut location = Location {
2359 for stmt in &block_data.statements {
2360 if !stmt.source_info.span.is_dummy() {
2361 self.last_span = stmt.source_info.span;
2363 self.check_stmt(mir, stmt, location);
2364 location.statement_index += 1;
2367 self.check_terminator(mir, block_data.terminator(), location);
2368 self.check_iscleanup(mir, block_data);
2372 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2374 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2376 debug!("normalize(value={:?}, location={:?})", value, location);
2377 let param_env = self.param_env;
2378 self.fully_perform_op(
2379 location.to_locations(),
2380 ConstraintCategory::Boring,
2381 param_env.and(type_op::normalize::Normalize::new(value)),
2382 ).unwrap_or_else(|NoSolution| {
2383 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2389 pub struct TypeckMir;
2391 impl MirPass for TypeckMir {
2392 fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
2393 let def_id = src.def_id;
2394 debug!("run_pass: {:?}", def_id);
2396 // When NLL is enabled, the borrow checker runs the typeck
2397 // itself, so we don't need this MIR pass anymore.
2398 if tcx.use_mir_borrowck() {
2402 if tcx.sess.err_count() > 0 {
2403 // compiling a broken program can obviously result in a
2404 // broken MIR, so try not to report duplicate errors.
2408 if tcx.is_struct_constructor(def_id) {
2409 // We just assume that the automatically generated struct constructors are
2410 // correct. See the comment in the `mir_borrowck` implementation for an
2411 // explanation why we need this.
2415 let param_env = tcx.param_env(def_id);
2416 tcx.infer_ctxt().enter(|infcx| {
2417 type_check_internal(
2429 // For verification purposes, we just ignore the resulting
2430 // region constraint sets. Not our problem. =)
2435 trait NormalizeLocation: fmt::Debug + Copy {
2436 fn to_locations(self) -> Locations;
2439 impl NormalizeLocation for Locations {
2440 fn to_locations(self) -> Locations {
2445 impl NormalizeLocation for Location {
2446 fn to_locations(self) -> Locations {
2447 Locations::Single(self)
2451 #[derive(Debug, Default)]
2452 struct ObligationAccumulator<'tcx> {
2453 obligations: PredicateObligations<'tcx>,
2456 impl<'tcx> ObligationAccumulator<'tcx> {
2457 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2458 let InferOk { value, obligations } = value;
2459 self.obligations.extend(obligations);
2463 fn into_vec(self) -> PredicateObligations<'tcx> {