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.
12 #![allow(unreachable_code)]
14 use borrow_check::borrow_set::BorrowSet;
15 use borrow_check::location::LocationTable;
16 use borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
17 use borrow_check::nll::facts::AllFacts;
18 use borrow_check::nll::region_infer::values::LivenessValues;
19 use borrow_check::nll::region_infer::values::PlaceholderIndex;
20 use borrow_check::nll::region_infer::values::PlaceholderIndices;
21 use borrow_check::nll::region_infer::values::RegionValueElements;
22 use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
23 use borrow_check::nll::renumber;
24 use borrow_check::nll::type_check::free_region_relations::{
25 CreateResult, UniversalRegionRelations,
27 use borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
28 use borrow_check::nll::ToRegionVid;
29 use dataflow::move_paths::MoveData;
30 use dataflow::FlowAtLocation;
31 use dataflow::MaybeInitializedPlaces;
34 use rustc::hir::def_id::DefId;
35 use rustc::infer::canonical::QueryRegionConstraint;
36 use rustc::infer::outlives::env::RegionBoundPairs;
37 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
38 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
39 use rustc::mir::tcx::PlaceTy;
40 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
42 use rustc::traits::query::type_op;
43 use rustc::traits::query::type_op::custom::CustomTypeOp;
44 use rustc::traits::query::{Fallible, NoSolution};
45 use rustc::traits::{ObligationCause, PredicateObligations};
46 use rustc::ty::fold::TypeFoldable;
47 use rustc::ty::subst::{Subst, Substs, UnpackedKind};
48 use rustc::ty::{self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TyKind};
49 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
50 use rustc_data_structures::indexed_vec::IndexVec;
53 use syntax_pos::{Span, DUMMY_SP};
54 use transform::{MirPass, MirSource};
56 macro_rules! span_mirbug {
57 ($context:expr, $elem:expr, $($message:tt)*) => ({
58 $crate::borrow_check::nll::type_check::mirbug(
62 "broken MIR in {:?} ({:?}): {}",
65 format_args!($($message)*),
71 macro_rules! span_mirbug_and_err {
72 ($context:expr, $elem:expr, $($message:tt)*) => ({
74 span_mirbug!($context, $elem, $($message)*);
80 mod constraint_conversion;
81 pub mod free_region_relations;
86 /// Type checks the given `mir` in the context of the inference
87 /// context `infcx`. Returns any region constraints that have yet to
88 /// be proven. This result is includes liveness constraints that
89 /// ensure that regions appearing in the types of all local variables
90 /// are live at all points where that local variable may later be
93 /// This phase of type-check ought to be infallible -- this is because
94 /// the original, HIR-based type-check succeeded. So if any errors
95 /// occur here, we will get a `bug!` reported.
99 /// - `infcx` -- inference context to use
100 /// - `param_env` -- parameter environment to use for trait solving
101 /// - `mir` -- MIR to type-check
102 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
103 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
104 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
105 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
106 /// to outlive; should represent the fn body
107 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
108 /// the types of the input parameters found in the MIR itself will be equated with these
109 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
110 /// the type for the RETURN_PLACE will be equated with this
111 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
112 /// constraints for the regions in the types of variables
113 /// - `flow_inits` -- results of a maybe-init dataflow analysis
114 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysiss
115 pub(crate) fn type_check<'gcx, 'tcx>(
116 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
117 param_env: ty::ParamEnv<'gcx>,
120 universal_regions: &Rc<UniversalRegions<'tcx>>,
121 location_table: &LocationTable,
122 borrow_set: &BorrowSet<'tcx>,
123 all_facts: &mut Option<AllFacts>,
124 flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
125 move_data: &MoveData<'tcx>,
126 elements: &Rc<RegionValueElements>,
127 ) -> MirTypeckResults<'tcx> {
128 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
129 let mut constraints = MirTypeckRegionConstraints {
130 placeholder_indices: PlaceholderIndices::default(),
131 placeholder_index_to_region: IndexVec::default(),
132 liveness_constraints: LivenessValues::new(elements),
133 outlives_constraints: ConstraintSet::default(),
134 closure_bounds_mapping: Default::default(),
135 type_tests: Vec::default(),
139 universal_region_relations,
141 normalized_inputs_and_output,
142 } = free_region_relations::create(
145 Some(implicit_region_bound),
150 let mut borrowck_context = BorrowCheckContext {
155 constraints: &mut constraints,
164 Some(implicit_region_bound),
165 Some(&mut borrowck_context),
166 Some(&universal_region_relations),
168 cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
169 liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
173 .map(|bcx| translate_outlives_facts(bcx));
179 universal_region_relations,
183 fn type_check_internal<'a, 'gcx, 'tcx, R>(
184 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
186 param_env: ty::ParamEnv<'gcx>,
188 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
189 implicit_region_bound: Option<ty::Region<'tcx>>,
190 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
191 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
192 mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
194 let mut checker = TypeChecker::new(
200 implicit_region_bound,
202 universal_region_relations,
204 let errors_reported = {
205 let mut verifier = TypeVerifier::new(&mut checker, mir);
206 verifier.visit_mir(mir);
207 verifier.errors_reported
210 if !errors_reported {
211 // if verifier failed, don't do further checks to avoid ICEs
212 checker.typeck_mir(mir);
218 fn translate_outlives_facts(cx: &mut BorrowCheckContext) {
219 if let Some(facts) = cx.all_facts {
220 let location_table = cx.location_table;
223 .extend(cx.constraints.outlives_constraints.iter().flat_map(
224 |constraint: &OutlivesConstraint| {
225 if let Some(from_location) = constraint.locations.from_location() {
226 Either::Left(iter::once((
229 location_table.mid_index(from_location),
235 .map(move |location| (constraint.sup, constraint.sub, location)),
243 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
244 // We sometimes see MIR failures (notably predicate failures) due to
245 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
246 // to avoid reporting bugs in those cases.
247 tcx.sess.diagnostic().delay_span_bug(span, msg);
250 enum FieldAccessError {
251 OutOfRange { field_count: usize },
254 /// Verifies that MIR types are sane to not crash further checks.
256 /// The sanitize_XYZ methods here take an MIR object and compute its
257 /// type, calling `span_mirbug` and returning an error type if there
259 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
260 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
264 errors_reported: bool,
267 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
268 fn visit_span(&mut self, span: &Span) {
269 if !span.is_dummy() {
270 self.last_span = *span;
274 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
275 self.sanitize_place(place, location, context);
278 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
279 self.super_constant(constant, location);
280 self.sanitize_constant(constant, location);
281 self.sanitize_type(constant, constant.ty);
283 if let Some(user_ty) = constant.user_ty {
284 if let Err(terr) = self.cx.relate_type_and_user_type(
286 ty::Variance::Invariant,
287 &UserTypeProjection { base: user_ty, projs: vec![], },
288 location.to_locations(),
289 ConstraintCategory::Boring,
294 "bad constant user type {:?} vs {:?}: {:?}",
303 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
304 self.super_rvalue(rvalue, location);
305 let rval_ty = rvalue.ty(self.mir, self.tcx());
306 self.sanitize_type(rvalue, rval_ty);
309 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
310 self.super_local_decl(local, local_decl);
311 self.sanitize_type(local_decl, local_decl.ty);
313 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
314 if let Err(terr) = self.cx.relate_type_and_user_type(
316 ty::Variance::Invariant,
318 Locations::All(*span),
319 ConstraintCategory::TypeAnnotation,
324 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
334 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
335 self.sanitize_type(&"return type", mir.return_ty());
336 for local_decl in &mir.local_decls {
337 self.sanitize_type(local_decl, local_decl.ty);
339 if self.errors_reported {
346 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
347 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
350 mir_def_id: cx.mir_def_id,
353 errors_reported: false,
357 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
361 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
362 if ty.has_escaping_bound_vars() || ty.references_error() {
363 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
369 /// Checks that the constant's `ty` field matches up with what
370 /// would be expected from its literal.
371 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
373 "sanitize_constant(constant={:?}, location={:?})",
377 // FIXME(#46702) -- We need some way to get the predicates
378 // associated with the "pre-evaluated" form of the
379 // constant. For example, consider that the constant
380 // may have associated constant projections (`<Foo as
381 // Trait<'a, 'b>>::SOME_CONST`) that impose
382 // constraints on `'a` and `'b`. These constraints
383 // would be lost if we just look at the normalized
385 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
386 let tcx = self.tcx();
387 let type_checker = &mut self.cx;
389 // FIXME -- For now, use the substitutions from
390 // `value.ty` rather than `value.val`. The
391 // renumberer will rewrite them to independent
392 // sets of regions; in principle, we ought to
393 // derive the type of the `value.val` from "first
394 // principles" and equate with value.ty, but as we
395 // are transitioning to the miri-based system, we
396 // don't have a handy function for that, so for
397 // now we just ignore `value.val` regions.
399 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
400 type_checker.normalize_and_prove_instantiated_predicates(
401 instantiated_predicates,
402 location.to_locations(),
406 debug!("sanitize_constant: expected_ty={:?}", constant.literal.ty);
408 if let Err(terr) = self.cx.eq_types(
411 location.to_locations(),
412 ConstraintCategory::Boring,
417 "constant {:?} should have type {:?} but has {:?} ({:?})",
426 /// Checks that the types internal to the `place` match up with
427 /// what would be expected.
432 context: PlaceContext,
434 debug!("sanitize_place: {:?}", place);
435 let place_ty = match *place {
436 Place::Local(index) => PlaceTy::Ty {
437 ty: self.mir.local_decls[index].ty,
439 Place::Promoted(box (_index, sty)) => {
440 let sty = self.sanitize_type(place, sty);
441 // FIXME -- promoted MIR return types reference
442 // various "free regions" (e.g., scopes and things)
443 // that they ought not to do. We have to figure out
444 // how best to handle that -- probably we want treat
445 // promoted MIR much like closures, renumbering all
446 // their free regions and propagating constraints
447 // upwards. We have the same acyclic guarantees, so
448 // that should be possible. But for now, ignore them.
450 // let promoted_mir = &self.mir.promoted[index];
451 // promoted_mir.return_ty()
452 PlaceTy::Ty { ty: sty }
454 Place::Static(box Static { def_id, ty: sty }) => {
455 let sty = self.sanitize_type(place, sty);
456 let ty = self.tcx().type_of(def_id);
457 let ty = self.cx.normalize(ty, location);
460 .eq_types(ty, sty, location.to_locations(), ConstraintCategory::Boring)
465 "bad static type ({:?}: {:?}): {:?}",
471 PlaceTy::Ty { ty: sty }
473 Place::Projection(ref proj) => {
474 let base_context = if context.is_mutating_use() {
475 PlaceContext::MutatingUse(MutatingUseContext::Projection)
477 PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
479 let base_ty = self.sanitize_place(&proj.base, location, base_context);
480 if let PlaceTy::Ty { ty } = base_ty {
481 if ty.references_error() {
482 assert!(self.errors_reported);
484 ty: self.tcx().types.err,
488 self.sanitize_projection(base_ty, &proj.elem, place, location)
491 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
492 let tcx = self.tcx();
493 let trait_ref = ty::TraitRef {
494 def_id: tcx.lang_items().copy_trait().unwrap(),
495 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
498 // In order to have a Copy operand, the type T of the value must be Copy. Note that we
499 // prove that T: Copy, rather than using the type_moves_by_default test. This is
500 // important because type_moves_by_default ignores the resulting region obligations and
501 // assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
502 // (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
503 // fully apply: in effect, the rule is that if a value of some type could implement
504 // Copy, then it must.
505 self.cx.prove_trait_ref(
507 location.to_locations(),
508 ConstraintCategory::CopyBound,
514 fn sanitize_projection(
517 pi: &PlaceElem<'tcx>,
521 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
522 let tcx = self.tcx();
523 let base_ty = base.to_ty(tcx);
525 ProjectionElem::Deref => {
526 let deref_ty = base_ty.builtin_deref(true);
528 ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
529 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
533 ProjectionElem::Index(i) => {
534 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
535 if index_ty != tcx.types.usize {
537 ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
541 ty: base_ty.builtin_index().unwrap_or_else(|| {
542 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
547 ProjectionElem::ConstantIndex { .. } => {
548 // consider verifying in-bounds
550 ty: base_ty.builtin_index().unwrap_or_else(|| {
551 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
555 ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
556 ty: match base_ty.sty {
557 ty::Array(inner, size) => {
558 let size = size.unwrap_usize(tcx);
559 let min_size = (from as u64) + (to as u64);
560 if let Some(rest_size) = size.checked_sub(min_size) {
561 tcx.mk_array(inner, rest_size)
563 span_mirbug_and_err!(
566 "taking too-small slice of {:?}",
571 ty::Slice(..) => base_ty,
572 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
575 ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
576 ty::Adt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
577 if index >= adt_def.variants.len() {
579 ty: span_mirbug_and_err!(
582 "cast to variant #{:?} but enum only has {:?}",
584 adt_def.variants.len()
591 variant_index: index,
596 ty: span_mirbug_and_err!(
599 "can't downcast {:?} as {:?}",
605 ProjectionElem::Field(field, fty) => {
606 let fty = self.sanitize_type(place, fty);
607 match self.field_ty(place, base, field, location) {
608 Ok(ty) => if let Err(terr) = self.cx.eq_types(
611 location.to_locations(),
612 ConstraintCategory::Boring,
617 "bad field access ({:?}: {:?}): {:?}",
623 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
626 "accessed field #{} but variant only has {}",
631 PlaceTy::Ty { ty: fty }
636 fn error(&mut self) -> Ty<'tcx> {
637 self.errors_reported = true;
643 parent: &dyn fmt::Debug,
644 base_ty: PlaceTy<'tcx>,
647 ) -> Result<Ty<'tcx>, FieldAccessError> {
648 let tcx = self.tcx();
650 let (variant, substs) = match base_ty {
655 } => (&adt_def.variants[variant_index], substs),
656 PlaceTy::Ty { ty } => match ty.sty {
657 ty::Adt(adt_def, substs) if !adt_def.is_enum() => (&adt_def.variants[0], substs),
658 ty::Closure(def_id, substs) => {
659 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
661 None => Err(FieldAccessError::OutOfRange {
662 field_count: substs.upvar_tys(def_id, tcx).count(),
666 ty::Generator(def_id, substs, _) => {
667 // Try pre-transform fields first (upvars and current state)
668 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
672 // Then try `field_tys` which contains all the fields, but it
673 // requires the final optimized MIR.
674 return match substs.field_tys(def_id, tcx).nth(field.index()) {
676 None => Err(FieldAccessError::OutOfRange {
677 field_count: substs.field_tys(def_id, tcx).count(),
682 return match tys.get(field.index()) {
684 None => Err(FieldAccessError::OutOfRange {
685 field_count: tys.len(),
690 return Ok(span_mirbug_and_err!(
693 "can't project out of {:?}",
700 if let Some(field) = variant.fields.get(field.index()) {
701 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
703 Err(FieldAccessError::OutOfRange {
704 field_count: variant.fields.len(),
710 /// The MIR type checker. Visits the MIR and enforces all the
711 /// constraints needed for it to be valid and well-typed. Along the
712 /// way, it accrues region constraints -- these can later be used by
713 /// NLL region checking.
714 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
715 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
716 param_env: ty::ParamEnv<'gcx>,
720 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
721 implicit_region_bound: Option<ty::Region<'tcx>>,
722 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
723 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
724 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
727 struct BorrowCheckContext<'a, 'tcx: 'a> {
728 universal_regions: &'a UniversalRegions<'tcx>,
729 location_table: &'a LocationTable,
730 all_facts: &'a mut Option<AllFacts>,
731 borrow_set: &'a BorrowSet<'tcx>,
732 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
735 crate struct MirTypeckResults<'tcx> {
736 crate constraints: MirTypeckRegionConstraints<'tcx>,
737 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
740 /// A collection of region constraints that must be satisfied for the
741 /// program to be considered well-typed.
742 crate struct MirTypeckRegionConstraints<'tcx> {
743 /// Maps from a `ty::Placeholder` to the corresponding
744 /// `PlaceholderIndex` bit that we will use for it.
746 /// To keep everything in sync, do not insert this set
747 /// directly. Instead, use the `placeholder_region` helper.
748 crate placeholder_indices: PlaceholderIndices,
750 /// Each time we add a placeholder to `placeholder_indices`, we
751 /// also create a corresponding "representative" region vid for
752 /// that wraps it. This vector tracks those. This way, when we
753 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
754 /// the same underlying `RegionVid`.
755 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
757 /// In general, the type-checker is not responsible for enforcing
758 /// liveness constraints; this job falls to the region inferencer,
759 /// which performs a liveness analysis. However, in some limited
760 /// cases, the MIR type-checker creates temporary regions that do
761 /// not otherwise appear in the MIR -- in particular, the
762 /// late-bound regions that it instantiates at call-sites -- and
763 /// hence it must report on their liveness constraints.
764 crate liveness_constraints: LivenessValues<RegionVid>,
766 crate outlives_constraints: ConstraintSet,
768 crate closure_bounds_mapping:
769 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
771 crate type_tests: Vec<TypeTest<'tcx>>,
774 impl MirTypeckRegionConstraints<'tcx> {
775 fn placeholder_region(
777 infcx: &InferCtxt<'_, '_, 'tcx>,
778 placeholder: ty::Placeholder,
779 ) -> ty::Region<'tcx> {
780 let placeholder_index = self.placeholder_indices.insert(placeholder);
781 match self.placeholder_index_to_region.get(placeholder_index) {
784 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
785 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
786 self.placeholder_index_to_region.push(region);
793 /// The `Locations` type summarizes *where* region constraints are
794 /// required to hold. Normally, this is at a particular point which
795 /// created the obligation, but for constraints that the user gave, we
796 /// want the constraint to hold at all points.
797 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
799 /// Indicates that a type constraint should always be true. This
800 /// is particularly important in the new borrowck analysis for
801 /// things like the type of the return slot. Consider this
805 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
807 /// return &y; // error
811 /// Here, we wind up with the signature from the return type being
812 /// something like `&'1 u32` where `'1` is a universal region. But
813 /// the type of the return slot `_0` is something like `&'2 u32`
814 /// where `'2` is an existential region variable. The type checker
815 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
816 /// older NLL analysis, we required this only at the entry point
817 /// to the function. By the nature of the constraints, this wound
818 /// up propagating to all points reachable from start (because
819 /// `'1` -- as a universal region -- is live everywhere). In the
820 /// newer analysis, though, this doesn't work: `_0` is considered
821 /// dead at the start (it has no usable value) and hence this type
822 /// equality is basically a no-op. Then, later on, when we do `_0
823 /// = &'3 y`, that region `'3` never winds up related to the
824 /// universal region `'1` and hence no error occurs. Therefore, we
825 /// use Locations::All instead, which ensures that the `'1` and
826 /// `'2` are equal everything. We also use this for other
827 /// user-given type annotations; e.g., if the user wrote `let mut
828 /// x: &'static u32 = ...`, we would ensure that all values
829 /// assigned to `x` are of `'static` lifetime.
831 /// The span points to the place the constraint arose. For example,
832 /// it points to the type in a user-given type annotation. If
833 /// there's no sensible span then it's DUMMY_SP.
836 /// An outlives constraint that only has to hold at a single location,
837 /// usually it represents a point where references flow from one spot to
838 /// another (e.g., `x = y`)
843 pub fn from_location(&self) -> Option<Location> {
845 Locations::All(_) => None,
846 Locations::Single(from_location) => Some(*from_location),
850 /// Gets a span representing the location.
851 pub fn span(&self, mir: &Mir<'_>) -> Span {
853 Locations::All(span) => *span,
854 Locations::Single(l) => mir.source_info(*l).span,
859 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
861 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
864 param_env: ty::ParamEnv<'gcx>,
865 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
866 implicit_region_bound: Option<ty::Region<'tcx>>,
867 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
868 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
877 implicit_region_bound,
879 reported_errors: Default::default(),
880 universal_region_relations,
884 /// Given some operation `op` that manipulates types, proves
885 /// predicates, or otherwise uses the inference context, executes
886 /// `op` and then executes all the further obligations that `op`
887 /// returns. This will yield a set of outlives constraints amongst
888 /// regions which are extracted and stored as having occurred at
891 /// **Any `rustc::infer` operations that might generate region
892 /// constraints should occur within this method so that those
893 /// constraints can be properly localized!**
894 fn fully_perform_op<R>(
896 locations: Locations,
897 category: ConstraintCategory,
898 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
900 let (r, opt_data) = op.fully_perform(self.infcx)?;
902 if let Some(data) = &opt_data {
903 self.push_region_constraints(locations, category, data);
909 fn push_region_constraints(
911 locations: Locations,
912 category: ConstraintCategory,
913 data: &[QueryRegionConstraint<'tcx>],
916 "push_region_constraints: constraints generated at {:?} are {:#?}",
920 if let Some(ref mut borrowck_context) = self.borrowck_context {
921 constraint_conversion::ConstraintConversion::new(
923 borrowck_context.universal_regions,
924 self.region_bound_pairs,
925 self.implicit_region_bound,
929 &mut borrowck_context.constraints,
930 ).convert_all(&data);
934 /// Convenient wrapper around `relate_tys::relate_types` -- see
935 /// that fn for docs.
941 locations: Locations,
942 category: ConstraintCategory,
944 relate_tys::relate_types(
951 self.borrowck_context.as_mut().map(|x| &mut **x),
959 locations: Locations,
960 category: ConstraintCategory,
962 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
965 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
966 /// variables in `sub` with their inferred definitions and try
967 /// again. This is used for opaque types in places (e.g., `let x:
969 fn sub_types_or_anon(
973 locations: Locations,
974 category: ConstraintCategory,
976 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
977 if let TyKind::Opaque(..) = sup.sty {
978 // When you have `let x: impl Foo = ...` in a closure,
979 // the resulting inferend values are stored with the
980 // def-id of the base function.
981 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
982 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
994 locations: Locations,
995 category: ConstraintCategory,
997 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1000 fn relate_type_and_user_type(
1004 user_ty: &UserTypeProjection<'tcx>,
1005 locations: Locations,
1006 category: ConstraintCategory,
1009 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1010 a, v, user_ty, locations,
1013 match user_ty.base {
1014 UserTypeAnnotation::Ty(canonical_ty) => {
1015 let (ty, _) = self.infcx
1016 .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_ty);
1018 // The `TypeRelating` code assumes that "unresolved inference
1019 // variables" appear in the "a" side, so flip `Contravariant`
1020 // ambient variance to get the right relationship.
1021 let v1 = ty::Contravariant.xform(v);
1023 let tcx = self.infcx.tcx;
1024 let mut projected_ty = PlaceTy::from_ty(ty);
1025 for proj in &user_ty.projs {
1026 projected_ty = projected_ty.projection_ty_core(
1027 tcx, proj, |this, field, &()| {
1028 let ty = this.field_ty(tcx, field);
1029 self.normalize(ty, locations)
1032 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1033 user_ty.base, ty, user_ty.projs, projected_ty);
1035 let ty = projected_ty.to_ty(tcx);
1037 self.relate_types(ty, v1, a, locations, category)?;
1039 UserTypeAnnotation::TypeOf(def_id, canonical_substs) => {
1044 .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
1046 let projs = self.infcx.tcx.intern_projs(&user_ty.projs);
1047 self.fully_perform_op(
1050 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1051 a, v, def_id, user_substs, projs,
1060 fn eq_opaque_type_and_type(
1062 revealed_ty: Ty<'tcx>,
1064 anon_owner_def_id: DefId,
1065 locations: Locations,
1066 category: ConstraintCategory,
1069 "eq_opaque_type_and_type( \
1072 revealed_ty, anon_ty
1074 let infcx = self.infcx;
1075 let tcx = infcx.tcx;
1076 let param_env = self.param_env;
1077 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1078 let opaque_type_map = self.fully_perform_op(
1083 let mut obligations = ObligationAccumulator::default();
1085 let dummy_body_id = ObligationCause::dummy().body_id;
1086 let (output_ty, opaque_type_map) =
1087 obligations.add(infcx.instantiate_opaque_types(
1094 "eq_opaque_type_and_type: \
1095 instantiated output_ty={:?} \
1096 opaque_type_map={:#?} \
1098 output_ty, opaque_type_map, revealed_ty
1100 obligations.add(infcx
1101 .at(&ObligationCause::dummy(), param_env)
1102 .eq(output_ty, revealed_ty)?);
1104 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1105 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1106 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1107 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1109 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1110 opaque_decl.concrete_ty,
1111 infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1114 obligations.add(infcx
1115 .at(&ObligationCause::dummy(), param_env)
1116 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1119 debug!("eq_opaque_type_and_type: equated");
1122 value: Some(opaque_type_map),
1123 obligations: obligations.into_vec(),
1126 || "input_output".to_string(),
1130 let universal_region_relations = match self.universal_region_relations {
1132 None => return Ok(()),
1135 // Finally, if we instantiated the anon types successfully, we
1136 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1137 // prove that `T: Iterator` where `T` is the type we
1138 // instantiated it with).
1139 if let Some(opaque_type_map) = opaque_type_map {
1140 for (opaque_def_id, opaque_decl) in opaque_type_map {
1141 self.fully_perform_op(
1143 ConstraintCategory::OpaqueType,
1146 infcx.constrain_opaque_type(
1149 universal_region_relations,
1153 obligations: vec![],
1156 || "opaque_type_map".to_string(),
1164 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1168 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1169 debug!("check_stmt: {:?}", stmt);
1170 let tcx = self.tcx();
1172 StatementKind::Assign(ref place, ref rv) => {
1173 // Assignments to temporaries are not "interesting";
1174 // they are not caused by the user, but rather artifacts
1175 // of lowering. Assignments to other sorts of places *are* interesting
1177 let category = match *place {
1178 Place::Local(RETURN_PLACE) => if let Some(BorrowCheckContext {
1181 defining_ty: DefiningTy::Const(def_id, _),
1185 }) = self.borrowck_context
1187 if tcx.is_static(*def_id).is_some() {
1188 ConstraintCategory::UseAsStatic
1190 ConstraintCategory::UseAsConst
1193 ConstraintCategory::Return
1195 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1196 ConstraintCategory::Boring
1198 _ => ConstraintCategory::Assignment,
1201 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1202 let rv_ty = rv.ty(mir, tcx);
1204 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1209 "bad assignment ({:?} = {:?}): {:?}",
1216 if let Some(user_ty) = self.rvalue_user_ty(rv) {
1217 if let Err(terr) = self.relate_type_and_user_type(
1219 ty::Variance::Invariant,
1220 &UserTypeProjection { base: user_ty, projs: vec![], },
1221 location.to_locations(),
1222 ConstraintCategory::Boring,
1227 "bad user type on rvalue ({:?} = {:?}): {:?}",
1235 self.check_rvalue(mir, rv, location);
1236 if !self.tcx().features().unsized_locals {
1237 let trait_ref = ty::TraitRef {
1238 def_id: tcx.lang_items().sized_trait().unwrap(),
1239 substs: tcx.mk_substs_trait(place_ty, &[]),
1241 self.prove_trait_ref(
1243 location.to_locations(),
1244 ConstraintCategory::SizedBound,
1248 StatementKind::SetDiscriminant {
1252 let place_type = place.ty(mir, tcx).to_ty(tcx);
1253 let adt = match place_type.sty {
1254 TyKind::Adt(adt, _) if adt.is_enum() => adt,
1257 stmt.source_info.span,
1258 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1264 if variant_index >= adt.variants.len() {
1266 stmt.source_info.span,
1267 "bad set discriminant ({:?} = {:?}): value of of range",
1273 StatementKind::AscribeUserType(ref place, variance, box ref c_ty) => {
1274 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1275 if let Err(terr) = self.relate_type_and_user_type(
1279 Locations::All(stmt.source_info.span),
1280 ConstraintCategory::TypeAnnotation,
1285 "bad type assert ({:?} <: {:?}): {:?}",
1292 StatementKind::FakeRead(..)
1293 | StatementKind::StorageLive(..)
1294 | StatementKind::StorageDead(..)
1295 | StatementKind::InlineAsm { .. }
1296 | StatementKind::EndRegion(_)
1297 | StatementKind::Retag { .. }
1298 | StatementKind::EscapeToRaw { .. }
1299 | StatementKind::Nop => {}
1303 fn check_terminator(
1306 term: &Terminator<'tcx>,
1307 term_location: Location,
1309 debug!("check_terminator: {:?}", term);
1310 let tcx = self.tcx();
1312 TerminatorKind::Goto { .. }
1313 | TerminatorKind::Resume
1314 | TerminatorKind::Abort
1315 | TerminatorKind::Return
1316 | TerminatorKind::GeneratorDrop
1317 | TerminatorKind::Unreachable
1318 | TerminatorKind::Drop { .. }
1319 | TerminatorKind::FalseEdges { .. }
1320 | TerminatorKind::FalseUnwind { .. } => {
1321 // no checks needed for these
1324 TerminatorKind::DropAndReplace {
1330 let place_ty = location.ty(mir, tcx).to_ty(tcx);
1331 let rv_ty = value.ty(mir, tcx);
1333 let locations = term_location.to_locations();
1335 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1340 "bad DropAndReplace ({:?} = {:?}): {:?}",
1347 TerminatorKind::SwitchInt {
1352 let discr_ty = discr.ty(mir, tcx);
1353 if let Err(terr) = self.sub_types(
1356 term_location.to_locations(),
1357 ConstraintCategory::Assignment,
1362 "bad SwitchInt ({:?} on {:?}): {:?}",
1368 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1369 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1371 // FIXME: check the values
1373 TerminatorKind::Call {
1380 let func_ty = func.ty(mir, tcx);
1381 debug!("check_terminator: call, func_ty={:?}", func_ty);
1382 let sig = match func_ty.sty {
1383 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1385 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1389 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
1390 term.source_info.span,
1391 LateBoundRegionConversionTime::FnCall,
1394 let sig = self.normalize(sig, term_location);
1395 self.check_call_dest(mir, term, &sig, destination, term_location);
1397 self.prove_predicates(
1398 sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1399 term_location.to_locations(),
1400 ConstraintCategory::Boring,
1403 // The ordinary liveness rules will ensure that all
1404 // regions in the type of the callee are live here. We
1405 // then further constrain the late-bound regions that
1406 // were instantiated at the call site to be live as
1407 // well. The resulting is that all the input (and
1408 // output) types in the signature must be live, since
1409 // all the inputs that fed into it were live.
1410 for &late_bound_region in map.values() {
1411 if let Some(ref mut borrowck_context) = self.borrowck_context {
1412 let region_vid = borrowck_context
1414 .to_region_vid(late_bound_region);
1417 .liveness_constraints
1418 .add_element(region_vid, term_location);
1422 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1424 TerminatorKind::Assert {
1425 ref cond, ref msg, ..
1427 let cond_ty = cond.ty(mir, tcx);
1428 if cond_ty != tcx.types.bool {
1429 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1432 if let BoundsCheck { ref len, ref index } = *msg {
1433 if len.ty(mir, tcx) != tcx.types.usize {
1434 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1436 if index.ty(mir, tcx) != tcx.types.usize {
1437 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1441 TerminatorKind::Yield { ref value, .. } => {
1442 let value_ty = value.ty(mir, tcx);
1443 match mir.yield_ty {
1444 None => span_mirbug!(self, term, "yield in non-generator"),
1446 if let Err(terr) = self.sub_types(
1449 term_location.to_locations(),
1450 ConstraintCategory::Return,
1455 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1470 term: &Terminator<'tcx>,
1471 sig: &ty::FnSig<'tcx>,
1472 destination: &Option<(Place<'tcx>, BasicBlock)>,
1473 term_location: Location,
1475 let tcx = self.tcx();
1476 match *destination {
1477 Some((ref dest, _target_block)) => {
1478 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1479 let category = match *dest {
1480 Place::Local(RETURN_PLACE) => {
1481 if let Some(BorrowCheckContext {
1484 defining_ty: DefiningTy::Const(def_id, _),
1488 }) = self.borrowck_context
1490 if tcx.is_static(*def_id).is_some() {
1491 ConstraintCategory::UseAsStatic
1493 ConstraintCategory::UseAsConst
1496 ConstraintCategory::Return
1499 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1500 ConstraintCategory::Boring
1502 _ => ConstraintCategory::Assignment,
1505 let locations = term_location.to_locations();
1508 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1513 "call dest mismatch ({:?} <- {:?}): {:?}",
1520 // When `#![feature(unsized_locals)]` is not enabled,
1521 // this check is done at `check_local`.
1522 if self.tcx().features().unsized_locals {
1523 let span = term.source_info.span;
1524 self.ensure_place_sized(dest_ty, span);
1528 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1529 if !sig.output().is_never() {
1530 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1536 fn check_call_inputs(
1539 term: &Terminator<'tcx>,
1540 sig: &ty::FnSig<'tcx>,
1541 args: &[Operand<'tcx>],
1542 term_location: Location,
1543 from_hir_call: bool,
1545 debug!("check_call_inputs({:?}, {:?})", sig, args);
1546 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1547 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1549 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1550 let op_arg_ty = op_arg.ty(mir, self.tcx());
1551 let category = if from_hir_call {
1552 ConstraintCategory::CallArgument
1554 ConstraintCategory::Boring
1557 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1562 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1572 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1573 let is_cleanup = block_data.is_cleanup;
1574 self.last_span = block_data.terminator().source_info.span;
1575 match block_data.terminator().kind {
1576 TerminatorKind::Goto { target } => {
1577 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1579 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1580 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1582 TerminatorKind::Resume => if !is_cleanup {
1583 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1585 TerminatorKind::Abort => if !is_cleanup {
1586 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1588 TerminatorKind::Return => if is_cleanup {
1589 span_mirbug!(self, block_data, "return on cleanup block")
1591 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1592 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1594 TerminatorKind::Yield { resume, drop, .. } => {
1596 span_mirbug!(self, block_data, "yield in cleanup block")
1598 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1599 if let Some(drop) = drop {
1600 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1603 TerminatorKind::Unreachable => {}
1604 TerminatorKind::Drop { target, unwind, .. }
1605 | TerminatorKind::DropAndReplace { target, unwind, .. }
1606 | TerminatorKind::Assert {
1611 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1612 if let Some(unwind) = unwind {
1614 span_mirbug!(self, block_data, "unwind on cleanup block")
1616 self.assert_iscleanup(mir, block_data, unwind, true);
1619 TerminatorKind::Call {
1624 if let &Some((_, target)) = destination {
1625 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1627 if let Some(cleanup) = cleanup {
1629 span_mirbug!(self, block_data, "cleanup on cleanup block")
1631 self.assert_iscleanup(mir, block_data, cleanup, true);
1634 TerminatorKind::FalseEdges {
1636 ref imaginary_targets,
1638 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1639 for target in imaginary_targets {
1640 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1643 TerminatorKind::FalseUnwind {
1647 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1648 if let Some(unwind) = unwind {
1653 "cleanup in cleanup block via false unwind"
1656 self.assert_iscleanup(mir, block_data, unwind, true);
1662 fn assert_iscleanup(
1665 ctxt: &dyn fmt::Debug,
1669 if mir[bb].is_cleanup != iscleanuppad {
1673 "cleanuppad mismatch: {:?} should be {:?}",
1680 fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1681 match mir.local_kind(local) {
1682 LocalKind::ReturnPointer | LocalKind::Arg => {
1683 // return values of normal functions are required to be
1684 // sized by typeck, but return values of ADT constructors are
1685 // not because we don't include a `Self: Sized` bounds on them.
1687 // Unbound parts of arguments were never required to be Sized
1688 // - maybe we should make that a warning.
1691 LocalKind::Var | LocalKind::Temp => {}
1694 // When `#![feature(unsized_locals)]` is enabled, only function calls
1695 // and nullary ops are checked in `check_call_dest`.
1696 if !self.tcx().features().unsized_locals {
1697 let span = local_decl.source_info.span;
1698 let ty = local_decl.ty;
1699 self.ensure_place_sized(ty, span);
1703 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1704 let tcx = self.tcx();
1706 // Erase the regions from `ty` to get a global type. The
1707 // `Sized` bound in no way depends on precise regions, so this
1708 // shouldn't affect `is_sized`.
1709 let gcx = tcx.global_tcx();
1710 let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1711 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1712 // in current MIR construction, all non-control-flow rvalue
1713 // expressions evaluate through `as_temp` or `into` a return
1714 // slot or local, so to find all unsized rvalues it is enough
1715 // to check all temps, return slots and locals.
1716 if let None = self.reported_errors.replace((ty, span)) {
1717 let mut diag = struct_span_err!(
1721 "cannot move a value of type {0}: the size of {0} \
1722 cannot be statically determined",
1726 // While this is located in `nll::typeck` this error is not
1727 // an NLL error, it's a required check to prevent creation
1728 // of unsized rvalues in certain cases:
1729 // * operand of a box expression
1730 // * callee in a call expression
1736 fn aggregate_field_ty(
1738 ak: &AggregateKind<'tcx>,
1741 ) -> Result<Ty<'tcx>, FieldAccessError> {
1742 let tcx = self.tcx();
1745 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1746 let variant = &def.variants[variant_index];
1747 let adj_field_index = active_field_index.unwrap_or(field_index);
1748 if let Some(field) = variant.fields.get(adj_field_index) {
1749 Ok(self.normalize(field.ty(tcx, substs), location))
1751 Err(FieldAccessError::OutOfRange {
1752 field_count: variant.fields.len(),
1756 AggregateKind::Closure(def_id, substs) => {
1757 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1759 None => Err(FieldAccessError::OutOfRange {
1760 field_count: substs.upvar_tys(def_id, tcx).count(),
1764 AggregateKind::Generator(def_id, substs, _) => {
1765 // Try pre-transform fields first (upvars and current state)
1766 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1769 // Then try `field_tys` which contains all the fields, but it
1770 // requires the final optimized MIR.
1771 match substs.field_tys(def_id, tcx).nth(field_index) {
1773 None => Err(FieldAccessError::OutOfRange {
1774 field_count: substs.field_tys(def_id, tcx).count(),
1779 AggregateKind::Array(ty) => Ok(ty),
1780 AggregateKind::Tuple => {
1781 unreachable!("This should have been covered in check_rvalues");
1786 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1787 let tcx = self.tcx();
1790 Rvalue::Aggregate(ak, ops) => {
1791 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1794 Rvalue::Repeat(operand, len) => if *len > 1 {
1795 let operand_ty = operand.ty(mir, tcx);
1797 let trait_ref = ty::TraitRef {
1798 def_id: tcx.lang_items().copy_trait().unwrap(),
1799 substs: tcx.mk_substs_trait(operand_ty, &[]),
1802 self.prove_trait_ref(
1804 location.to_locations(),
1805 ConstraintCategory::CopyBound,
1809 Rvalue::NullaryOp(_, ty) => {
1810 // Even with unsized locals cannot box an unsized value.
1811 if self.tcx().features().unsized_locals {
1812 let span = mir.source_info(location).span;
1813 self.ensure_place_sized(ty, span);
1816 let trait_ref = ty::TraitRef {
1817 def_id: tcx.lang_items().sized_trait().unwrap(),
1818 substs: tcx.mk_substs_trait(ty, &[]),
1821 self.prove_trait_ref(
1823 location.to_locations(),
1824 ConstraintCategory::SizedBound,
1828 Rvalue::Cast(cast_kind, op, ty) => {
1830 CastKind::ReifyFnPointer => {
1831 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1833 // The type that we see in the fcx is like
1834 // `foo::<'a, 'b>`, where `foo` is the path to a
1835 // function definition. When we extract the
1836 // signature, it comes from the `fn_sig` query,
1837 // and hence may contain unnormalized results.
1838 let fn_sig = self.normalize(fn_sig, location);
1840 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1842 if let Err(terr) = self.eq_types(
1845 location.to_locations(),
1846 ConstraintCategory::Cast,
1851 "equating {:?} with {:?} yields {:?}",
1859 CastKind::ClosureFnPointer => {
1860 let sig = match op.ty(mir, tcx).sty {
1861 ty::Closure(def_id, substs) => {
1862 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1866 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1868 if let Err(terr) = self.eq_types(
1871 location.to_locations(),
1872 ConstraintCategory::Cast,
1877 "equating {:?} with {:?} yields {:?}",
1885 CastKind::UnsafeFnPointer => {
1886 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1888 // The type that we see in the fcx is like
1889 // `foo::<'a, 'b>`, where `foo` is the path to a
1890 // function definition. When we extract the
1891 // signature, it comes from the `fn_sig` query,
1892 // and hence may contain unnormalized results.
1893 let fn_sig = self.normalize(fn_sig, location);
1895 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1897 if let Err(terr) = self.eq_types(
1900 location.to_locations(),
1901 ConstraintCategory::Cast,
1906 "equating {:?} with {:?} yields {:?}",
1914 CastKind::Unsize => {
1916 let trait_ref = ty::TraitRef {
1917 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1918 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1921 self.prove_trait_ref(
1923 location.to_locations(),
1924 ConstraintCategory::Cast,
1928 CastKind::Misc => {}
1932 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1933 self.add_reborrow_constraint(location, region, borrowed_place);
1936 // FIXME: These other cases have to be implemented in future PRs
1939 | Rvalue::BinaryOp(..)
1940 | Rvalue::CheckedBinaryOp(..)
1941 | Rvalue::UnaryOp(..)
1942 | Rvalue::Discriminant(..) => {}
1946 /// If this rvalue supports a user-given type annotation, then
1947 /// extract and return it. This represents the final type of the
1948 /// rvalue and will be unified with the inferred type.
1949 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotation<'tcx>> {
1952 | Rvalue::Repeat(..)
1956 | Rvalue::BinaryOp(..)
1957 | Rvalue::CheckedBinaryOp(..)
1958 | Rvalue::NullaryOp(..)
1959 | Rvalue::UnaryOp(..)
1960 | Rvalue::Discriminant(..) => None,
1962 Rvalue::Aggregate(aggregate, _) => match **aggregate {
1963 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
1964 AggregateKind::Array(_) => None,
1965 AggregateKind::Tuple => None,
1966 AggregateKind::Closure(_, _) => None,
1967 AggregateKind::Generator(_, _, _) => None,
1972 fn check_aggregate_rvalue(
1975 rvalue: &Rvalue<'tcx>,
1976 aggregate_kind: &AggregateKind<'tcx>,
1977 operands: &[Operand<'tcx>],
1980 let tcx = self.tcx();
1982 self.prove_aggregate_predicates(aggregate_kind, location);
1984 if *aggregate_kind == AggregateKind::Tuple {
1985 // tuple rvalue field type is always the type of the op. Nothing to check here.
1989 for (i, operand) in operands.iter().enumerate() {
1990 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
1991 Ok(field_ty) => field_ty,
1992 Err(FieldAccessError::OutOfRange { field_count }) => {
1996 "accessed field #{} but variant only has {}",
2003 let operand_ty = operand.ty(mir, tcx);
2005 if let Err(terr) = self.sub_types(
2008 location.to_locations(),
2009 ConstraintCategory::Boring,
2014 "{:?} is not a subtype of {:?}: {:?}",
2023 /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
2027 /// - `location`: the location `L` where the borrow expression occurs
2028 /// - `borrow_region`: the region `'a` associated with the borrow
2029 /// - `borrowed_place`: the place `P` being borrowed
2030 fn add_reborrow_constraint(
2033 borrow_region: ty::Region<'tcx>,
2034 borrowed_place: &Place<'tcx>,
2036 // These constraints are only meaningful during borrowck:
2037 let BorrowCheckContext {
2043 } = match self.borrowck_context {
2044 Some(ref mut borrowck_context) => borrowck_context,
2048 // In Polonius mode, we also push a `borrow_region` fact
2049 // linking the loan to the region (in some cases, though,
2050 // there is no loan associated with this borrow expression --
2051 // that occurs when we are borrowing an unsafe place, for
2053 if let Some(all_facts) = all_facts {
2054 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2055 let region_vid = borrow_region.to_region_vid();
2056 all_facts.borrow_region.push((
2059 location_table.mid_index(location),
2064 // If we are reborrowing the referent of another reference, we
2065 // need to add outlives relationships. In a case like `&mut
2066 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2067 // need to ensure that `'b: 'a`.
2069 let mut borrowed_place = borrowed_place;
2072 "add_reborrow_constraint({:?}, {:?}, {:?})",
2073 location, borrow_region, borrowed_place
2075 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2076 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2079 ProjectionElem::Deref => {
2080 let tcx = self.infcx.tcx;
2081 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
2083 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2085 ty::Ref(ref_region, _, mutbl) => {
2086 constraints.outlives_constraints.push(OutlivesConstraint {
2087 sup: ref_region.to_region_vid(),
2088 sub: borrow_region.to_region_vid(),
2089 locations: location.to_locations(),
2090 category: ConstraintCategory::Boring,
2094 hir::Mutability::MutImmutable => {
2095 // Immutable reference. We don't need the base
2096 // to be valid for the entire lifetime of
2100 hir::Mutability::MutMutable => {
2101 // Mutable reference. We *do* need the base
2102 // to be valid, because after the base becomes
2103 // invalid, someone else can use our mutable deref.
2105 // This is in order to make the following function
2108 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2113 // As otherwise you could clone `&mut T` using the
2114 // following function:
2116 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2117 // let my_clone = unsafe_deref(&'a x);
2126 // deref of raw pointer, guaranteed to be valid
2129 ty::Adt(def, _) if def.is_box() => {
2130 // deref of `Box`, need the base to be valid - propagate
2132 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2135 ProjectionElem::Field(..)
2136 | ProjectionElem::Downcast(..)
2137 | ProjectionElem::Index(..)
2138 | ProjectionElem::ConstantIndex { .. }
2139 | ProjectionElem::Subslice { .. } => {
2140 // other field access
2144 // The "propagate" case. We need to check that our base is valid
2145 // for the borrow's lifetime.
2146 borrowed_place = base;
2150 fn prove_aggregate_predicates(
2152 aggregate_kind: &AggregateKind<'tcx>,
2155 let tcx = self.tcx();
2158 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2159 aggregate_kind, location
2162 let instantiated_predicates = match aggregate_kind {
2163 AggregateKind::Adt(def, _, substs, _, _) => {
2164 tcx.predicates_of(def.did).instantiate(tcx, substs)
2167 // For closures, we have some **extra requirements** we
2169 // have to check. In particular, in their upvars and
2170 // signatures, closures often reference various regions
2171 // from the surrounding function -- we call those the
2172 // closure's free regions. When we borrow-check (and hence
2173 // region-check) closures, we may find that the closure
2174 // requires certain relationships between those free
2175 // regions. However, because those free regions refer to
2176 // portions of the CFG of their caller, the closure is not
2177 // in a position to verify those relationships. In that
2178 // case, the requirements get "propagated" to us, and so
2179 // we have to solve them here where we instantiate the
2182 // Despite the opacity of the previous parapgrah, this is
2183 // actually relatively easy to understand in terms of the
2184 // desugaring. A closure gets desugared to a struct, and
2185 // these extra requirements are basically like where
2186 // clauses on the struct.
2187 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2188 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2189 self.prove_closure_bounds(tcx, *def_id, substs, location)
2192 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2195 self.normalize_and_prove_instantiated_predicates(
2196 instantiated_predicates,
2197 location.to_locations(),
2201 fn prove_closure_bounds(
2203 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2205 substs: &'tcx Substs<'tcx>,
2207 ) -> ty::InstantiatedPredicates<'tcx> {
2208 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2209 let closure_constraints =
2210 closure_region_requirements.apply_requirements(tcx, location, def_id, substs);
2212 if let Some(ref mut borrowck_context) = self.borrowck_context {
2213 let bounds_mapping = closure_constraints
2216 .filter_map(|(idx, constraint)| {
2217 let ty::OutlivesPredicate(k1, r2) =
2218 constraint.no_bound_vars().unwrap_or_else(|| {
2219 bug!("query_constraint {:?} contained bound vars", constraint,);
2223 UnpackedKind::Lifetime(r1) => {
2224 // constraint is r1: r2
2225 let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
2226 let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
2227 let outlives_requirements =
2228 &closure_region_requirements.outlives_requirements[idx];
2232 outlives_requirements.category,
2233 outlives_requirements.blame_span,
2237 UnpackedKind::Type(_) => None,
2242 let existing = borrowck_context
2244 .closure_bounds_mapping
2245 .insert(location, bounds_mapping);
2248 "Multiple closures at the same location."
2252 self.push_region_constraints(
2253 location.to_locations(),
2254 ConstraintCategory::ClosureBounds,
2255 &closure_constraints,
2259 tcx.predicates_of(def_id).instantiate(tcx, substs)
2264 trait_ref: ty::TraitRef<'tcx>,
2265 locations: Locations,
2266 category: ConstraintCategory,
2268 self.prove_predicates(
2269 Some(ty::Predicate::Trait(
2270 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2277 fn normalize_and_prove_instantiated_predicates(
2279 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2280 locations: Locations,
2282 for predicate in instantiated_predicates.predicates {
2283 let predicate = self.normalize(predicate, locations);
2284 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2288 fn prove_predicates(
2290 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2291 locations: Locations,
2292 category: ConstraintCategory,
2294 for predicate in predicates {
2296 "prove_predicates(predicate={:?}, locations={:?})",
2297 predicate, locations,
2300 self.prove_predicate(predicate, locations, category);
2306 predicate: ty::Predicate<'tcx>,
2307 locations: Locations,
2308 category: ConstraintCategory,
2311 "prove_predicate(predicate={:?}, location={:?})",
2312 predicate, locations,
2315 let param_env = self.param_env;
2316 self.fully_perform_op(
2319 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2320 ).unwrap_or_else(|NoSolution| {
2321 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2325 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2326 self.last_span = mir.span;
2327 debug!("run_on_mir: {:?}", mir.span);
2329 for (local, local_decl) in mir.local_decls.iter_enumerated() {
2330 self.check_local(mir, local, local_decl);
2333 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2334 let mut location = Location {
2338 for stmt in &block_data.statements {
2339 if !stmt.source_info.span.is_dummy() {
2340 self.last_span = stmt.source_info.span;
2342 self.check_stmt(mir, stmt, location);
2343 location.statement_index += 1;
2346 self.check_terminator(mir, block_data.terminator(), location);
2347 self.check_iscleanup(mir, block_data);
2351 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2353 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2355 debug!("normalize(value={:?}, location={:?})", value, location);
2356 let param_env = self.param_env;
2357 self.fully_perform_op(
2358 location.to_locations(),
2359 ConstraintCategory::Boring,
2360 param_env.and(type_op::normalize::Normalize::new(value)),
2361 ).unwrap_or_else(|NoSolution| {
2362 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2368 pub struct TypeckMir;
2370 impl MirPass for TypeckMir {
2371 fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
2372 let def_id = src.def_id;
2373 debug!("run_pass: {:?}", def_id);
2375 // When NLL is enabled, the borrow checker runs the typeck
2376 // itself, so we don't need this MIR pass anymore.
2377 if tcx.use_mir_borrowck() {
2381 if tcx.sess.err_count() > 0 {
2382 // compiling a broken program can obviously result in a
2383 // broken MIR, so try not to report duplicate errors.
2387 if tcx.is_struct_constructor(def_id) {
2388 // We just assume that the automatically generated struct constructors are
2389 // correct. See the comment in the `mir_borrowck` implementation for an
2390 // explanation why we need this.
2394 let param_env = tcx.param_env(def_id);
2395 tcx.infer_ctxt().enter(|infcx| {
2396 type_check_internal(
2408 // For verification purposes, we just ignore the resulting
2409 // region constraint sets. Not our problem. =)
2414 trait NormalizeLocation: fmt::Debug + Copy {
2415 fn to_locations(self) -> Locations;
2418 impl NormalizeLocation for Locations {
2419 fn to_locations(self) -> Locations {
2424 impl NormalizeLocation for Location {
2425 fn to_locations(self) -> Locations {
2426 Locations::Single(self)
2430 #[derive(Debug, Default)]
2431 struct ObligationAccumulator<'tcx> {
2432 obligations: PredicateObligations<'tcx>,
2435 impl<'tcx> ObligationAccumulator<'tcx> {
2436 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2437 let InferOk { value, obligations } = value;
2438 self.obligations.extend(obligations);
2442 fn into_vec(self) -> PredicateObligations<'tcx> {