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::{ConstraintCategory, 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::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;
46 use rustc::ty::{self, CanonicalTy, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TyKind};
49 use syntax_pos::{Span, DUMMY_SP};
50 use transform::{MirPass, MirSource};
53 use rustc_data_structures::fx::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 type_tests: Vec::default(),
133 let mut placeholder_indices = PlaceholderIndices::default();
136 universal_region_relations,
138 normalized_inputs_and_output,
139 } = free_region_relations::create(
142 Some(implicit_region_bound),
147 let mut borrowck_context = BorrowCheckContext {
152 constraints: &mut constraints,
153 placeholder_indices: &mut placeholder_indices,
162 Some(implicit_region_bound),
163 Some(&mut borrowck_context),
164 Some(&universal_region_relations),
166 cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
167 liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
171 .map(|bcx| translate_outlives_facts(bcx));
178 universal_region_relations,
182 fn type_check_internal<'a, 'gcx, 'tcx, R>(
183 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
185 param_env: ty::ParamEnv<'gcx>,
187 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
188 implicit_region_bound: Option<ty::Region<'tcx>>,
189 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
190 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
191 mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
193 let mut checker = TypeChecker::new(
199 implicit_region_bound,
201 universal_region_relations,
203 let errors_reported = {
204 let mut verifier = TypeVerifier::new(&mut checker, mir);
205 verifier.visit_mir(mir);
206 verifier.errors_reported
209 if !errors_reported {
210 // if verifier failed, don't do further checks to avoid ICEs
211 checker.typeck_mir(mir);
217 fn translate_outlives_facts(cx: &mut BorrowCheckContext) {
218 if let Some(facts) = cx.all_facts {
219 let location_table = cx.location_table;
222 .extend(cx.constraints.outlives_constraints.iter().flat_map(
223 |constraint: &OutlivesConstraint| {
224 if let Some(from_location) = constraint.locations.from_location() {
225 Either::Left(iter::once((
228 location_table.mid_index(from_location),
234 .map(move |location| (constraint.sup, constraint.sub, location)),
242 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
243 // We sometimes see MIR failures (notably predicate failures) due to
244 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
245 // to avoid reporting bugs in those cases.
246 tcx.sess.diagnostic().delay_span_bug(span, msg);
249 enum FieldAccessError {
250 OutOfRange { field_count: usize },
253 /// Verifies that MIR types are sane to not crash further checks.
255 /// The sanitize_XYZ methods here take an MIR object and compute its
256 /// type, calling `span_mirbug` and returning an error type if there
258 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
259 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
263 errors_reported: bool,
266 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
267 fn visit_span(&mut self, span: &Span) {
268 if !span.is_dummy() {
269 self.last_span = *span;
273 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
274 self.sanitize_place(place, location, context);
277 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
278 self.super_constant(constant, location);
279 self.sanitize_constant(constant, location);
280 self.sanitize_type(constant, constant.ty);
282 if let Some(user_ty) = constant.user_ty {
283 if let Err(terr) = self.cx.relate_type_and_user_type(
285 ty::Variance::Invariant,
287 location.to_locations(),
288 ConstraintCategory::Boring,
293 "bad constant user type {:?} vs {:?}: {:?}",
302 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
303 self.super_rvalue(rvalue, location);
304 let rval_ty = rvalue.ty(self.mir, self.tcx());
305 self.sanitize_type(rvalue, rval_ty);
308 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
309 self.super_local_decl(local, local_decl);
310 self.sanitize_type(local_decl, local_decl.ty);
312 if let Some(user_ty) = local_decl.user_ty {
313 if let Err(terr) = self.cx.relate_type_and_user_type(
315 ty::Variance::Invariant,
317 Locations::All(local_decl.source_info.span),
318 ConstraintCategory::TypeAnnotation,
323 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
333 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
334 self.sanitize_type(&"return type", mir.return_ty());
335 for local_decl in &mir.local_decls {
336 self.sanitize_type(local_decl, local_decl.ty);
338 if self.errors_reported {
345 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
346 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
349 mir_def_id: cx.mir_def_id,
352 errors_reported: false,
356 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
360 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
361 if ty.has_escaping_regions() || ty.references_error() {
362 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
368 /// Checks that the constant's `ty` field matches up with what
369 /// would be expected from its literal.
370 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
372 "sanitize_constant(constant={:?}, location={:?})",
376 // FIXME(#46702) -- We need some way to get the predicates
377 // associated with the "pre-evaluated" form of the
378 // constant. For example, consider that the constant
379 // may have associated constant projections (`<Foo as
380 // Trait<'a, 'b>>::SOME_CONST`) that impose
381 // constraints on `'a` and `'b`. These constraints
382 // would be lost if we just look at the normalized
384 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
385 let tcx = self.tcx();
386 let type_checker = &mut self.cx;
388 // FIXME -- For now, use the substitutions from
389 // `value.ty` rather than `value.val`. The
390 // renumberer will rewrite them to independent
391 // sets of regions; in principle, we ought to
392 // derive the type of the `value.val` from "first
393 // principles" and equate with value.ty, but as we
394 // are transitioning to the miri-based system, we
395 // don't have a handy function for that, so for
396 // now we just ignore `value.val` regions.
398 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
399 type_checker.normalize_and_prove_instantiated_predicates(
400 instantiated_predicates,
401 location.to_locations(),
405 debug!("sanitize_constant: expected_ty={:?}", constant.literal.ty);
407 if let Err(terr) = self.cx.eq_types(
410 location.to_locations(),
411 ConstraintCategory::Boring,
416 "constant {:?} should have type {:?} but has {:?} ({:?})",
425 /// Checks that the types internal to the `place` match up with
426 /// what would be expected.
431 context: PlaceContext,
433 debug!("sanitize_place: {:?}", place);
434 let place_ty = match *place {
435 Place::Local(index) => PlaceTy::Ty {
436 ty: self.mir.local_decls[index].ty,
438 Place::Promoted(box (_index, sty)) => {
439 let sty = self.sanitize_type(place, sty);
440 // FIXME -- promoted MIR return types reference
441 // various "free regions" (e.g., scopes and things)
442 // that they ought not to do. We have to figure out
443 // how best to handle that -- probably we want treat
444 // promoted MIR much like closures, renumbering all
445 // their free regions and propagating constraints
446 // upwards. We have the same acyclic guarantees, so
447 // that should be possible. But for now, ignore them.
449 // let promoted_mir = &self.mir.promoted[index];
450 // promoted_mir.return_ty()
451 PlaceTy::Ty { ty: sty }
453 Place::Static(box Static { def_id, ty: sty }) => {
454 let sty = self.sanitize_type(place, sty);
455 let ty = self.tcx().type_of(def_id);
456 let ty = self.cx.normalize(ty, location);
459 .eq_types(ty, sty, location.to_locations(), ConstraintCategory::Boring)
464 "bad static type ({:?}: {:?}): {:?}",
470 PlaceTy::Ty { ty: sty }
472 Place::Projection(ref proj) => {
473 let base_context = if context.is_mutating_use() {
474 PlaceContext::Projection(Mutability::Mut)
476 PlaceContext::Projection(Mutability::Not)
478 let base_ty = self.sanitize_place(&proj.base, location, base_context);
479 if let PlaceTy::Ty { ty } = base_ty {
480 if ty.references_error() {
481 assert!(self.errors_reported);
483 ty: self.tcx().types.err,
487 self.sanitize_projection(base_ty, &proj.elem, place, location)
490 if let PlaceContext::Copy = context {
491 let tcx = self.tcx();
492 let trait_ref = ty::TraitRef {
493 def_id: tcx.lang_items().copy_trait().unwrap(),
494 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
497 // In order to have a Copy operand, the type T of the value must be Copy. Note that we
498 // prove that T: Copy, rather than using the type_moves_by_default test. This is
499 // important because type_moves_by_default ignores the resulting region obligations and
500 // assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
501 // (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
502 // fully apply: in effect, the rule is that if a value of some type could implement
503 // Copy, then it must.
504 self.cx.prove_trait_ref(
506 location.to_locations(),
507 ConstraintCategory::CopyBound,
513 fn sanitize_projection(
516 pi: &PlaceElem<'tcx>,
520 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
521 let tcx = self.tcx();
522 let base_ty = base.to_ty(tcx);
524 ProjectionElem::Deref => {
525 let deref_ty = base_ty.builtin_deref(true);
527 ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
528 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
532 ProjectionElem::Index(i) => {
533 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
534 if index_ty != tcx.types.usize {
536 ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
540 ty: base_ty.builtin_index().unwrap_or_else(|| {
541 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
546 ProjectionElem::ConstantIndex { .. } => {
547 // consider verifying in-bounds
549 ty: base_ty.builtin_index().unwrap_or_else(|| {
550 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
554 ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
555 ty: match base_ty.sty {
556 ty::Array(inner, size) => {
557 let size = size.unwrap_usize(tcx);
558 let min_size = (from as u64) + (to as u64);
559 if let Some(rest_size) = size.checked_sub(min_size) {
560 tcx.mk_array(inner, rest_size)
562 span_mirbug_and_err!(
565 "taking too-small slice of {:?}",
570 ty::Slice(..) => base_ty,
571 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
574 ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
575 ty::Adt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
576 if index >= adt_def.variants.len() {
578 ty: span_mirbug_and_err!(
581 "cast to variant #{:?} but enum only has {:?}",
583 adt_def.variants.len()
590 variant_index: index,
595 ty: span_mirbug_and_err!(
598 "can't downcast {:?} as {:?}",
604 ProjectionElem::Field(field, fty) => {
605 let fty = self.sanitize_type(place, fty);
606 match self.field_ty(place, base, field, location) {
607 Ok(ty) => if let Err(terr) = self.cx.eq_types(
610 location.to_locations(),
611 ConstraintCategory::Boring,
616 "bad field access ({:?}: {:?}): {:?}",
622 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
625 "accessed field #{} but variant only has {}",
630 PlaceTy::Ty { ty: fty }
635 fn error(&mut self) -> Ty<'tcx> {
636 self.errors_reported = true;
642 parent: &dyn fmt::Debug,
643 base_ty: PlaceTy<'tcx>,
646 ) -> Result<Ty<'tcx>, FieldAccessError> {
647 let tcx = self.tcx();
649 let (variant, substs) = match base_ty {
654 } => (&adt_def.variants[variant_index], substs),
655 PlaceTy::Ty { ty } => match ty.sty {
656 ty::Adt(adt_def, substs) if !adt_def.is_enum() => (&adt_def.variants[0], substs),
657 ty::Closure(def_id, substs) => {
658 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
660 None => Err(FieldAccessError::OutOfRange {
661 field_count: substs.upvar_tys(def_id, tcx).count(),
665 ty::Generator(def_id, substs, _) => {
666 // Try pre-transform fields first (upvars and current state)
667 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
671 // Then try `field_tys` which contains all the fields, but it
672 // requires the final optimized MIR.
673 return match substs.field_tys(def_id, tcx).nth(field.index()) {
675 None => Err(FieldAccessError::OutOfRange {
676 field_count: substs.field_tys(def_id, tcx).count(),
681 return match tys.get(field.index()) {
683 None => Err(FieldAccessError::OutOfRange {
684 field_count: tys.len(),
689 return Ok(span_mirbug_and_err!(
692 "can't project out of {:?}",
699 if let Some(field) = variant.fields.get(field.index()) {
700 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
702 Err(FieldAccessError::OutOfRange {
703 field_count: variant.fields.len(),
709 /// The MIR type checker. Visits the MIR and enforces all the
710 /// constraints needed for it to be valid and well-typed. Along the
711 /// way, it accrues region constraints -- these can later be used by
712 /// NLL region checking.
713 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
714 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
715 param_env: ty::ParamEnv<'gcx>,
719 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
720 implicit_region_bound: Option<ty::Region<'tcx>>,
721 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
722 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
723 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
726 struct BorrowCheckContext<'a, 'tcx: 'a> {
727 universal_regions: &'a UniversalRegions<'tcx>,
728 location_table: &'a LocationTable,
729 all_facts: &'a mut Option<AllFacts>,
730 borrow_set: &'a BorrowSet<'tcx>,
731 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
732 placeholder_indices: &'a mut PlaceholderIndices,
735 crate struct MirTypeckResults<'tcx> {
736 crate constraints: MirTypeckRegionConstraints<'tcx>,
737 crate placeholder_indices: PlaceholderIndices,
738 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
741 /// A collection of region constraints that must be satisfied for the
742 /// program to be considered well-typed.
743 crate struct MirTypeckRegionConstraints<'tcx> {
744 /// In general, the type-checker is not responsible for enforcing
745 /// liveness constraints; this job falls to the region inferencer,
746 /// which performs a liveness analysis. However, in some limited
747 /// cases, the MIR type-checker creates temporary regions that do
748 /// not otherwise appear in the MIR -- in particular, the
749 /// late-bound regions that it instantiates at call-sites -- and
750 /// hence it must report on their liveness constraints.
751 crate liveness_constraints: LivenessValues<RegionVid>,
753 crate outlives_constraints: ConstraintSet,
755 crate type_tests: Vec<TypeTest<'tcx>>,
758 /// The `Locations` type summarizes *where* region constraints are
759 /// required to hold. Normally, this is at a particular point which
760 /// created the obligation, but for constraints that the user gave, we
761 /// want the constraint to hold at all points.
762 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
764 /// Indicates that a type constraint should always be true. This
765 /// is particularly important in the new borrowck analysis for
766 /// things like the type of the return slot. Consider this
770 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
772 /// return &y; // error
776 /// Here, we wind up with the signature from the return type being
777 /// something like `&'1 u32` where `'1` is a universal region. But
778 /// the type of the return slot `_0` is something like `&'2 u32`
779 /// where `'2` is an existential region variable. The type checker
780 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
781 /// older NLL analysis, we required this only at the entry point
782 /// to the function. By the nature of the constraints, this wound
783 /// up propagating to all points reachable from start (because
784 /// `'1` -- as a universal region -- is live everywhere). In the
785 /// newer analysis, though, this doesn't work: `_0` is considered
786 /// dead at the start (it has no usable value) and hence this type
787 /// equality is basically a no-op. Then, later on, when we do `_0
788 /// = &'3 y`, that region `'3` never winds up related to the
789 /// universal region `'1` and hence no error occurs. Therefore, we
790 /// use Locations::All instead, which ensures that the `'1` and
791 /// `'2` are equal everything. We also use this for other
792 /// user-given type annotations; e.g., if the user wrote `let mut
793 /// x: &'static u32 = ...`, we would ensure that all values
794 /// assigned to `x` are of `'static` lifetime.
796 /// The span points to the place the constraint arose. For example,
797 /// it points to the type in a user-given type annotation. If
798 /// there's no sensible span then it's DUMMY_SP.
801 /// An outlives constraint that only has to hold at a single location,
802 /// usually it represents a point where references flow from one spot to
803 /// another (e.g., `x = y`)
808 pub fn from_location(&self) -> Option<Location> {
810 Locations::All(_) => None,
811 Locations::Single(from_location) => Some(*from_location),
815 /// Gets a span representing the location.
816 pub fn span(&self, mir: &Mir<'_>) -> Span {
818 Locations::All(span) => *span,
819 Locations::Single(l) => mir.source_info(*l).span,
824 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
826 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
829 param_env: ty::ParamEnv<'gcx>,
830 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
831 implicit_region_bound: Option<ty::Region<'tcx>>,
832 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
833 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
842 implicit_region_bound,
844 reported_errors: FxHashSet(),
845 universal_region_relations,
849 /// Given some operation `op` that manipulates types, proves
850 /// predicates, or otherwise uses the inference context, executes
851 /// `op` and then executes all the further obligations that `op`
852 /// returns. This will yield a set of outlives constraints amongst
853 /// regions which are extracted and stored as having occurred at
856 /// **Any `rustc::infer` operations that might generate region
857 /// constraints should occur within this method so that those
858 /// constraints can be properly localized!**
859 fn fully_perform_op<R>(
861 locations: Locations,
862 category: ConstraintCategory,
863 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
865 let (r, opt_data) = op.fully_perform(self.infcx)?;
867 if let Some(data) = &opt_data {
868 self.push_region_constraints(locations, category, data);
874 fn push_region_constraints(
876 locations: Locations,
877 category: ConstraintCategory,
878 data: &[QueryRegionConstraint<'tcx>],
881 "push_region_constraints: constraints generated at {:?} are {:#?}",
885 if let Some(ref mut borrowck_context) = self.borrowck_context {
886 constraint_conversion::ConstraintConversion::new(
888 borrowck_context.universal_regions,
889 self.region_bound_pairs,
890 self.implicit_region_bound,
894 &mut borrowck_context.constraints.outlives_constraints,
895 &mut borrowck_context.constraints.type_tests,
896 ).convert_all(&data);
904 locations: Locations,
905 category: ConstraintCategory,
907 relate_tys::sub_types(
913 self.borrowck_context.as_mut().map(|x| &mut **x),
917 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
918 /// variables in `sub` with their inferred definitions and try
919 /// again. This is used for opaque types in places (e.g., `let x:
921 fn sub_types_or_anon(
925 locations: Locations,
926 category: ConstraintCategory,
928 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
929 if let TyKind::Opaque(..) = sup.sty {
930 // When you have `let x: impl Foo = ...` in a closure,
931 // the resulting inferend values are stored with the
932 // def-id of the base function.
933 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
934 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
946 locations: Locations,
947 category: ConstraintCategory,
949 relate_tys::eq_types(
955 self.borrowck_context.as_mut().map(|x| &mut **x),
959 fn relate_type_and_user_type(
963 b: CanonicalTy<'tcx>,
964 locations: Locations,
965 category: ConstraintCategory,
967 relate_tys::relate_type_and_user_type(
974 self.borrowck_context.as_mut().map(|x| &mut **x),
978 fn eq_opaque_type_and_type(
980 revealed_ty: Ty<'tcx>,
982 anon_owner_def_id: DefId,
983 locations: Locations,
984 category: ConstraintCategory,
987 "eq_opaque_type_and_type( \
992 let infcx = self.infcx;
994 let param_env = self.param_env;
995 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
996 let opaque_type_map = self.fully_perform_op(
1001 let mut obligations = ObligationAccumulator::default();
1003 let dummy_body_id = ObligationCause::dummy().body_id;
1004 let (output_ty, opaque_type_map) =
1005 obligations.add(infcx.instantiate_opaque_types(
1012 "eq_opaque_type_and_type: \
1013 instantiated output_ty={:?} \
1014 opaque_type_map={:#?} \
1016 output_ty, opaque_type_map, revealed_ty
1018 obligations.add(infcx
1019 .at(&ObligationCause::dummy(), param_env)
1020 .eq(output_ty, revealed_ty)?);
1022 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1023 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1024 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1025 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1027 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1028 opaque_decl.concrete_ty,
1029 infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1032 obligations.add(infcx
1033 .at(&ObligationCause::dummy(), param_env)
1034 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1037 debug!("eq_opaque_type_and_type: equated");
1040 value: Some(opaque_type_map),
1041 obligations: obligations.into_vec(),
1044 || "input_output".to_string(),
1048 let universal_region_relations = match self.universal_region_relations {
1050 None => return Ok(()),
1053 // Finally, if we instantiated the anon types successfully, we
1054 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1055 // prove that `T: Iterator` where `T` is the type we
1056 // instantiated it with).
1057 if let Some(opaque_type_map) = opaque_type_map {
1058 for (opaque_def_id, opaque_decl) in opaque_type_map {
1059 self.fully_perform_op(
1061 ConstraintCategory::OpaqueType,
1064 infcx.constrain_opaque_type(
1067 universal_region_relations,
1071 obligations: vec![],
1074 || "opaque_type_map".to_string(),
1082 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1086 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1087 debug!("check_stmt: {:?}", stmt);
1088 let tcx = self.tcx();
1090 StatementKind::Assign(ref place, ref rv) => {
1091 // Assignments to temporaries are not "interesting";
1092 // they are not caused by the user, but rather artifacts
1093 // of lowering. Assignments to other sorts of places *are* interesting
1095 let category = match *place {
1096 Place::Local(RETURN_PLACE) => ConstraintCategory::Return,
1097 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1098 ConstraintCategory::Boring
1100 _ => ConstraintCategory::Assignment,
1103 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1104 let rv_ty = rv.ty(mir, tcx);
1106 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1111 "bad assignment ({:?} = {:?}): {:?}",
1118 if let Some(user_ty) = self.rvalue_user_ty(rv) {
1119 if let Err(terr) = self.relate_type_and_user_type(
1121 ty::Variance::Invariant,
1123 location.to_locations(),
1124 ConstraintCategory::Boring,
1129 "bad user type on rvalue ({:?} = {:?}): {:?}",
1137 self.check_rvalue(mir, rv, location);
1138 if !self.tcx().features().unsized_locals {
1139 let trait_ref = ty::TraitRef {
1140 def_id: tcx.lang_items().sized_trait().unwrap(),
1141 substs: tcx.mk_substs_trait(place_ty, &[]),
1143 self.prove_trait_ref(
1145 location.to_locations(),
1146 ConstraintCategory::SizedBound,
1150 StatementKind::SetDiscriminant {
1154 let place_type = place.ty(mir, tcx).to_ty(tcx);
1155 let adt = match place_type.sty {
1156 TyKind::Adt(adt, _) if adt.is_enum() => adt,
1159 stmt.source_info.span,
1160 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1166 if variant_index >= adt.variants.len() {
1168 stmt.source_info.span,
1169 "bad set discriminant ({:?} = {:?}): value of of range",
1175 StatementKind::AscribeUserType(ref place, variance, c_ty) => {
1176 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1177 if let Err(terr) = self.relate_type_and_user_type(
1181 Locations::All(stmt.source_info.span),
1182 ConstraintCategory::TypeAnnotation,
1187 "bad type assert ({:?} <: {:?}): {:?}",
1194 StatementKind::FakeRead(..)
1195 | StatementKind::StorageLive(_)
1196 | StatementKind::StorageDead(_)
1197 | StatementKind::InlineAsm { .. }
1198 | StatementKind::EndRegion(_)
1199 | StatementKind::Validate(..)
1200 | StatementKind::Nop => {}
1204 fn check_terminator(
1207 term: &Terminator<'tcx>,
1208 term_location: Location,
1210 debug!("check_terminator: {:?}", term);
1211 let tcx = self.tcx();
1213 TerminatorKind::Goto { .. }
1214 | TerminatorKind::Resume
1215 | TerminatorKind::Abort
1216 | TerminatorKind::Return
1217 | TerminatorKind::GeneratorDrop
1218 | TerminatorKind::Unreachable
1219 | TerminatorKind::Drop { .. }
1220 | TerminatorKind::FalseEdges { .. }
1221 | TerminatorKind::FalseUnwind { .. } => {
1222 // no checks needed for these
1225 TerminatorKind::DropAndReplace {
1231 let place_ty = location.ty(mir, tcx).to_ty(tcx);
1232 let rv_ty = value.ty(mir, tcx);
1234 let locations = term_location.to_locations();
1236 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1241 "bad DropAndReplace ({:?} = {:?}): {:?}",
1248 TerminatorKind::SwitchInt {
1253 let discr_ty = discr.ty(mir, tcx);
1254 if let Err(terr) = self.sub_types(
1257 term_location.to_locations(),
1258 ConstraintCategory::Assignment,
1263 "bad SwitchInt ({:?} on {:?}): {:?}",
1269 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1270 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1272 // FIXME: check the values
1274 TerminatorKind::Call {
1280 let func_ty = func.ty(mir, tcx);
1281 debug!("check_terminator: call, func_ty={:?}", func_ty);
1282 let sig = match func_ty.sty {
1283 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1285 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1289 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
1290 term.source_info.span,
1291 LateBoundRegionConversionTime::FnCall,
1294 let sig = self.normalize(sig, term_location);
1295 self.check_call_dest(mir, term, &sig, destination, term_location);
1297 self.prove_predicates(
1298 sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1299 term_location.to_locations(),
1300 ConstraintCategory::Boring,
1303 // The ordinary liveness rules will ensure that all
1304 // regions in the type of the callee are live here. We
1305 // then further constrain the late-bound regions that
1306 // were instantiated at the call site to be live as
1307 // well. The resulting is that all the input (and
1308 // output) types in the signature must be live, since
1309 // all the inputs that fed into it were live.
1310 for &late_bound_region in map.values() {
1311 if let Some(ref mut borrowck_context) = self.borrowck_context {
1312 let region_vid = borrowck_context
1314 .to_region_vid(late_bound_region);
1317 .liveness_constraints
1318 .add_element(region_vid, term_location);
1322 self.check_call_inputs(mir, term, &sig, args, term_location);
1324 TerminatorKind::Assert {
1325 ref cond, ref msg, ..
1327 let cond_ty = cond.ty(mir, tcx);
1328 if cond_ty != tcx.types.bool {
1329 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1332 if let BoundsCheck { ref len, ref index } = *msg {
1333 if len.ty(mir, tcx) != tcx.types.usize {
1334 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1336 if index.ty(mir, tcx) != tcx.types.usize {
1337 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1341 TerminatorKind::Yield { ref value, .. } => {
1342 let value_ty = value.ty(mir, tcx);
1343 match mir.yield_ty {
1344 None => span_mirbug!(self, term, "yield in non-generator"),
1346 if let Err(terr) = self.sub_types(
1349 term_location.to_locations(),
1350 ConstraintCategory::Return,
1355 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1370 term: &Terminator<'tcx>,
1371 sig: &ty::FnSig<'tcx>,
1372 destination: &Option<(Place<'tcx>, BasicBlock)>,
1373 term_location: Location,
1375 let tcx = self.tcx();
1376 match *destination {
1377 Some((ref dest, _target_block)) => {
1378 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1379 let category = match *dest {
1380 Place::Local(RETURN_PLACE) => ConstraintCategory::Return,
1381 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1382 ConstraintCategory::Boring
1384 _ => ConstraintCategory::Assignment,
1387 let locations = term_location.to_locations();
1390 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1395 "call dest mismatch ({:?} <- {:?}): {:?}",
1402 // When `#![feature(unsized_locals)]` is not enabled,
1403 // this check is done at `check_local`.
1404 if self.tcx().features().unsized_locals {
1405 let span = term.source_info.span;
1406 self.ensure_place_sized(dest_ty, span);
1410 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1411 if !sig.output().is_never() {
1412 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1418 fn check_call_inputs(
1421 term: &Terminator<'tcx>,
1422 sig: &ty::FnSig<'tcx>,
1423 args: &[Operand<'tcx>],
1424 term_location: Location,
1426 debug!("check_call_inputs({:?}, {:?})", sig, args);
1427 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1428 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1430 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1431 let op_arg_ty = op_arg.ty(mir, self.tcx());
1432 if let Err(terr) = self.sub_types(
1435 term_location.to_locations(),
1436 ConstraintCategory::CallArgument,
1441 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1451 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1452 let is_cleanup = block_data.is_cleanup;
1453 self.last_span = block_data.terminator().source_info.span;
1454 match block_data.terminator().kind {
1455 TerminatorKind::Goto { target } => {
1456 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1458 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1459 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1461 TerminatorKind::Resume => if !is_cleanup {
1462 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1464 TerminatorKind::Abort => if !is_cleanup {
1465 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1467 TerminatorKind::Return => if is_cleanup {
1468 span_mirbug!(self, block_data, "return on cleanup block")
1470 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1471 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1473 TerminatorKind::Yield { resume, drop, .. } => {
1475 span_mirbug!(self, block_data, "yield in cleanup block")
1477 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1478 if let Some(drop) = drop {
1479 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1482 TerminatorKind::Unreachable => {}
1483 TerminatorKind::Drop { target, unwind, .. }
1484 | TerminatorKind::DropAndReplace { target, unwind, .. }
1485 | TerminatorKind::Assert {
1490 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1491 if let Some(unwind) = unwind {
1493 span_mirbug!(self, block_data, "unwind on cleanup block")
1495 self.assert_iscleanup(mir, block_data, unwind, true);
1498 TerminatorKind::Call {
1503 if let &Some((_, target)) = destination {
1504 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1506 if let Some(cleanup) = cleanup {
1508 span_mirbug!(self, block_data, "cleanup on cleanup block")
1510 self.assert_iscleanup(mir, block_data, cleanup, true);
1513 TerminatorKind::FalseEdges {
1515 ref imaginary_targets,
1517 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1518 for target in imaginary_targets {
1519 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1522 TerminatorKind::FalseUnwind {
1526 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1527 if let Some(unwind) = unwind {
1532 "cleanup in cleanup block via false unwind"
1535 self.assert_iscleanup(mir, block_data, unwind, true);
1541 fn assert_iscleanup(
1544 ctxt: &dyn fmt::Debug,
1548 if mir[bb].is_cleanup != iscleanuppad {
1552 "cleanuppad mismatch: {:?} should be {:?}",
1559 fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1560 match mir.local_kind(local) {
1561 LocalKind::ReturnPointer | LocalKind::Arg => {
1562 // return values of normal functions are required to be
1563 // sized by typeck, but return values of ADT constructors are
1564 // not because we don't include a `Self: Sized` bounds on them.
1566 // Unbound parts of arguments were never required to be Sized
1567 // - maybe we should make that a warning.
1570 LocalKind::Var | LocalKind::Temp => {}
1573 // When `#![feature(unsized_locals)]` is enabled, only function calls
1574 // and nullary ops are checked in `check_call_dest`.
1575 if !self.tcx().features().unsized_locals {
1576 let span = local_decl.source_info.span;
1577 let ty = local_decl.ty;
1578 self.ensure_place_sized(ty, span);
1582 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1583 let tcx = self.tcx();
1585 // Erase the regions from `ty` to get a global type. The
1586 // `Sized` bound in no way depends on precise regions, so this
1587 // shouldn't affect `is_sized`.
1588 let gcx = tcx.global_tcx();
1589 let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1590 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1591 // in current MIR construction, all non-control-flow rvalue
1592 // expressions evaluate through `as_temp` or `into` a return
1593 // slot or local, so to find all unsized rvalues it is enough
1594 // to check all temps, return slots and locals.
1595 if let None = self.reported_errors.replace((ty, span)) {
1596 let mut diag = struct_span_err!(
1600 "cannot move a value of type {0}: the size of {0} \
1601 cannot be statically determined",
1605 // While this is located in `nll::typeck` this error is not
1606 // an NLL error, it's a required check to prevent creation
1607 // of unsized rvalues in certain cases:
1608 // * operand of a box expression
1609 // * callee in a call expression
1615 fn aggregate_field_ty(
1617 ak: &AggregateKind<'tcx>,
1620 ) -> Result<Ty<'tcx>, FieldAccessError> {
1621 let tcx = self.tcx();
1624 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1625 let variant = &def.variants[variant_index];
1626 let adj_field_index = active_field_index.unwrap_or(field_index);
1627 if let Some(field) = variant.fields.get(adj_field_index) {
1628 Ok(self.normalize(field.ty(tcx, substs), location))
1630 Err(FieldAccessError::OutOfRange {
1631 field_count: variant.fields.len(),
1635 AggregateKind::Closure(def_id, substs) => {
1636 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1638 None => Err(FieldAccessError::OutOfRange {
1639 field_count: substs.upvar_tys(def_id, tcx).count(),
1643 AggregateKind::Generator(def_id, substs, _) => {
1644 // Try pre-transform fields first (upvars and current state)
1645 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1648 // Then try `field_tys` which contains all the fields, but it
1649 // requires the final optimized MIR.
1650 match substs.field_tys(def_id, tcx).nth(field_index) {
1652 None => Err(FieldAccessError::OutOfRange {
1653 field_count: substs.field_tys(def_id, tcx).count(),
1658 AggregateKind::Array(ty) => Ok(ty),
1659 AggregateKind::Tuple => {
1660 unreachable!("This should have been covered in check_rvalues");
1665 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1666 let tcx = self.tcx();
1669 Rvalue::Aggregate(ak, ops) => {
1670 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1673 Rvalue::Repeat(operand, len) => if *len > 1 {
1674 let operand_ty = operand.ty(mir, tcx);
1676 let trait_ref = ty::TraitRef {
1677 def_id: tcx.lang_items().copy_trait().unwrap(),
1678 substs: tcx.mk_substs_trait(operand_ty, &[]),
1681 self.prove_trait_ref(
1683 location.to_locations(),
1684 ConstraintCategory::CopyBound,
1688 Rvalue::NullaryOp(_, ty) => {
1689 // Even with unsized locals cannot box an unsized value.
1690 if self.tcx().features().unsized_locals {
1691 let span = mir.source_info(location).span;
1692 self.ensure_place_sized(ty, span);
1695 let trait_ref = ty::TraitRef {
1696 def_id: tcx.lang_items().sized_trait().unwrap(),
1697 substs: tcx.mk_substs_trait(ty, &[]),
1700 self.prove_trait_ref(
1702 location.to_locations(),
1703 ConstraintCategory::SizedBound,
1707 Rvalue::Cast(cast_kind, op, ty) => {
1709 CastKind::ReifyFnPointer => {
1710 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1712 // The type that we see in the fcx is like
1713 // `foo::<'a, 'b>`, where `foo` is the path to a
1714 // function definition. When we extract the
1715 // signature, it comes from the `fn_sig` query,
1716 // and hence may contain unnormalized results.
1717 let fn_sig = self.normalize(fn_sig, location);
1719 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1721 if let Err(terr) = self.eq_types(
1724 location.to_locations(),
1725 ConstraintCategory::Cast,
1730 "equating {:?} with {:?} yields {:?}",
1738 CastKind::ClosureFnPointer => {
1739 let sig = match op.ty(mir, tcx).sty {
1740 ty::Closure(def_id, substs) => {
1741 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1745 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1747 if let Err(terr) = self.eq_types(
1750 location.to_locations(),
1751 ConstraintCategory::Cast,
1756 "equating {:?} with {:?} yields {:?}",
1764 CastKind::UnsafeFnPointer => {
1765 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1767 // The type that we see in the fcx is like
1768 // `foo::<'a, 'b>`, where `foo` is the path to a
1769 // function definition. When we extract the
1770 // signature, it comes from the `fn_sig` query,
1771 // and hence may contain unnormalized results.
1772 let fn_sig = self.normalize(fn_sig, location);
1774 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1776 if let Err(terr) = self.eq_types(
1779 location.to_locations(),
1780 ConstraintCategory::Cast,
1785 "equating {:?} with {:?} yields {:?}",
1793 CastKind::Unsize => {
1795 let trait_ref = ty::TraitRef {
1796 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1797 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1800 self.prove_trait_ref(
1802 location.to_locations(),
1803 ConstraintCategory::Cast,
1807 CastKind::Misc => {}
1811 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1812 self.add_reborrow_constraint(location, region, borrowed_place);
1815 // FIXME: These other cases have to be implemented in future PRs
1818 | Rvalue::BinaryOp(..)
1819 | Rvalue::CheckedBinaryOp(..)
1820 | Rvalue::UnaryOp(..)
1821 | Rvalue::Discriminant(..) => {}
1825 /// If this rvalue supports a user-given type annotation, then
1826 /// extract and return it. This represents the final type of the
1827 /// rvalue and will be unified with the inferred type.
1828 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<CanonicalTy<'tcx>> {
1831 | Rvalue::Repeat(..)
1835 | Rvalue::BinaryOp(..)
1836 | Rvalue::CheckedBinaryOp(..)
1837 | Rvalue::NullaryOp(..)
1838 | Rvalue::UnaryOp(..)
1839 | Rvalue::Discriminant(..) => None,
1841 Rvalue::Aggregate(aggregate, _) => match **aggregate {
1842 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
1843 AggregateKind::Array(_) => None,
1844 AggregateKind::Tuple => None,
1845 AggregateKind::Closure(_, _) => None,
1846 AggregateKind::Generator(_, _, _) => None,
1851 fn check_aggregate_rvalue(
1854 rvalue: &Rvalue<'tcx>,
1855 aggregate_kind: &AggregateKind<'tcx>,
1856 operands: &[Operand<'tcx>],
1859 let tcx = self.tcx();
1861 self.prove_aggregate_predicates(aggregate_kind, location);
1863 if *aggregate_kind == AggregateKind::Tuple {
1864 // tuple rvalue field type is always the type of the op. Nothing to check here.
1868 for (i, operand) in operands.iter().enumerate() {
1869 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
1870 Ok(field_ty) => field_ty,
1871 Err(FieldAccessError::OutOfRange { field_count }) => {
1875 "accessed field #{} but variant only has {}",
1882 let operand_ty = operand.ty(mir, tcx);
1884 if let Err(terr) = self.sub_types(
1887 location.to_locations(),
1888 ConstraintCategory::Boring,
1893 "{:?} is not a subtype of {:?}: {:?}",
1902 /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
1906 /// - `location`: the location `L` where the borrow expression occurs
1907 /// - `borrow_region`: the region `'a` associated with the borrow
1908 /// - `borrowed_place`: the place `P` being borrowed
1909 fn add_reborrow_constraint(
1912 borrow_region: ty::Region<'tcx>,
1913 borrowed_place: &Place<'tcx>,
1915 // These constraints are only meaningful during borrowck:
1916 let BorrowCheckContext {
1922 } = match self.borrowck_context {
1923 Some(ref mut borrowck_context) => borrowck_context,
1927 // In Polonius mode, we also push a `borrow_region` fact
1928 // linking the loan to the region (in some cases, though,
1929 // there is no loan associated with this borrow expression --
1930 // that occurs when we are borrowing an unsafe place, for
1932 if let Some(all_facts) = all_facts {
1933 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
1934 let region_vid = borrow_region.to_region_vid();
1935 all_facts.borrow_region.push((
1938 location_table.mid_index(location),
1943 // If we are reborrowing the referent of another reference, we
1944 // need to add outlives relationships. In a case like `&mut
1945 // *p`, where the `p` has type `&'b mut Foo`, for example, we
1946 // need to ensure that `'b: 'a`.
1948 let mut borrowed_place = borrowed_place;
1951 "add_reborrow_constraint({:?}, {:?}, {:?})",
1952 location, borrow_region, borrowed_place
1954 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
1955 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
1958 ProjectionElem::Deref => {
1959 let tcx = self.infcx.tcx;
1960 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1962 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
1964 ty::Ref(ref_region, _, mutbl) => {
1965 constraints.outlives_constraints.push(OutlivesConstraint {
1966 sup: ref_region.to_region_vid(),
1967 sub: borrow_region.to_region_vid(),
1968 locations: location.to_locations(),
1969 category: ConstraintCategory::Boring,
1973 hir::Mutability::MutImmutable => {
1974 // Immutable reference. We don't need the base
1975 // to be valid for the entire lifetime of
1979 hir::Mutability::MutMutable => {
1980 // Mutable reference. We *do* need the base
1981 // to be valid, because after the base becomes
1982 // invalid, someone else can use our mutable deref.
1984 // This is in order to make the following function
1987 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
1992 // As otherwise you could clone `&mut T` using the
1993 // following function:
1995 // fn bad(x: &mut T) -> (&mut T, &mut T) {
1996 // let my_clone = unsafe_deref(&'a x);
2005 // deref of raw pointer, guaranteed to be valid
2008 ty::Adt(def, _) if def.is_box() => {
2009 // deref of `Box`, need the base to be valid - propagate
2011 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2014 ProjectionElem::Field(..)
2015 | ProjectionElem::Downcast(..)
2016 | ProjectionElem::Index(..)
2017 | ProjectionElem::ConstantIndex { .. }
2018 | ProjectionElem::Subslice { .. } => {
2019 // other field access
2023 // The "propagate" case. We need to check that our base is valid
2024 // for the borrow's lifetime.
2025 borrowed_place = base;
2029 fn prove_aggregate_predicates(
2031 aggregate_kind: &AggregateKind<'tcx>,
2034 let tcx = self.tcx();
2037 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2038 aggregate_kind, location
2041 let instantiated_predicates = match aggregate_kind {
2042 AggregateKind::Adt(def, _, substs, _, _) => {
2043 tcx.predicates_of(def.did).instantiate(tcx, substs)
2046 // For closures, we have some **extra requirements** we
2048 // have to check. In particular, in their upvars and
2049 // signatures, closures often reference various regions
2050 // from the surrounding function -- we call those the
2051 // closure's free regions. When we borrow-check (and hence
2052 // region-check) closures, we may find that the closure
2053 // requires certain relationships between those free
2054 // regions. However, because those free regions refer to
2055 // portions of the CFG of their caller, the closure is not
2056 // in a position to verify those relationships. In that
2057 // case, the requirements get "propagated" to us, and so
2058 // we have to solve them here where we instantiate the
2061 // Despite the opacity of the previous parapgrah, this is
2062 // actually relatively easy to understand in terms of the
2063 // desugaring. A closure gets desugared to a struct, and
2064 // these extra requirements are basically like where
2065 // clauses on the struct.
2066 AggregateKind::Closure(def_id, substs) => {
2067 if let Some(closure_region_requirements) =
2068 tcx.mir_borrowck(*def_id).closure_requirements
2070 let closure_constraints = closure_region_requirements.apply_requirements(
2077 self.push_region_constraints(
2078 location.to_locations(),
2079 ConstraintCategory::ClosureBounds,
2080 &closure_constraints,
2084 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
2087 AggregateKind::Generator(def_id, substs, _) => {
2088 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
2091 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2094 self.normalize_and_prove_instantiated_predicates(
2095 instantiated_predicates,
2096 location.to_locations(),
2102 trait_ref: ty::TraitRef<'tcx>,
2103 locations: Locations,
2104 category: ConstraintCategory,
2106 self.prove_predicates(
2107 Some(ty::Predicate::Trait(
2108 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2115 fn normalize_and_prove_instantiated_predicates(
2117 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2118 locations: Locations,
2120 for predicate in instantiated_predicates.predicates {
2121 let predicate = self.normalize(predicate, locations);
2122 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2126 fn prove_predicates(
2128 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2129 locations: Locations,
2130 category: ConstraintCategory,
2132 for predicate in predicates {
2134 "prove_predicates(predicate={:?}, locations={:?})",
2135 predicate, locations,
2138 self.prove_predicate(predicate, locations, category);
2144 predicate: ty::Predicate<'tcx>,
2145 locations: Locations,
2146 category: ConstraintCategory,
2149 "prove_predicate(predicate={:?}, location={:?})",
2150 predicate, locations,
2153 let param_env = self.param_env;
2154 self.fully_perform_op(
2157 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2158 ).unwrap_or_else(|NoSolution| {
2159 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2163 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2164 self.last_span = mir.span;
2165 debug!("run_on_mir: {:?}", mir.span);
2167 for (local, local_decl) in mir.local_decls.iter_enumerated() {
2168 self.check_local(mir, local, local_decl);
2171 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2172 let mut location = Location {
2176 for stmt in &block_data.statements {
2177 if !stmt.source_info.span.is_dummy() {
2178 self.last_span = stmt.source_info.span;
2180 self.check_stmt(mir, stmt, location);
2181 location.statement_index += 1;
2184 self.check_terminator(mir, block_data.terminator(), location);
2185 self.check_iscleanup(mir, block_data);
2189 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2191 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2193 debug!("normalize(value={:?}, location={:?})", value, location);
2194 let param_env = self.param_env;
2195 self.fully_perform_op(
2196 location.to_locations(),
2197 ConstraintCategory::Boring,
2198 param_env.and(type_op::normalize::Normalize::new(value)),
2199 ).unwrap_or_else(|NoSolution| {
2200 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2206 pub struct TypeckMir;
2208 impl MirPass for TypeckMir {
2209 fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
2210 let def_id = src.def_id;
2211 debug!("run_pass: {:?}", def_id);
2213 // When NLL is enabled, the borrow checker runs the typeck
2214 // itself, so we don't need this MIR pass anymore.
2215 if tcx.use_mir_borrowck() {
2219 if tcx.sess.err_count() > 0 {
2220 // compiling a broken program can obviously result in a
2221 // broken MIR, so try not to report duplicate errors.
2225 if tcx.is_struct_constructor(def_id) {
2226 // We just assume that the automatically generated struct constructors are
2227 // correct. See the comment in the `mir_borrowck` implementation for an
2228 // explanation why we need this.
2232 let param_env = tcx.param_env(def_id);
2233 tcx.infer_ctxt().enter(|infcx| {
2234 type_check_internal(
2246 // For verification purposes, we just ignore the resulting
2247 // region constraint sets. Not our problem. =)
2252 trait NormalizeLocation: fmt::Debug + Copy {
2253 fn to_locations(self) -> Locations;
2256 impl NormalizeLocation for Locations {
2257 fn to_locations(self) -> Locations {
2262 impl NormalizeLocation for Location {
2263 fn to_locations(self) -> Locations {
2264 Locations::Single(self)
2268 #[derive(Debug, Default)]
2269 struct ObligationAccumulator<'tcx> {
2270 obligations: PredicateObligations<'tcx>,
2273 impl<'tcx> ObligationAccumulator<'tcx> {
2274 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2275 let InferOk { value, obligations } = value;
2276 self.obligations.extend(obligations);
2280 fn into_vec(self) -> PredicateObligations<'tcx> {