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::PlaceholderIndices;
20 use borrow_check::nll::region_infer::values::RegionValueElements;
21 use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
22 use borrow_check::nll::renumber;
23 use borrow_check::nll::type_check::free_region_relations::{
24 CreateResult, UniversalRegionRelations,
26 use borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
27 use borrow_check::nll::ToRegionVid;
28 use dataflow::move_paths::MoveData;
29 use dataflow::FlowAtLocation;
30 use dataflow::MaybeInitializedPlaces;
32 use rustc::hir::def_id::DefId;
33 use rustc::infer::canonical::QueryRegionConstraint;
34 use rustc::infer::outlives::env::RegionBoundPairs;
35 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
36 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
37 use rustc::mir::tcx::PlaceTy;
38 use rustc::mir::visit::{PlaceContext, Visitor};
40 use rustc::traits::query::type_op;
41 use rustc::traits::query::type_op::custom::CustomTypeOp;
42 use rustc::traits::query::{Fallible, NoSolution};
43 use rustc::traits::{ObligationCause, PredicateObligations};
44 use rustc::ty::fold::TypeFoldable;
45 use rustc::ty::subst::{Subst, Substs, UnpackedKind, UserSelfTy, UserSubsts};
46 use rustc::ty::{self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TyKind};
49 use syntax_pos::{Span, DUMMY_SP};
50 use transform::{MirPass, MirSource};
53 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
55 macro_rules! span_mirbug {
56 ($context:expr, $elem:expr, $($message:tt)*) => ({
57 $crate::borrow_check::nll::type_check::mirbug(
61 "broken MIR in {:?} ({:?}): {}",
64 format_args!($($message)*),
70 macro_rules! span_mirbug_and_err {
71 ($context:expr, $elem:expr, $($message:tt)*) => ({
73 span_mirbug!($context, $elem, $($message)*);
79 mod constraint_conversion;
80 pub mod free_region_relations;
85 /// Type checks the given `mir` in the context of the inference
86 /// context `infcx`. Returns any region constraints that have yet to
87 /// be proven. This result is includes liveness constraints that
88 /// ensure that regions appearing in the types of all local variables
89 /// are live at all points where that local variable may later be
92 /// This phase of type-check ought to be infallible -- this is because
93 /// the original, HIR-based type-check succeeded. So if any errors
94 /// occur here, we will get a `bug!` reported.
98 /// - `infcx` -- inference context to use
99 /// - `param_env` -- parameter environment to use for trait solving
100 /// - `mir` -- MIR to type-check
101 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
102 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
103 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
104 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
105 /// to outlive; should represent the fn body
106 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
107 /// the types of the input parameters found in the MIR itself will be equated with these
108 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
109 /// the type for the RETURN_PLACE will be equated with this
110 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
111 /// constraints for the regions in the types of variables
112 /// - `flow_inits` -- results of a maybe-init dataflow analysis
113 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysiss
114 pub(crate) fn type_check<'gcx, 'tcx>(
115 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
116 param_env: ty::ParamEnv<'gcx>,
119 universal_regions: &Rc<UniversalRegions<'tcx>>,
120 location_table: &LocationTable,
121 borrow_set: &BorrowSet<'tcx>,
122 all_facts: &mut Option<AllFacts>,
123 flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
124 move_data: &MoveData<'tcx>,
125 elements: &Rc<RegionValueElements>,
126 ) -> MirTypeckResults<'tcx> {
127 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
128 let mut constraints = MirTypeckRegionConstraints {
129 liveness_constraints: LivenessValues::new(elements),
130 outlives_constraints: ConstraintSet::default(),
131 closure_bounds_mapping: Default::default(),
132 type_tests: Vec::default(),
134 let mut placeholder_indices = PlaceholderIndices::default();
137 universal_region_relations,
139 normalized_inputs_and_output,
140 } = free_region_relations::create(
143 Some(implicit_region_bound),
148 let mut borrowck_context = BorrowCheckContext {
153 constraints: &mut constraints,
154 placeholder_indices: &mut placeholder_indices,
163 Some(implicit_region_bound),
164 Some(&mut borrowck_context),
165 Some(&universal_region_relations),
167 cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
168 liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
172 .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,
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 if let Some((user_ty, span)) = local_decl.user_ty {
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_regions() || 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::Projection(Mutability::Mut)
477 PlaceContext::Projection(Mutability::Not)
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::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>,
733 placeholder_indices: &'a mut PlaceholderIndices,
736 crate struct MirTypeckResults<'tcx> {
737 crate constraints: MirTypeckRegionConstraints<'tcx>,
738 crate placeholder_indices: PlaceholderIndices,
739 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
742 /// A collection of region constraints that must be satisfied for the
743 /// program to be considered well-typed.
744 crate struct MirTypeckRegionConstraints<'tcx> {
745 /// In general, the type-checker is not responsible for enforcing
746 /// liveness constraints; this job falls to the region inferencer,
747 /// which performs a liveness analysis. However, in some limited
748 /// cases, the MIR type-checker creates temporary regions that do
749 /// not otherwise appear in the MIR -- in particular, the
750 /// late-bound regions that it instantiates at call-sites -- and
751 /// hence it must report on their liveness constraints.
752 crate liveness_constraints: LivenessValues<RegionVid>,
754 crate outlives_constraints: ConstraintSet,
756 crate closure_bounds_mapping:
757 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
759 crate type_tests: Vec<TypeTest<'tcx>>,
762 /// The `Locations` type summarizes *where* region constraints are
763 /// required to hold. Normally, this is at a particular point which
764 /// created the obligation, but for constraints that the user gave, we
765 /// want the constraint to hold at all points.
766 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
768 /// Indicates that a type constraint should always be true. This
769 /// is particularly important in the new borrowck analysis for
770 /// things like the type of the return slot. Consider this
774 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
776 /// return &y; // error
780 /// Here, we wind up with the signature from the return type being
781 /// something like `&'1 u32` where `'1` is a universal region. But
782 /// the type of the return slot `_0` is something like `&'2 u32`
783 /// where `'2` is an existential region variable. The type checker
784 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
785 /// older NLL analysis, we required this only at the entry point
786 /// to the function. By the nature of the constraints, this wound
787 /// up propagating to all points reachable from start (because
788 /// `'1` -- as a universal region -- is live everywhere). In the
789 /// newer analysis, though, this doesn't work: `_0` is considered
790 /// dead at the start (it has no usable value) and hence this type
791 /// equality is basically a no-op. Then, later on, when we do `_0
792 /// = &'3 y`, that region `'3` never winds up related to the
793 /// universal region `'1` and hence no error occurs. Therefore, we
794 /// use Locations::All instead, which ensures that the `'1` and
795 /// `'2` are equal everything. We also use this for other
796 /// user-given type annotations; e.g., if the user wrote `let mut
797 /// x: &'static u32 = ...`, we would ensure that all values
798 /// assigned to `x` are of `'static` lifetime.
800 /// The span points to the place the constraint arose. For example,
801 /// it points to the type in a user-given type annotation. If
802 /// there's no sensible span then it's DUMMY_SP.
805 /// An outlives constraint that only has to hold at a single location,
806 /// usually it represents a point where references flow from one spot to
807 /// another (e.g., `x = y`)
812 pub fn from_location(&self) -> Option<Location> {
814 Locations::All(_) => None,
815 Locations::Single(from_location) => Some(*from_location),
819 /// Gets a span representing the location.
820 pub fn span(&self, mir: &Mir<'_>) -> Span {
822 Locations::All(span) => *span,
823 Locations::Single(l) => mir.source_info(*l).span,
828 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
830 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
833 param_env: ty::ParamEnv<'gcx>,
834 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
835 implicit_region_bound: Option<ty::Region<'tcx>>,
836 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
837 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
846 implicit_region_bound,
848 reported_errors: Default::default(),
849 universal_region_relations,
853 /// Given some operation `op` that manipulates types, proves
854 /// predicates, or otherwise uses the inference context, executes
855 /// `op` and then executes all the further obligations that `op`
856 /// returns. This will yield a set of outlives constraints amongst
857 /// regions which are extracted and stored as having occurred at
860 /// **Any `rustc::infer` operations that might generate region
861 /// constraints should occur within this method so that those
862 /// constraints can be properly localized!**
863 fn fully_perform_op<R>(
865 locations: Locations,
866 category: ConstraintCategory,
867 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
869 let (r, opt_data) = op.fully_perform(self.infcx)?;
871 if let Some(data) = &opt_data {
872 self.push_region_constraints(locations, category, data);
878 fn push_region_constraints(
880 locations: Locations,
881 category: ConstraintCategory,
882 data: &[QueryRegionConstraint<'tcx>],
885 "push_region_constraints: constraints generated at {:?} are {:#?}",
889 if let Some(ref mut borrowck_context) = self.borrowck_context {
890 constraint_conversion::ConstraintConversion::new(
892 borrowck_context.universal_regions,
893 self.region_bound_pairs,
894 self.implicit_region_bound,
898 &mut borrowck_context.constraints.outlives_constraints,
899 &mut borrowck_context.constraints.type_tests,
900 ).convert_all(&data);
904 /// Convenient wrapper around `relate_tys::relate_types` -- see
905 /// that fn for docs.
911 locations: Locations,
912 category: ConstraintCategory,
914 relate_tys::relate_types(
921 self.borrowck_context.as_mut().map(|x| &mut **x),
929 locations: Locations,
930 category: ConstraintCategory,
932 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
935 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
936 /// variables in `sub` with their inferred definitions and try
937 /// again. This is used for opaque types in places (e.g., `let x:
939 fn sub_types_or_anon(
943 locations: Locations,
944 category: ConstraintCategory,
946 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
947 if let TyKind::Opaque(..) = sup.sty {
948 // When you have `let x: impl Foo = ...` in a closure,
949 // the resulting inferend values are stored with the
950 // def-id of the base function.
951 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
952 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
964 locations: Locations,
965 category: ConstraintCategory,
967 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
970 fn relate_type_and_user_type(
974 user_ty: UserTypeAnnotation<'tcx>,
975 locations: Locations,
976 category: ConstraintCategory,
978 let tcx = self.tcx();
981 "relate_type_and_user_type(a={:?}, v={:?}, b={:?}, locations={:?})",
982 a, v, user_ty, locations
985 // The `TypeRelating` code assumes that "unresolved inference
986 // variables" appear in the "a" side, so flip `Contravariant`
987 // ambient variance to get the right relationship.
988 let v1 = ty::Contravariant.xform(v);
991 UserTypeAnnotation::Ty(canonical_ty) => {
992 let (ty, _) = self.infcx
993 .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_ty);
995 self.relate_types(ty, v1, a, locations, category)?;
997 self.prove_predicate(ty::Predicate::WellFormed(ty), locations, category);
999 UserTypeAnnotation::TypeOf(def_id, canonical_substs) => {
1007 .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
1009 let ty = self.tcx().type_of(def_id);
1010 let ty = ty.subst(tcx, substs);
1011 let ty = self.normalize(ty, locations);
1013 self.relate_types(ty, v1, a, locations, category)?;
1015 if let Some(UserSelfTy {
1020 let impl_self_ty = tcx.type_of(impl_def_id);
1021 let impl_self_ty = impl_self_ty.subst(tcx, &substs);
1022 let impl_self_ty = self.normalize(impl_self_ty, locations);
1024 // There may be type variables in `substs` and hence
1025 // in `impl_self_ty`, but they should all have been
1026 // resolved to some fixed value during the first call
1027 // to `relate`, above. Therefore, if we use
1028 // `resolve_type_vars_if_possible` we should get to
1029 // something without type variables. This is important
1030 // because the `b` type in `relate_with_variance`
1031 // below is not permitted to have inference variables.
1032 let impl_self_ty = self.infcx.resolve_type_vars_if_possible(&impl_self_ty);
1033 assert!(!impl_self_ty.has_infer_types());
1035 self.eq_types(self_ty, impl_self_ty, locations, category)?;
1037 self.prove_predicate(
1038 ty::Predicate::WellFormed(impl_self_ty),
1044 // Prove the predicates coming along with `def_id`.
1046 // Also, normalize the `instantiated_predicates`
1047 // because otherwise we wind up with duplicate "type
1048 // outlives" error messages.
1049 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
1050 let instantiated_predicates = self.fold_to_region_vid(instantiated_predicates);
1051 self.normalize_and_prove_instantiated_predicates(
1052 instantiated_predicates,
1056 // In addition to proving the predicates, we have to
1057 // prove that `ty` is well-formed -- this is because
1058 // the WF of `ty` is predicated on the substs being
1059 // well-formed, and we haven't proven *that*. We don't
1060 // want to prove the WF of types from `substs` directly because they
1061 // haven't been normalized.
1063 // FIXME(nmatsakis): Well, perhaps we should normalize
1064 // them? This would only be relevant if some input
1065 // type were ill-formed but did not appear in `ty`,
1066 // which...could happen with normalization...
1067 self.prove_predicate(ty::Predicate::WellFormed(ty), locations, category);
1074 /// Replace all free regions in `value` with their NLL `RegionVid`
1075 /// equivalents; if not in NLL, does nothing. This is never
1076 /// particularly necessary -- we'll do it lazilly as we process
1077 /// the value anyway -- but in some specific cases it is useful to
1078 /// normalize so we can suppress duplicate error messages.
1079 fn fold_to_region_vid<T>(&self, value: T) -> T
1081 T: TypeFoldable<'tcx>,
1083 if let Some(borrowck_context) = &self.borrowck_context {
1084 self.tcx().fold_regions(&value, &mut false, |r, _debruijn| {
1085 if r.has_free_regions() {
1086 self.tcx().mk_region(ty::RegionKind::ReVar(
1087 borrowck_context.universal_regions.to_region_vid(r),
1098 fn eq_opaque_type_and_type(
1100 revealed_ty: Ty<'tcx>,
1102 anon_owner_def_id: DefId,
1103 locations: Locations,
1104 category: ConstraintCategory,
1107 "eq_opaque_type_and_type( \
1110 revealed_ty, anon_ty
1112 let infcx = self.infcx;
1113 let tcx = infcx.tcx;
1114 let param_env = self.param_env;
1115 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1116 let opaque_type_map = self.fully_perform_op(
1121 let mut obligations = ObligationAccumulator::default();
1123 let dummy_body_id = ObligationCause::dummy().body_id;
1124 let (output_ty, opaque_type_map) =
1125 obligations.add(infcx.instantiate_opaque_types(
1132 "eq_opaque_type_and_type: \
1133 instantiated output_ty={:?} \
1134 opaque_type_map={:#?} \
1136 output_ty, opaque_type_map, revealed_ty
1138 obligations.add(infcx
1139 .at(&ObligationCause::dummy(), param_env)
1140 .eq(output_ty, revealed_ty)?);
1142 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1143 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1144 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1145 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1147 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1148 opaque_decl.concrete_ty,
1149 infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1152 obligations.add(infcx
1153 .at(&ObligationCause::dummy(), param_env)
1154 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1157 debug!("eq_opaque_type_and_type: equated");
1160 value: Some(opaque_type_map),
1161 obligations: obligations.into_vec(),
1164 || "input_output".to_string(),
1168 let universal_region_relations = match self.universal_region_relations {
1170 None => return Ok(()),
1173 // Finally, if we instantiated the anon types successfully, we
1174 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1175 // prove that `T: Iterator` where `T` is the type we
1176 // instantiated it with).
1177 if let Some(opaque_type_map) = opaque_type_map {
1178 for (opaque_def_id, opaque_decl) in opaque_type_map {
1179 self.fully_perform_op(
1181 ConstraintCategory::OpaqueType,
1184 infcx.constrain_opaque_type(
1187 universal_region_relations,
1191 obligations: vec![],
1194 || "opaque_type_map".to_string(),
1202 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1206 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1207 debug!("check_stmt: {:?}", stmt);
1208 let tcx = self.tcx();
1210 StatementKind::Assign(ref place, ref rv) => {
1211 // Assignments to temporaries are not "interesting";
1212 // they are not caused by the user, but rather artifacts
1213 // of lowering. Assignments to other sorts of places *are* interesting
1215 let category = match *place {
1216 Place::Local(RETURN_PLACE) => if let Some(BorrowCheckContext {
1219 defining_ty: DefiningTy::Const(def_id, _),
1223 }) = self.borrowck_context
1225 if tcx.is_static(*def_id).is_some() {
1226 ConstraintCategory::UseAsStatic
1228 ConstraintCategory::UseAsConst
1231 ConstraintCategory::Return
1233 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1234 ConstraintCategory::Boring
1236 _ => ConstraintCategory::Assignment,
1239 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1240 let rv_ty = rv.ty(mir, tcx);
1242 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1247 "bad assignment ({:?} = {:?}): {:?}",
1254 if let Some(user_ty) = self.rvalue_user_ty(rv) {
1255 if let Err(terr) = self.relate_type_and_user_type(
1257 ty::Variance::Invariant,
1259 location.to_locations(),
1260 ConstraintCategory::Boring,
1265 "bad user type on rvalue ({:?} = {:?}): {:?}",
1273 self.check_rvalue(mir, rv, location);
1274 if !self.tcx().features().unsized_locals {
1275 let trait_ref = ty::TraitRef {
1276 def_id: tcx.lang_items().sized_trait().unwrap(),
1277 substs: tcx.mk_substs_trait(place_ty, &[]),
1279 self.prove_trait_ref(
1281 location.to_locations(),
1282 ConstraintCategory::SizedBound,
1286 StatementKind::SetDiscriminant {
1290 let place_type = place.ty(mir, tcx).to_ty(tcx);
1291 let adt = match place_type.sty {
1292 TyKind::Adt(adt, _) if adt.is_enum() => adt,
1295 stmt.source_info.span,
1296 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1302 if variant_index >= adt.variants.len() {
1304 stmt.source_info.span,
1305 "bad set discriminant ({:?} = {:?}): value of of range",
1311 StatementKind::AscribeUserType(ref place, variance, c_ty) => {
1312 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1313 if let Err(terr) = self.relate_type_and_user_type(
1317 Locations::All(stmt.source_info.span),
1318 ConstraintCategory::TypeAnnotation,
1323 "bad type assert ({:?} <: {:?}): {:?}",
1330 StatementKind::FakeRead(..)
1331 | StatementKind::StorageLive(_)
1332 | StatementKind::StorageDead(_)
1333 | StatementKind::InlineAsm { .. }
1334 | StatementKind::EndRegion(_)
1335 | StatementKind::Validate(..)
1336 | StatementKind::Nop => {}
1340 fn check_terminator(
1343 term: &Terminator<'tcx>,
1344 term_location: Location,
1346 debug!("check_terminator: {:?}", term);
1347 let tcx = self.tcx();
1349 TerminatorKind::Goto { .. }
1350 | TerminatorKind::Resume
1351 | TerminatorKind::Abort
1352 | TerminatorKind::Return
1353 | TerminatorKind::GeneratorDrop
1354 | TerminatorKind::Unreachable
1355 | TerminatorKind::Drop { .. }
1356 | TerminatorKind::FalseEdges { .. }
1357 | TerminatorKind::FalseUnwind { .. } => {
1358 // no checks needed for these
1361 TerminatorKind::DropAndReplace {
1367 let place_ty = location.ty(mir, tcx).to_ty(tcx);
1368 let rv_ty = value.ty(mir, tcx);
1370 let locations = term_location.to_locations();
1372 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1377 "bad DropAndReplace ({:?} = {:?}): {:?}",
1384 TerminatorKind::SwitchInt {
1389 let discr_ty = discr.ty(mir, tcx);
1390 if let Err(terr) = self.sub_types(
1393 term_location.to_locations(),
1394 ConstraintCategory::Assignment,
1399 "bad SwitchInt ({:?} on {:?}): {:?}",
1405 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1406 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1408 // FIXME: check the values
1410 TerminatorKind::Call {
1417 let func_ty = func.ty(mir, tcx);
1418 debug!("check_terminator: call, func_ty={:?}", func_ty);
1419 let sig = match func_ty.sty {
1420 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1422 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1426 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
1427 term.source_info.span,
1428 LateBoundRegionConversionTime::FnCall,
1431 let sig = self.normalize(sig, term_location);
1432 self.check_call_dest(mir, term, &sig, destination, term_location);
1434 self.prove_predicates(
1435 sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1436 term_location.to_locations(),
1437 ConstraintCategory::Boring,
1440 // The ordinary liveness rules will ensure that all
1441 // regions in the type of the callee are live here. We
1442 // then further constrain the late-bound regions that
1443 // were instantiated at the call site to be live as
1444 // well. The resulting is that all the input (and
1445 // output) types in the signature must be live, since
1446 // all the inputs that fed into it were live.
1447 for &late_bound_region in map.values() {
1448 if let Some(ref mut borrowck_context) = self.borrowck_context {
1449 let region_vid = borrowck_context
1451 .to_region_vid(late_bound_region);
1454 .liveness_constraints
1455 .add_element(region_vid, term_location);
1459 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1461 TerminatorKind::Assert {
1462 ref cond, ref msg, ..
1464 let cond_ty = cond.ty(mir, tcx);
1465 if cond_ty != tcx.types.bool {
1466 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1469 if let BoundsCheck { ref len, ref index } = *msg {
1470 if len.ty(mir, tcx) != tcx.types.usize {
1471 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1473 if index.ty(mir, tcx) != tcx.types.usize {
1474 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1478 TerminatorKind::Yield { ref value, .. } => {
1479 let value_ty = value.ty(mir, tcx);
1480 match mir.yield_ty {
1481 None => span_mirbug!(self, term, "yield in non-generator"),
1483 if let Err(terr) = self.sub_types(
1486 term_location.to_locations(),
1487 ConstraintCategory::Return,
1492 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1507 term: &Terminator<'tcx>,
1508 sig: &ty::FnSig<'tcx>,
1509 destination: &Option<(Place<'tcx>, BasicBlock)>,
1510 term_location: Location,
1512 let tcx = self.tcx();
1513 match *destination {
1514 Some((ref dest, _target_block)) => {
1515 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1516 let category = match *dest {
1517 Place::Local(RETURN_PLACE) => {
1518 if let Some(BorrowCheckContext {
1521 defining_ty: DefiningTy::Const(def_id, _),
1525 }) = self.borrowck_context
1527 if tcx.is_static(*def_id).is_some() {
1528 ConstraintCategory::UseAsStatic
1530 ConstraintCategory::UseAsConst
1533 ConstraintCategory::Return
1536 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1537 ConstraintCategory::Boring
1539 _ => ConstraintCategory::Assignment,
1542 let locations = term_location.to_locations();
1545 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1550 "call dest mismatch ({:?} <- {:?}): {:?}",
1557 // When `#![feature(unsized_locals)]` is not enabled,
1558 // this check is done at `check_local`.
1559 if self.tcx().features().unsized_locals {
1560 let span = term.source_info.span;
1561 self.ensure_place_sized(dest_ty, span);
1565 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1566 if !sig.output().is_never() {
1567 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1573 fn check_call_inputs(
1576 term: &Terminator<'tcx>,
1577 sig: &ty::FnSig<'tcx>,
1578 args: &[Operand<'tcx>],
1579 term_location: Location,
1580 from_hir_call: bool,
1582 debug!("check_call_inputs({:?}, {:?})", sig, args);
1583 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1584 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1586 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1587 let op_arg_ty = op_arg.ty(mir, self.tcx());
1588 let category = if from_hir_call {
1589 ConstraintCategory::CallArgument
1591 ConstraintCategory::Boring
1594 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1599 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1609 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1610 let is_cleanup = block_data.is_cleanup;
1611 self.last_span = block_data.terminator().source_info.span;
1612 match block_data.terminator().kind {
1613 TerminatorKind::Goto { target } => {
1614 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1616 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1617 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1619 TerminatorKind::Resume => if !is_cleanup {
1620 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1622 TerminatorKind::Abort => if !is_cleanup {
1623 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1625 TerminatorKind::Return => if is_cleanup {
1626 span_mirbug!(self, block_data, "return on cleanup block")
1628 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1629 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1631 TerminatorKind::Yield { resume, drop, .. } => {
1633 span_mirbug!(self, block_data, "yield in cleanup block")
1635 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1636 if let Some(drop) = drop {
1637 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1640 TerminatorKind::Unreachable => {}
1641 TerminatorKind::Drop { target, unwind, .. }
1642 | TerminatorKind::DropAndReplace { target, unwind, .. }
1643 | TerminatorKind::Assert {
1648 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1649 if let Some(unwind) = unwind {
1651 span_mirbug!(self, block_data, "unwind on cleanup block")
1653 self.assert_iscleanup(mir, block_data, unwind, true);
1656 TerminatorKind::Call {
1661 if let &Some((_, target)) = destination {
1662 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1664 if let Some(cleanup) = cleanup {
1666 span_mirbug!(self, block_data, "cleanup on cleanup block")
1668 self.assert_iscleanup(mir, block_data, cleanup, true);
1671 TerminatorKind::FalseEdges {
1673 ref imaginary_targets,
1675 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1676 for target in imaginary_targets {
1677 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1680 TerminatorKind::FalseUnwind {
1684 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1685 if let Some(unwind) = unwind {
1690 "cleanup in cleanup block via false unwind"
1693 self.assert_iscleanup(mir, block_data, unwind, true);
1699 fn assert_iscleanup(
1702 ctxt: &dyn fmt::Debug,
1706 if mir[bb].is_cleanup != iscleanuppad {
1710 "cleanuppad mismatch: {:?} should be {:?}",
1717 fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1718 match mir.local_kind(local) {
1719 LocalKind::ReturnPointer | LocalKind::Arg => {
1720 // return values of normal functions are required to be
1721 // sized by typeck, but return values of ADT constructors are
1722 // not because we don't include a `Self: Sized` bounds on them.
1724 // Unbound parts of arguments were never required to be Sized
1725 // - maybe we should make that a warning.
1728 LocalKind::Var | LocalKind::Temp => {}
1731 // When `#![feature(unsized_locals)]` is enabled, only function calls
1732 // and nullary ops are checked in `check_call_dest`.
1733 if !self.tcx().features().unsized_locals {
1734 let span = local_decl.source_info.span;
1735 let ty = local_decl.ty;
1736 self.ensure_place_sized(ty, span);
1740 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1741 let tcx = self.tcx();
1743 // Erase the regions from `ty` to get a global type. The
1744 // `Sized` bound in no way depends on precise regions, so this
1745 // shouldn't affect `is_sized`.
1746 let gcx = tcx.global_tcx();
1747 let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1748 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1749 // in current MIR construction, all non-control-flow rvalue
1750 // expressions evaluate through `as_temp` or `into` a return
1751 // slot or local, so to find all unsized rvalues it is enough
1752 // to check all temps, return slots and locals.
1753 if let None = self.reported_errors.replace((ty, span)) {
1754 let mut diag = struct_span_err!(
1758 "cannot move a value of type {0}: the size of {0} \
1759 cannot be statically determined",
1763 // While this is located in `nll::typeck` this error is not
1764 // an NLL error, it's a required check to prevent creation
1765 // of unsized rvalues in certain cases:
1766 // * operand of a box expression
1767 // * callee in a call expression
1773 fn aggregate_field_ty(
1775 ak: &AggregateKind<'tcx>,
1778 ) -> Result<Ty<'tcx>, FieldAccessError> {
1779 let tcx = self.tcx();
1782 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1783 let variant = &def.variants[variant_index];
1784 let adj_field_index = active_field_index.unwrap_or(field_index);
1785 if let Some(field) = variant.fields.get(adj_field_index) {
1786 Ok(self.normalize(field.ty(tcx, substs), location))
1788 Err(FieldAccessError::OutOfRange {
1789 field_count: variant.fields.len(),
1793 AggregateKind::Closure(def_id, substs) => {
1794 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1796 None => Err(FieldAccessError::OutOfRange {
1797 field_count: substs.upvar_tys(def_id, tcx).count(),
1801 AggregateKind::Generator(def_id, substs, _) => {
1802 // Try pre-transform fields first (upvars and current state)
1803 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1806 // Then try `field_tys` which contains all the fields, but it
1807 // requires the final optimized MIR.
1808 match substs.field_tys(def_id, tcx).nth(field_index) {
1810 None => Err(FieldAccessError::OutOfRange {
1811 field_count: substs.field_tys(def_id, tcx).count(),
1816 AggregateKind::Array(ty) => Ok(ty),
1817 AggregateKind::Tuple => {
1818 unreachable!("This should have been covered in check_rvalues");
1823 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1824 let tcx = self.tcx();
1827 Rvalue::Aggregate(ak, ops) => {
1828 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1831 Rvalue::Repeat(operand, len) => if *len > 1 {
1832 let operand_ty = operand.ty(mir, tcx);
1834 let trait_ref = ty::TraitRef {
1835 def_id: tcx.lang_items().copy_trait().unwrap(),
1836 substs: tcx.mk_substs_trait(operand_ty, &[]),
1839 self.prove_trait_ref(
1841 location.to_locations(),
1842 ConstraintCategory::CopyBound,
1846 Rvalue::NullaryOp(_, ty) => {
1847 // Even with unsized locals cannot box an unsized value.
1848 if self.tcx().features().unsized_locals {
1849 let span = mir.source_info(location).span;
1850 self.ensure_place_sized(ty, span);
1853 let trait_ref = ty::TraitRef {
1854 def_id: tcx.lang_items().sized_trait().unwrap(),
1855 substs: tcx.mk_substs_trait(ty, &[]),
1858 self.prove_trait_ref(
1860 location.to_locations(),
1861 ConstraintCategory::SizedBound,
1865 Rvalue::Cast(cast_kind, op, ty) => {
1867 CastKind::ReifyFnPointer => {
1868 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1870 // The type that we see in the fcx is like
1871 // `foo::<'a, 'b>`, where `foo` is the path to a
1872 // function definition. When we extract the
1873 // signature, it comes from the `fn_sig` query,
1874 // and hence may contain unnormalized results.
1875 let fn_sig = self.normalize(fn_sig, location);
1877 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1879 if let Err(terr) = self.eq_types(
1882 location.to_locations(),
1883 ConstraintCategory::Cast,
1888 "equating {:?} with {:?} yields {:?}",
1896 CastKind::ClosureFnPointer => {
1897 let sig = match op.ty(mir, tcx).sty {
1898 ty::Closure(def_id, substs) => {
1899 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1903 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1905 if let Err(terr) = self.eq_types(
1908 location.to_locations(),
1909 ConstraintCategory::Cast,
1914 "equating {:?} with {:?} yields {:?}",
1922 CastKind::UnsafeFnPointer => {
1923 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1925 // The type that we see in the fcx is like
1926 // `foo::<'a, 'b>`, where `foo` is the path to a
1927 // function definition. When we extract the
1928 // signature, it comes from the `fn_sig` query,
1929 // and hence may contain unnormalized results.
1930 let fn_sig = self.normalize(fn_sig, location);
1932 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1934 if let Err(terr) = self.eq_types(
1937 location.to_locations(),
1938 ConstraintCategory::Cast,
1943 "equating {:?} with {:?} yields {:?}",
1951 CastKind::Unsize => {
1953 let trait_ref = ty::TraitRef {
1954 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1955 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1958 self.prove_trait_ref(
1960 location.to_locations(),
1961 ConstraintCategory::Cast,
1965 CastKind::Misc => {}
1969 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1970 self.add_reborrow_constraint(location, region, borrowed_place);
1973 // FIXME: These other cases have to be implemented in future PRs
1976 | Rvalue::BinaryOp(..)
1977 | Rvalue::CheckedBinaryOp(..)
1978 | Rvalue::UnaryOp(..)
1979 | Rvalue::Discriminant(..) => {}
1983 /// If this rvalue supports a user-given type annotation, then
1984 /// extract and return it. This represents the final type of the
1985 /// rvalue and will be unified with the inferred type.
1986 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotation<'tcx>> {
1989 | Rvalue::Repeat(..)
1993 | Rvalue::BinaryOp(..)
1994 | Rvalue::CheckedBinaryOp(..)
1995 | Rvalue::NullaryOp(..)
1996 | Rvalue::UnaryOp(..)
1997 | Rvalue::Discriminant(..) => None,
1999 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2000 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2001 AggregateKind::Array(_) => None,
2002 AggregateKind::Tuple => None,
2003 AggregateKind::Closure(_, _) => None,
2004 AggregateKind::Generator(_, _, _) => None,
2009 fn check_aggregate_rvalue(
2012 rvalue: &Rvalue<'tcx>,
2013 aggregate_kind: &AggregateKind<'tcx>,
2014 operands: &[Operand<'tcx>],
2017 let tcx = self.tcx();
2019 self.prove_aggregate_predicates(aggregate_kind, location);
2021 if *aggregate_kind == AggregateKind::Tuple {
2022 // tuple rvalue field type is always the type of the op. Nothing to check here.
2026 for (i, operand) in operands.iter().enumerate() {
2027 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2028 Ok(field_ty) => field_ty,
2029 Err(FieldAccessError::OutOfRange { field_count }) => {
2033 "accessed field #{} but variant only has {}",
2040 let operand_ty = operand.ty(mir, tcx);
2042 if let Err(terr) = self.sub_types(
2045 location.to_locations(),
2046 ConstraintCategory::Boring,
2051 "{:?} is not a subtype of {:?}: {:?}",
2060 /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
2064 /// - `location`: the location `L` where the borrow expression occurs
2065 /// - `borrow_region`: the region `'a` associated with the borrow
2066 /// - `borrowed_place`: the place `P` being borrowed
2067 fn add_reborrow_constraint(
2070 borrow_region: ty::Region<'tcx>,
2071 borrowed_place: &Place<'tcx>,
2073 // These constraints are only meaningful during borrowck:
2074 let BorrowCheckContext {
2080 } = match self.borrowck_context {
2081 Some(ref mut borrowck_context) => borrowck_context,
2085 // In Polonius mode, we also push a `borrow_region` fact
2086 // linking the loan to the region (in some cases, though,
2087 // there is no loan associated with this borrow expression --
2088 // that occurs when we are borrowing an unsafe place, for
2090 if let Some(all_facts) = all_facts {
2091 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2092 let region_vid = borrow_region.to_region_vid();
2093 all_facts.borrow_region.push((
2096 location_table.mid_index(location),
2101 // If we are reborrowing the referent of another reference, we
2102 // need to add outlives relationships. In a case like `&mut
2103 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2104 // need to ensure that `'b: 'a`.
2106 let mut borrowed_place = borrowed_place;
2109 "add_reborrow_constraint({:?}, {:?}, {:?})",
2110 location, borrow_region, borrowed_place
2112 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2113 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2116 ProjectionElem::Deref => {
2117 let tcx = self.infcx.tcx;
2118 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
2120 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2122 ty::Ref(ref_region, _, mutbl) => {
2123 constraints.outlives_constraints.push(OutlivesConstraint {
2124 sup: ref_region.to_region_vid(),
2125 sub: borrow_region.to_region_vid(),
2126 locations: location.to_locations(),
2127 category: ConstraintCategory::Boring,
2131 hir::Mutability::MutImmutable => {
2132 // Immutable reference. We don't need the base
2133 // to be valid for the entire lifetime of
2137 hir::Mutability::MutMutable => {
2138 // Mutable reference. We *do* need the base
2139 // to be valid, because after the base becomes
2140 // invalid, someone else can use our mutable deref.
2142 // This is in order to make the following function
2145 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2150 // As otherwise you could clone `&mut T` using the
2151 // following function:
2153 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2154 // let my_clone = unsafe_deref(&'a x);
2163 // deref of raw pointer, guaranteed to be valid
2166 ty::Adt(def, _) if def.is_box() => {
2167 // deref of `Box`, need the base to be valid - propagate
2169 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2172 ProjectionElem::Field(..)
2173 | ProjectionElem::Downcast(..)
2174 | ProjectionElem::Index(..)
2175 | ProjectionElem::ConstantIndex { .. }
2176 | ProjectionElem::Subslice { .. } => {
2177 // other field access
2181 // The "propagate" case. We need to check that our base is valid
2182 // for the borrow's lifetime.
2183 borrowed_place = base;
2187 fn prove_aggregate_predicates(
2189 aggregate_kind: &AggregateKind<'tcx>,
2192 let tcx = self.tcx();
2195 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2196 aggregate_kind, location
2199 let instantiated_predicates = match aggregate_kind {
2200 AggregateKind::Adt(def, _, substs, _, _) => {
2201 tcx.predicates_of(def.did).instantiate(tcx, substs)
2204 // For closures, we have some **extra requirements** we
2206 // have to check. In particular, in their upvars and
2207 // signatures, closures often reference various regions
2208 // from the surrounding function -- we call those the
2209 // closure's free regions. When we borrow-check (and hence
2210 // region-check) closures, we may find that the closure
2211 // requires certain relationships between those free
2212 // regions. However, because those free regions refer to
2213 // portions of the CFG of their caller, the closure is not
2214 // in a position to verify those relationships. In that
2215 // case, the requirements get "propagated" to us, and so
2216 // we have to solve them here where we instantiate the
2219 // Despite the opacity of the previous parapgrah, this is
2220 // actually relatively easy to understand in terms of the
2221 // desugaring. A closure gets desugared to a struct, and
2222 // these extra requirements are basically like where
2223 // clauses on the struct.
2224 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2225 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2226 self.prove_closure_bounds(tcx, *def_id, substs, location)
2229 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2232 self.normalize_and_prove_instantiated_predicates(
2233 instantiated_predicates,
2234 location.to_locations(),
2238 fn prove_closure_bounds(
2240 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2242 substs: &'tcx Substs<'tcx>,
2244 ) -> ty::InstantiatedPredicates<'tcx> {
2245 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2246 let closure_constraints =
2247 closure_region_requirements.apply_requirements(tcx, location, def_id, substs);
2249 if let Some(ref mut borrowck_context) = self.borrowck_context {
2250 let bounds_mapping = closure_constraints
2253 .filter_map(|(idx, constraint)| {
2254 let ty::OutlivesPredicate(k1, r2) =
2255 constraint.no_late_bound_regions().unwrap_or_else(|| {
2256 bug!("query_constraint {:?} contained bound regions", constraint,);
2260 UnpackedKind::Lifetime(r1) => {
2261 // constraint is r1: r2
2262 let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
2263 let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
2264 let outlives_requirements =
2265 &closure_region_requirements.outlives_requirements[idx];
2269 outlives_requirements.category,
2270 outlives_requirements.blame_span,
2274 UnpackedKind::Type(_) => None,
2279 let existing = borrowck_context
2281 .closure_bounds_mapping
2282 .insert(location, bounds_mapping);
2285 "Multiple closures at the same location."
2289 self.push_region_constraints(
2290 location.to_locations(),
2291 ConstraintCategory::ClosureBounds,
2292 &closure_constraints,
2296 tcx.predicates_of(def_id).instantiate(tcx, substs)
2301 trait_ref: ty::TraitRef<'tcx>,
2302 locations: Locations,
2303 category: ConstraintCategory,
2305 self.prove_predicates(
2306 Some(ty::Predicate::Trait(
2307 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2314 fn normalize_and_prove_instantiated_predicates(
2316 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2317 locations: Locations,
2319 for predicate in instantiated_predicates.predicates {
2320 let predicate = self.normalize(predicate, locations);
2321 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2325 fn prove_predicates(
2327 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2328 locations: Locations,
2329 category: ConstraintCategory,
2331 for predicate in predicates {
2333 "prove_predicates(predicate={:?}, locations={:?})",
2334 predicate, locations,
2337 self.prove_predicate(predicate, locations, category);
2343 predicate: ty::Predicate<'tcx>,
2344 locations: Locations,
2345 category: ConstraintCategory,
2348 "prove_predicate(predicate={:?}, location={:?})",
2349 predicate, locations,
2352 let param_env = self.param_env;
2353 self.fully_perform_op(
2356 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2357 ).unwrap_or_else(|NoSolution| {
2358 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2362 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2363 self.last_span = mir.span;
2364 debug!("run_on_mir: {:?}", mir.span);
2366 for (local, local_decl) in mir.local_decls.iter_enumerated() {
2367 self.check_local(mir, local, local_decl);
2370 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2371 let mut location = Location {
2375 for stmt in &block_data.statements {
2376 if !stmt.source_info.span.is_dummy() {
2377 self.last_span = stmt.source_info.span;
2379 self.check_stmt(mir, stmt, location);
2380 location.statement_index += 1;
2383 self.check_terminator(mir, block_data.terminator(), location);
2384 self.check_iscleanup(mir, block_data);
2388 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2390 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2392 debug!("normalize(value={:?}, location={:?})", value, location);
2393 let param_env = self.param_env;
2394 self.fully_perform_op(
2395 location.to_locations(),
2396 ConstraintCategory::Boring,
2397 param_env.and(type_op::normalize::Normalize::new(value)),
2398 ).unwrap_or_else(|NoSolution| {
2399 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2405 pub struct TypeckMir;
2407 impl MirPass for TypeckMir {
2408 fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
2409 let def_id = src.def_id;
2410 debug!("run_pass: {:?}", def_id);
2412 // When NLL is enabled, the borrow checker runs the typeck
2413 // itself, so we don't need this MIR pass anymore.
2414 if tcx.use_mir_borrowck() {
2418 if tcx.sess.err_count() > 0 {
2419 // compiling a broken program can obviously result in a
2420 // broken MIR, so try not to report duplicate errors.
2424 if tcx.is_struct_constructor(def_id) {
2425 // We just assume that the automatically generated struct constructors are
2426 // correct. See the comment in the `mir_borrowck` implementation for an
2427 // explanation why we need this.
2431 let param_env = tcx.param_env(def_id);
2432 tcx.infer_ctxt().enter(|infcx| {
2433 type_check_internal(
2445 // For verification purposes, we just ignore the resulting
2446 // region constraint sets. Not our problem. =)
2451 trait NormalizeLocation: fmt::Debug + Copy {
2452 fn to_locations(self) -> Locations;
2455 impl NormalizeLocation for Locations {
2456 fn to_locations(self) -> Locations {
2461 impl NormalizeLocation for Location {
2462 fn to_locations(self) -> Locations {
2463 Locations::Single(self)
2467 #[derive(Debug, Default)]
2468 struct ObligationAccumulator<'tcx> {
2469 obligations: PredicateObligations<'tcx>,
2472 impl<'tcx> ObligationAccumulator<'tcx> {
2473 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2474 let InferOk { value, obligations } = value;
2475 self.obligations.extend(obligations);
2479 fn into_vec(self) -> PredicateObligations<'tcx> {