1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This pass type-checks the MIR to ensure it is not broken.
12 #![allow(unreachable_code)]
14 use borrow_check::borrow_set::BorrowSet;
15 use borrow_check::location::LocationTable;
16 use borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
17 use borrow_check::nll::facts::AllFacts;
18 use borrow_check::nll::region_infer::values::LivenessValues;
19 use borrow_check::nll::region_infer::values::PlaceholderIndex;
20 use borrow_check::nll::region_infer::values::PlaceholderIndices;
21 use borrow_check::nll::region_infer::values::RegionValueElements;
22 use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
23 use borrow_check::nll::renumber;
24 use borrow_check::nll::type_check::free_region_relations::{
25 CreateResult, UniversalRegionRelations,
27 use borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
28 use borrow_check::nll::ToRegionVid;
29 use dataflow::move_paths::MoveData;
30 use dataflow::FlowAtLocation;
31 use dataflow::MaybeInitializedPlaces;
34 use rustc::hir::def_id::DefId;
35 use rustc::infer::canonical::QueryRegionConstraint;
36 use rustc::infer::outlives::env::RegionBoundPairs;
37 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
38 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
39 use rustc::mir::tcx::PlaceTy;
40 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
42 use rustc::traits::query::type_op;
43 use rustc::traits::query::type_op::custom::CustomTypeOp;
44 use rustc::traits::query::{Fallible, NoSolution};
45 use rustc::traits::{ObligationCause, PredicateObligations};
46 use rustc::ty::fold::TypeFoldable;
47 use rustc::ty::subst::{Subst, Substs, UnpackedKind};
48 use rustc::ty::{self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TyKind};
49 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
50 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
51 use rustc::ty::layout::VariantIdx;
54 use syntax_pos::{Span, DUMMY_SP};
55 use transform::{MirPass, MirSource};
57 macro_rules! span_mirbug {
58 ($context:expr, $elem:expr, $($message:tt)*) => ({
59 $crate::borrow_check::nll::type_check::mirbug(
63 "broken MIR in {:?} ({:?}): {}",
66 format_args!($($message)*),
72 macro_rules! span_mirbug_and_err {
73 ($context:expr, $elem:expr, $($message:tt)*) => ({
75 span_mirbug!($context, $elem, $($message)*);
81 mod constraint_conversion;
82 pub mod free_region_relations;
87 /// Type checks the given `mir` in the context of the inference
88 /// context `infcx`. Returns any region constraints that have yet to
89 /// be proven. This result is includes liveness constraints that
90 /// ensure that regions appearing in the types of all local variables
91 /// are live at all points where that local variable may later be
94 /// This phase of type-check ought to be infallible -- this is because
95 /// the original, HIR-based type-check succeeded. So if any errors
96 /// occur here, we will get a `bug!` reported.
100 /// - `infcx` -- inference context to use
101 /// - `param_env` -- parameter environment to use for trait solving
102 /// - `mir` -- MIR to type-check
103 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
104 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
105 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
106 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
107 /// to outlive; should represent the fn body
108 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
109 /// the types of the input parameters found in the MIR itself will be equated with these
110 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
111 /// the type for the RETURN_PLACE will be equated with this
112 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
113 /// constraints for the regions in the types of variables
114 /// - `flow_inits` -- results of a maybe-init dataflow analysis
115 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
116 pub(crate) fn type_check<'gcx, 'tcx>(
117 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
118 param_env: ty::ParamEnv<'gcx>,
121 universal_regions: &Rc<UniversalRegions<'tcx>>,
122 location_table: &LocationTable,
123 borrow_set: &BorrowSet<'tcx>,
124 all_facts: &mut Option<AllFacts>,
125 flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
126 move_data: &MoveData<'tcx>,
127 elements: &Rc<RegionValueElements>,
128 ) -> MirTypeckResults<'tcx> {
129 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
130 let mut constraints = MirTypeckRegionConstraints {
131 placeholder_indices: PlaceholderIndices::default(),
132 placeholder_index_to_region: IndexVec::default(),
133 liveness_constraints: LivenessValues::new(elements),
134 outlives_constraints: ConstraintSet::default(),
135 closure_bounds_mapping: Default::default(),
136 type_tests: Vec::default(),
140 universal_region_relations,
142 normalized_inputs_and_output,
143 } = free_region_relations::create(
146 Some(implicit_region_bound),
151 let mut borrowck_context = BorrowCheckContext {
156 constraints: &mut constraints,
165 Some(implicit_region_bound),
166 Some(&mut borrowck_context),
167 Some(&universal_region_relations),
169 cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
170 liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
174 .map(|bcx| translate_outlives_facts(bcx));
180 universal_region_relations,
184 fn type_check_internal<'a, 'gcx, 'tcx, R>(
185 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
187 param_env: ty::ParamEnv<'gcx>,
189 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
190 implicit_region_bound: Option<ty::Region<'tcx>>,
191 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
192 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
193 mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
195 let mut checker = TypeChecker::new(
201 implicit_region_bound,
203 universal_region_relations,
205 let errors_reported = {
206 let mut verifier = TypeVerifier::new(&mut checker, mir);
207 verifier.visit_mir(mir);
208 verifier.errors_reported
211 if !errors_reported {
212 // if verifier failed, don't do further checks to avoid ICEs
213 checker.typeck_mir(mir);
219 fn translate_outlives_facts(cx: &mut BorrowCheckContext) {
220 if let Some(facts) = cx.all_facts {
221 let location_table = cx.location_table;
224 .extend(cx.constraints.outlives_constraints.iter().flat_map(
225 |constraint: &OutlivesConstraint| {
226 if let Some(from_location) = constraint.locations.from_location() {
227 Either::Left(iter::once((
230 location_table.mid_index(from_location),
236 .map(move |location| (constraint.sup, constraint.sub, location)),
244 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
245 // We sometimes see MIR failures (notably predicate failures) due to
246 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
247 // to avoid reporting bugs in those cases.
248 tcx.sess.diagnostic().delay_span_bug(span, msg);
251 enum FieldAccessError {
252 OutOfRange { field_count: usize },
255 /// Verifies that MIR types are sane to not crash further checks.
257 /// The sanitize_XYZ methods here take an MIR object and compute its
258 /// type, calling `span_mirbug` and returning an error type if there
260 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
261 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
265 errors_reported: bool,
268 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
269 fn visit_span(&mut self, span: &Span) {
270 if !span.is_dummy() {
271 self.last_span = *span;
275 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
276 self.sanitize_place(place, location, context);
279 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
280 self.super_constant(constant, location);
281 self.sanitize_constant(constant, location);
282 self.sanitize_type(constant, constant.ty);
284 if let Some(user_ty) = constant.user_ty {
285 if let Err(terr) = self.cx.relate_type_and_user_type(
287 ty::Variance::Invariant,
288 &UserTypeProjection { base: user_ty, projs: vec![], },
289 location.to_locations(),
290 ConstraintCategory::Boring,
295 "bad constant user type {:?} vs {:?}: {:?}",
304 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
305 self.super_rvalue(rvalue, location);
306 let rval_ty = rvalue.ty(self.mir, self.tcx());
307 self.sanitize_type(rvalue, rval_ty);
310 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
311 self.super_local_decl(local, local_decl);
312 self.sanitize_type(local_decl, local_decl.ty);
314 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
315 if let Err(terr) = self.cx.relate_type_and_user_type(
317 ty::Variance::Invariant,
319 Locations::All(*span),
320 ConstraintCategory::TypeAnnotation,
325 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
335 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
336 self.sanitize_type(&"return type", mir.return_ty());
337 for local_decl in &mir.local_decls {
338 self.sanitize_type(local_decl, local_decl.ty);
340 if self.errors_reported {
347 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
348 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
351 mir_def_id: cx.mir_def_id,
354 errors_reported: false,
358 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
362 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
363 if ty.has_escaping_bound_vars() || ty.references_error() {
364 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
370 /// Checks that the constant's `ty` field matches up with what
371 /// would be expected from its literal.
372 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
374 "sanitize_constant(constant={:?}, location={:?})",
378 // FIXME(#46702) -- We need some way to get the predicates
379 // associated with the "pre-evaluated" form of the
380 // constant. For example, consider that the constant
381 // may have associated constant projections (`<Foo as
382 // Trait<'a, 'b>>::SOME_CONST`) that impose
383 // constraints on `'a` and `'b`. These constraints
384 // would be lost if we just look at the normalized
386 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
387 let tcx = self.tcx();
388 let type_checker = &mut self.cx;
390 // FIXME -- For now, use the substitutions from
391 // `value.ty` rather than `value.val`. The
392 // renumberer will rewrite them to independent
393 // sets of regions; in principle, we ought to
394 // derive the type of the `value.val` from "first
395 // principles" and equate with value.ty, but as we
396 // are transitioning to the miri-based system, we
397 // don't have a handy function for that, so for
398 // now we just ignore `value.val` regions.
400 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
401 type_checker.normalize_and_prove_instantiated_predicates(
402 instantiated_predicates,
403 location.to_locations(),
407 debug!("sanitize_constant: expected_ty={:?}", constant.literal.ty);
409 if let Err(terr) = self.cx.eq_types(
412 location.to_locations(),
413 ConstraintCategory::Boring,
418 "constant {:?} should have type {:?} but has {:?} ({:?})",
427 /// Checks that the types internal to the `place` match up with
428 /// what would be expected.
433 context: PlaceContext,
435 debug!("sanitize_place: {:?}", place);
436 let place_ty = match *place {
437 Place::Local(index) => PlaceTy::Ty {
438 ty: self.mir.local_decls[index].ty,
440 Place::Promoted(box (_index, sty)) => {
441 let sty = self.sanitize_type(place, sty);
442 // FIXME -- promoted MIR return types reference
443 // various "free regions" (e.g., scopes and things)
444 // that they ought not to do. We have to figure out
445 // how best to handle that -- probably we want treat
446 // promoted MIR much like closures, renumbering all
447 // their free regions and propagating constraints
448 // upwards. We have the same acyclic guarantees, so
449 // that should be possible. But for now, ignore them.
451 // let promoted_mir = &self.mir.promoted[index];
452 // promoted_mir.return_ty()
453 PlaceTy::Ty { ty: sty }
455 Place::Static(box Static { def_id, ty: sty }) => {
456 let sty = self.sanitize_type(place, sty);
457 let ty = self.tcx().type_of(def_id);
458 let ty = self.cx.normalize(ty, location);
461 .eq_types(ty, sty, location.to_locations(), ConstraintCategory::Boring)
466 "bad static type ({:?}: {:?}): {:?}",
472 PlaceTy::Ty { ty: sty }
474 Place::Projection(ref proj) => {
475 let base_context = if context.is_mutating_use() {
476 PlaceContext::MutatingUse(MutatingUseContext::Projection)
478 PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
480 let base_ty = self.sanitize_place(&proj.base, location, base_context);
481 if let PlaceTy::Ty { ty } = base_ty {
482 if ty.references_error() {
483 assert!(self.errors_reported);
485 ty: self.tcx().types.err,
489 self.sanitize_projection(base_ty, &proj.elem, place, location)
492 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
493 let tcx = self.tcx();
494 let trait_ref = ty::TraitRef {
495 def_id: tcx.lang_items().copy_trait().unwrap(),
496 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
499 // In order to have a Copy operand, the type T of the value must be Copy. Note that we
500 // prove that T: Copy, rather than using the type_moves_by_default test. This is
501 // important because type_moves_by_default ignores the resulting region obligations and
502 // assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
503 // (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
504 // fully apply: in effect, the rule is that if a value of some type could implement
505 // Copy, then it must.
506 self.cx.prove_trait_ref(
508 location.to_locations(),
509 ConstraintCategory::CopyBound,
515 fn sanitize_projection(
518 pi: &PlaceElem<'tcx>,
522 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
523 let tcx = self.tcx();
524 let base_ty = base.to_ty(tcx);
526 ProjectionElem::Deref => {
527 let deref_ty = base_ty.builtin_deref(true);
529 ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
530 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
534 ProjectionElem::Index(i) => {
535 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
536 if index_ty != tcx.types.usize {
538 ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
542 ty: base_ty.builtin_index().unwrap_or_else(|| {
543 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
548 ProjectionElem::ConstantIndex { .. } => {
549 // consider verifying in-bounds
551 ty: base_ty.builtin_index().unwrap_or_else(|| {
552 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
556 ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
557 ty: match base_ty.sty {
558 ty::Array(inner, size) => {
559 let size = size.unwrap_usize(tcx);
560 let min_size = (from as u64) + (to as u64);
561 if let Some(rest_size) = size.checked_sub(min_size) {
562 tcx.mk_array(inner, rest_size)
564 span_mirbug_and_err!(
567 "taking too-small slice of {:?}",
572 ty::Slice(..) => base_ty,
573 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
576 ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
577 ty::Adt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
578 if index.as_usize() >= adt_def.variants.len() {
580 ty: span_mirbug_and_err!(
583 "cast to variant #{:?} but enum only has {:?}",
585 adt_def.variants.len()
592 variant_index: index,
597 ty: span_mirbug_and_err!(
600 "can't downcast {:?} as {:?}",
606 ProjectionElem::Field(field, fty) => {
607 let fty = self.sanitize_type(place, fty);
608 match self.field_ty(place, base, field, location) {
609 Ok(ty) => if let Err(terr) = self.cx.eq_types(
612 location.to_locations(),
613 ConstraintCategory::Boring,
618 "bad field access ({:?}: {:?}): {:?}",
624 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
627 "accessed field #{} but variant only has {}",
632 PlaceTy::Ty { ty: fty }
637 fn error(&mut self) -> Ty<'tcx> {
638 self.errors_reported = true;
644 parent: &dyn fmt::Debug,
645 base_ty: PlaceTy<'tcx>,
648 ) -> Result<Ty<'tcx>, FieldAccessError> {
649 let tcx = self.tcx();
651 let (variant, substs) = match base_ty {
656 } => (&adt_def.variants[variant_index], substs),
657 PlaceTy::Ty { ty } => match ty.sty {
658 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
659 (&adt_def.variants[VariantIdx::new(0)], substs),
660 ty::Closure(def_id, substs) => {
661 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
663 None => Err(FieldAccessError::OutOfRange {
664 field_count: substs.upvar_tys(def_id, tcx).count(),
668 ty::Generator(def_id, substs, _) => {
669 // Try pre-transform fields first (upvars and current state)
670 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
674 // Then try `field_tys` which contains all the fields, but it
675 // requires the final optimized MIR.
676 return match substs.field_tys(def_id, tcx).nth(field.index()) {
678 None => Err(FieldAccessError::OutOfRange {
679 field_count: substs.field_tys(def_id, tcx).count(),
684 return match tys.get(field.index()) {
686 None => Err(FieldAccessError::OutOfRange {
687 field_count: tys.len(),
692 return Ok(span_mirbug_and_err!(
695 "can't project out of {:?}",
702 if let Some(field) = variant.fields.get(field.index()) {
703 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
705 Err(FieldAccessError::OutOfRange {
706 field_count: variant.fields.len(),
712 /// The MIR type checker. Visits the MIR and enforces all the
713 /// constraints needed for it to be valid and well-typed. Along the
714 /// way, it accrues region constraints -- these can later be used by
715 /// NLL region checking.
716 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
717 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
718 param_env: ty::ParamEnv<'gcx>,
722 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
723 implicit_region_bound: Option<ty::Region<'tcx>>,
724 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
725 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
726 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
729 struct BorrowCheckContext<'a, 'tcx: 'a> {
730 universal_regions: &'a UniversalRegions<'tcx>,
731 location_table: &'a LocationTable,
732 all_facts: &'a mut Option<AllFacts>,
733 borrow_set: &'a BorrowSet<'tcx>,
734 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
737 crate struct MirTypeckResults<'tcx> {
738 crate constraints: MirTypeckRegionConstraints<'tcx>,
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 /// Maps from a `ty::Placeholder` to the corresponding
746 /// `PlaceholderIndex` bit that we will use for it.
748 /// To keep everything in sync, do not insert this set
749 /// directly. Instead, use the `placeholder_region` helper.
750 crate placeholder_indices: PlaceholderIndices,
752 /// Each time we add a placeholder to `placeholder_indices`, we
753 /// also create a corresponding "representative" region vid for
754 /// that wraps it. This vector tracks those. This way, when we
755 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
756 /// the same underlying `RegionVid`.
757 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
759 /// In general, the type-checker is not responsible for enforcing
760 /// liveness constraints; this job falls to the region inferencer,
761 /// which performs a liveness analysis. However, in some limited
762 /// cases, the MIR type-checker creates temporary regions that do
763 /// not otherwise appear in the MIR -- in particular, the
764 /// late-bound regions that it instantiates at call-sites -- and
765 /// hence it must report on their liveness constraints.
766 crate liveness_constraints: LivenessValues<RegionVid>,
768 crate outlives_constraints: ConstraintSet,
770 crate closure_bounds_mapping:
771 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
773 crate type_tests: Vec<TypeTest<'tcx>>,
776 impl MirTypeckRegionConstraints<'tcx> {
777 fn placeholder_region(
779 infcx: &InferCtxt<'_, '_, 'tcx>,
780 placeholder: ty::PlaceholderRegion,
781 ) -> ty::Region<'tcx> {
782 let placeholder_index = self.placeholder_indices.insert(placeholder);
783 match self.placeholder_index_to_region.get(placeholder_index) {
786 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
787 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
788 self.placeholder_index_to_region.push(region);
795 /// The `Locations` type summarizes *where* region constraints are
796 /// required to hold. Normally, this is at a particular point which
797 /// created the obligation, but for constraints that the user gave, we
798 /// want the constraint to hold at all points.
799 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
801 /// Indicates that a type constraint should always be true. This
802 /// is particularly important in the new borrowck analysis for
803 /// things like the type of the return slot. Consider this
807 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
809 /// return &y; // error
813 /// Here, we wind up with the signature from the return type being
814 /// something like `&'1 u32` where `'1` is a universal region. But
815 /// the type of the return slot `_0` is something like `&'2 u32`
816 /// where `'2` is an existential region variable. The type checker
817 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
818 /// older NLL analysis, we required this only at the entry point
819 /// to the function. By the nature of the constraints, this wound
820 /// up propagating to all points reachable from start (because
821 /// `'1` -- as a universal region -- is live everywhere). In the
822 /// newer analysis, though, this doesn't work: `_0` is considered
823 /// dead at the start (it has no usable value) and hence this type
824 /// equality is basically a no-op. Then, later on, when we do `_0
825 /// = &'3 y`, that region `'3` never winds up related to the
826 /// universal region `'1` and hence no error occurs. Therefore, we
827 /// use Locations::All instead, which ensures that the `'1` and
828 /// `'2` are equal everything. We also use this for other
829 /// user-given type annotations; e.g., if the user wrote `let mut
830 /// x: &'static u32 = ...`, we would ensure that all values
831 /// assigned to `x` are of `'static` lifetime.
833 /// The span points to the place the constraint arose. For example,
834 /// it points to the type in a user-given type annotation. If
835 /// there's no sensible span then it's DUMMY_SP.
838 /// An outlives constraint that only has to hold at a single location,
839 /// usually it represents a point where references flow from one spot to
840 /// another (e.g., `x = y`)
845 pub fn from_location(&self) -> Option<Location> {
847 Locations::All(_) => None,
848 Locations::Single(from_location) => Some(*from_location),
852 /// Gets a span representing the location.
853 pub fn span(&self, mir: &Mir<'_>) -> Span {
855 Locations::All(span) => *span,
856 Locations::Single(l) => mir.source_info(*l).span,
861 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
863 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
866 param_env: ty::ParamEnv<'gcx>,
867 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
868 implicit_region_bound: Option<ty::Region<'tcx>>,
869 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
870 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
879 implicit_region_bound,
881 reported_errors: Default::default(),
882 universal_region_relations,
886 /// Given some operation `op` that manipulates types, proves
887 /// predicates, or otherwise uses the inference context, executes
888 /// `op` and then executes all the further obligations that `op`
889 /// returns. This will yield a set of outlives constraints amongst
890 /// regions which are extracted and stored as having occurred at
893 /// **Any `rustc::infer` operations that might generate region
894 /// constraints should occur within this method so that those
895 /// constraints can be properly localized!**
896 fn fully_perform_op<R>(
898 locations: Locations,
899 category: ConstraintCategory,
900 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
902 let (r, opt_data) = op.fully_perform(self.infcx)?;
904 if let Some(data) = &opt_data {
905 self.push_region_constraints(locations, category, data);
911 fn push_region_constraints(
913 locations: Locations,
914 category: ConstraintCategory,
915 data: &[QueryRegionConstraint<'tcx>],
918 "push_region_constraints: constraints generated at {:?} are {:#?}",
922 if let Some(ref mut borrowck_context) = self.borrowck_context {
923 constraint_conversion::ConstraintConversion::new(
925 borrowck_context.universal_regions,
926 self.region_bound_pairs,
927 self.implicit_region_bound,
931 &mut borrowck_context.constraints,
932 ).convert_all(&data);
936 /// Convenient wrapper around `relate_tys::relate_types` -- see
937 /// that fn for docs.
943 locations: Locations,
944 category: ConstraintCategory,
946 relate_tys::relate_types(
953 self.borrowck_context.as_mut().map(|x| &mut **x),
961 locations: Locations,
962 category: ConstraintCategory,
964 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
967 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
968 /// variables in `sub` with their inferred definitions and try
969 /// again. This is used for opaque types in places (e.g., `let x:
971 fn sub_types_or_anon(
975 locations: Locations,
976 category: ConstraintCategory,
978 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
979 if let TyKind::Opaque(..) = sup.sty {
980 // When you have `let x: impl Foo = ...` in a closure,
981 // the resulting inferend values are stored with the
982 // def-id of the base function.
983 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
984 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
996 locations: Locations,
997 category: ConstraintCategory,
999 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1002 fn relate_type_and_user_type(
1006 user_ty: &UserTypeProjection<'tcx>,
1007 locations: Locations,
1008 category: ConstraintCategory,
1011 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1012 a, v, user_ty, locations,
1015 match user_ty.base {
1016 UserTypeAnnotation::Ty(canonical_ty) => {
1017 let (ty, _) = self.infcx
1018 .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_ty);
1020 // The `TypeRelating` code assumes that "unresolved inference
1021 // variables" appear in the "a" side, so flip `Contravariant`
1022 // ambient variance to get the right relationship.
1023 let v1 = ty::Contravariant.xform(v);
1025 let tcx = self.infcx.tcx;
1026 let ty = self.normalize(ty, locations);
1028 // We need to follow any provided projetions into the type.
1030 // if we hit a ty var as we descend, then just skip the
1031 // attempt to relate the mir local with any type.
1032 #[derive(Debug)] struct HitTyVar;
1033 let mut curr_projected_ty: Result<PlaceTy, HitTyVar>;
1035 curr_projected_ty = Ok(PlaceTy::from_ty(ty));
1036 for proj in &user_ty.projs {
1037 let projected_ty = if let Ok(projected_ty) = curr_projected_ty {
1042 curr_projected_ty = projected_ty.projection_ty_core(
1043 tcx, proj, |this, field, &()| {
1044 if this.to_ty(tcx).is_ty_var() {
1047 let ty = this.field_ty(tcx, field);
1048 Ok(self.normalize(ty, locations))
1052 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1053 user_ty.base, ty, user_ty.projs, curr_projected_ty);
1055 if let Ok(projected_ty) = curr_projected_ty {
1056 let ty = projected_ty.to_ty(tcx);
1057 self.relate_types(ty, v1, a, locations, category)?;
1060 UserTypeAnnotation::TypeOf(def_id, canonical_substs) => {
1065 .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
1067 let projs = self.infcx.tcx.intern_projs(&user_ty.projs);
1068 self.fully_perform_op(
1071 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1072 a, v, def_id, user_substs, projs,
1081 fn eq_opaque_type_and_type(
1083 revealed_ty: Ty<'tcx>,
1085 anon_owner_def_id: DefId,
1086 locations: Locations,
1087 category: ConstraintCategory,
1090 "eq_opaque_type_and_type( \
1093 revealed_ty, anon_ty
1095 let infcx = self.infcx;
1096 let tcx = infcx.tcx;
1097 let param_env = self.param_env;
1098 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1099 let opaque_type_map = self.fully_perform_op(
1104 let mut obligations = ObligationAccumulator::default();
1106 let dummy_body_id = ObligationCause::dummy().body_id;
1107 let (output_ty, opaque_type_map) =
1108 obligations.add(infcx.instantiate_opaque_types(
1115 "eq_opaque_type_and_type: \
1116 instantiated output_ty={:?} \
1117 opaque_type_map={:#?} \
1119 output_ty, opaque_type_map, revealed_ty
1121 obligations.add(infcx
1122 .at(&ObligationCause::dummy(), param_env)
1123 .eq(output_ty, revealed_ty)?);
1125 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1126 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1127 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1128 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1130 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1131 opaque_decl.concrete_ty,
1132 infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1135 obligations.add(infcx
1136 .at(&ObligationCause::dummy(), param_env)
1137 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1140 debug!("eq_opaque_type_and_type: equated");
1143 value: Some(opaque_type_map),
1144 obligations: obligations.into_vec(),
1147 || "input_output".to_string(),
1151 let universal_region_relations = match self.universal_region_relations {
1153 None => return Ok(()),
1156 // Finally, if we instantiated the anon types successfully, we
1157 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1158 // prove that `T: Iterator` where `T` is the type we
1159 // instantiated it with).
1160 if let Some(opaque_type_map) = opaque_type_map {
1161 for (opaque_def_id, opaque_decl) in opaque_type_map {
1162 self.fully_perform_op(
1164 ConstraintCategory::OpaqueType,
1167 infcx.constrain_opaque_type(
1170 universal_region_relations,
1174 obligations: vec![],
1177 || "opaque_type_map".to_string(),
1185 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1189 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1190 debug!("check_stmt: {:?}", stmt);
1191 let tcx = self.tcx();
1193 StatementKind::Assign(ref place, ref rv) => {
1194 // Assignments to temporaries are not "interesting";
1195 // they are not caused by the user, but rather artifacts
1196 // of lowering. Assignments to other sorts of places *are* interesting
1198 let category = match *place {
1199 Place::Local(RETURN_PLACE) => if let Some(BorrowCheckContext {
1202 defining_ty: DefiningTy::Const(def_id, _),
1206 }) = self.borrowck_context
1208 if tcx.is_static(*def_id).is_some() {
1209 ConstraintCategory::UseAsStatic
1211 ConstraintCategory::UseAsConst
1214 ConstraintCategory::Return
1216 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1217 ConstraintCategory::Boring
1219 _ => ConstraintCategory::Assignment,
1222 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1223 let rv_ty = rv.ty(mir, tcx);
1225 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1230 "bad assignment ({:?} = {:?}): {:?}",
1237 if let Some(user_ty) = self.rvalue_user_ty(rv) {
1238 if let Err(terr) = self.relate_type_and_user_type(
1240 ty::Variance::Invariant,
1241 &UserTypeProjection { base: user_ty, projs: vec![], },
1242 location.to_locations(),
1243 ConstraintCategory::Boring,
1248 "bad user type on rvalue ({:?} = {:?}): {:?}",
1256 self.check_rvalue(mir, rv, location);
1257 if !self.tcx().features().unsized_locals {
1258 let trait_ref = ty::TraitRef {
1259 def_id: tcx.lang_items().sized_trait().unwrap(),
1260 substs: tcx.mk_substs_trait(place_ty, &[]),
1262 self.prove_trait_ref(
1264 location.to_locations(),
1265 ConstraintCategory::SizedBound,
1269 StatementKind::SetDiscriminant {
1273 let place_type = place.ty(mir, tcx).to_ty(tcx);
1274 let adt = match place_type.sty {
1275 TyKind::Adt(adt, _) if adt.is_enum() => adt,
1278 stmt.source_info.span,
1279 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1285 if variant_index.as_usize() >= adt.variants.len() {
1287 stmt.source_info.span,
1288 "bad set discriminant ({:?} = {:?}): value of of range",
1294 StatementKind::AscribeUserType(ref place, variance, box ref c_ty) => {
1295 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1296 if let Err(terr) = self.relate_type_and_user_type(
1300 Locations::All(stmt.source_info.span),
1301 ConstraintCategory::TypeAnnotation,
1306 "bad type assert ({:?} <: {:?}): {:?}",
1313 StatementKind::FakeRead(..)
1314 | StatementKind::StorageLive(..)
1315 | StatementKind::StorageDead(..)
1316 | StatementKind::InlineAsm { .. }
1317 | StatementKind::Retag { .. }
1318 | StatementKind::EscapeToRaw { .. }
1319 | StatementKind::Nop => {}
1323 fn check_terminator(
1326 term: &Terminator<'tcx>,
1327 term_location: Location,
1329 debug!("check_terminator: {:?}", term);
1330 let tcx = self.tcx();
1332 TerminatorKind::Goto { .. }
1333 | TerminatorKind::Resume
1334 | TerminatorKind::Abort
1335 | TerminatorKind::Return
1336 | TerminatorKind::GeneratorDrop
1337 | TerminatorKind::Unreachable
1338 | TerminatorKind::Drop { .. }
1339 | TerminatorKind::FalseEdges { .. }
1340 | TerminatorKind::FalseUnwind { .. } => {
1341 // no checks needed for these
1344 TerminatorKind::DropAndReplace {
1350 let place_ty = location.ty(mir, tcx).to_ty(tcx);
1351 let rv_ty = value.ty(mir, tcx);
1353 let locations = term_location.to_locations();
1355 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1360 "bad DropAndReplace ({:?} = {:?}): {:?}",
1367 TerminatorKind::SwitchInt {
1372 let discr_ty = discr.ty(mir, tcx);
1373 if let Err(terr) = self.sub_types(
1376 term_location.to_locations(),
1377 ConstraintCategory::Assignment,
1382 "bad SwitchInt ({:?} on {:?}): {:?}",
1388 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1389 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1391 // FIXME: check the values
1393 TerminatorKind::Call {
1400 let func_ty = func.ty(mir, tcx);
1401 debug!("check_terminator: call, func_ty={:?}", func_ty);
1402 let sig = match func_ty.sty {
1403 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1405 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1409 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1410 term.source_info.span,
1411 LateBoundRegionConversionTime::FnCall,
1414 let sig = self.normalize(sig, term_location);
1415 self.check_call_dest(mir, term, &sig, destination, term_location);
1417 self.prove_predicates(
1418 sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1419 term_location.to_locations(),
1420 ConstraintCategory::Boring,
1423 // The ordinary liveness rules will ensure that all
1424 // regions in the type of the callee are live here. We
1425 // then further constrain the late-bound regions that
1426 // were instantiated at the call site to be live as
1427 // well. The resulting is that all the input (and
1428 // output) types in the signature must be live, since
1429 // all the inputs that fed into it were live.
1430 for &late_bound_region in map.values() {
1431 if let Some(ref mut borrowck_context) = self.borrowck_context {
1432 let region_vid = borrowck_context
1434 .to_region_vid(late_bound_region);
1437 .liveness_constraints
1438 .add_element(region_vid, term_location);
1442 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1444 TerminatorKind::Assert {
1445 ref cond, ref msg, ..
1447 let cond_ty = cond.ty(mir, tcx);
1448 if cond_ty != tcx.types.bool {
1449 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1452 if let BoundsCheck { ref len, ref index } = *msg {
1453 if len.ty(mir, tcx) != tcx.types.usize {
1454 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1456 if index.ty(mir, tcx) != tcx.types.usize {
1457 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1461 TerminatorKind::Yield { ref value, .. } => {
1462 let value_ty = value.ty(mir, tcx);
1463 match mir.yield_ty {
1464 None => span_mirbug!(self, term, "yield in non-generator"),
1466 if let Err(terr) = self.sub_types(
1469 term_location.to_locations(),
1470 ConstraintCategory::Return,
1475 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1490 term: &Terminator<'tcx>,
1491 sig: &ty::FnSig<'tcx>,
1492 destination: &Option<(Place<'tcx>, BasicBlock)>,
1493 term_location: Location,
1495 let tcx = self.tcx();
1496 match *destination {
1497 Some((ref dest, _target_block)) => {
1498 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1499 let category = match *dest {
1500 Place::Local(RETURN_PLACE) => {
1501 if let Some(BorrowCheckContext {
1504 defining_ty: DefiningTy::Const(def_id, _),
1508 }) = self.borrowck_context
1510 if tcx.is_static(*def_id).is_some() {
1511 ConstraintCategory::UseAsStatic
1513 ConstraintCategory::UseAsConst
1516 ConstraintCategory::Return
1519 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1520 ConstraintCategory::Boring
1522 _ => ConstraintCategory::Assignment,
1525 let locations = term_location.to_locations();
1528 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1533 "call dest mismatch ({:?} <- {:?}): {:?}",
1540 // When `#![feature(unsized_locals)]` is not enabled,
1541 // this check is done at `check_local`.
1542 if self.tcx().features().unsized_locals {
1543 let span = term.source_info.span;
1544 self.ensure_place_sized(dest_ty, span);
1548 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1549 if !sig.output().is_never() {
1550 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1556 fn check_call_inputs(
1559 term: &Terminator<'tcx>,
1560 sig: &ty::FnSig<'tcx>,
1561 args: &[Operand<'tcx>],
1562 term_location: Location,
1563 from_hir_call: bool,
1565 debug!("check_call_inputs({:?}, {:?})", sig, args);
1566 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1567 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1569 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1570 let op_arg_ty = op_arg.ty(mir, self.tcx());
1571 let category = if from_hir_call {
1572 ConstraintCategory::CallArgument
1574 ConstraintCategory::Boring
1577 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1582 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1592 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1593 let is_cleanup = block_data.is_cleanup;
1594 self.last_span = block_data.terminator().source_info.span;
1595 match block_data.terminator().kind {
1596 TerminatorKind::Goto { target } => {
1597 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1599 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1600 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1602 TerminatorKind::Resume => if !is_cleanup {
1603 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1605 TerminatorKind::Abort => if !is_cleanup {
1606 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1608 TerminatorKind::Return => if is_cleanup {
1609 span_mirbug!(self, block_data, "return on cleanup block")
1611 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1612 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1614 TerminatorKind::Yield { resume, drop, .. } => {
1616 span_mirbug!(self, block_data, "yield in cleanup block")
1618 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1619 if let Some(drop) = drop {
1620 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1623 TerminatorKind::Unreachable => {}
1624 TerminatorKind::Drop { target, unwind, .. }
1625 | TerminatorKind::DropAndReplace { target, unwind, .. }
1626 | TerminatorKind::Assert {
1631 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1632 if let Some(unwind) = unwind {
1634 span_mirbug!(self, block_data, "unwind on cleanup block")
1636 self.assert_iscleanup(mir, block_data, unwind, true);
1639 TerminatorKind::Call {
1644 if let &Some((_, target)) = destination {
1645 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1647 if let Some(cleanup) = cleanup {
1649 span_mirbug!(self, block_data, "cleanup on cleanup block")
1651 self.assert_iscleanup(mir, block_data, cleanup, true);
1654 TerminatorKind::FalseEdges {
1656 ref imaginary_targets,
1658 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1659 for target in imaginary_targets {
1660 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1663 TerminatorKind::FalseUnwind {
1667 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1668 if let Some(unwind) = unwind {
1673 "cleanup in cleanup block via false unwind"
1676 self.assert_iscleanup(mir, block_data, unwind, true);
1682 fn assert_iscleanup(
1685 ctxt: &dyn fmt::Debug,
1689 if mir[bb].is_cleanup != iscleanuppad {
1693 "cleanuppad mismatch: {:?} should be {:?}",
1700 fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1701 match mir.local_kind(local) {
1702 LocalKind::ReturnPointer | LocalKind::Arg => {
1703 // return values of normal functions are required to be
1704 // sized by typeck, but return values of ADT constructors are
1705 // not because we don't include a `Self: Sized` bounds on them.
1707 // Unbound parts of arguments were never required to be Sized
1708 // - maybe we should make that a warning.
1711 LocalKind::Var | LocalKind::Temp => {}
1714 // When `#![feature(unsized_locals)]` is enabled, only function calls
1715 // and nullary ops are checked in `check_call_dest`.
1716 if !self.tcx().features().unsized_locals {
1717 let span = local_decl.source_info.span;
1718 let ty = local_decl.ty;
1719 self.ensure_place_sized(ty, span);
1723 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1724 let tcx = self.tcx();
1726 // Erase the regions from `ty` to get a global type. The
1727 // `Sized` bound in no way depends on precise regions, so this
1728 // shouldn't affect `is_sized`.
1729 let gcx = tcx.global_tcx();
1730 let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1731 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1732 // in current MIR construction, all non-control-flow rvalue
1733 // expressions evaluate through `as_temp` or `into` a return
1734 // slot or local, so to find all unsized rvalues it is enough
1735 // to check all temps, return slots and locals.
1736 if let None = self.reported_errors.replace((ty, span)) {
1737 let mut diag = struct_span_err!(
1741 "cannot move a value of type {0}: the size of {0} \
1742 cannot be statically determined",
1746 // While this is located in `nll::typeck` this error is not
1747 // an NLL error, it's a required check to prevent creation
1748 // of unsized rvalues in certain cases:
1749 // * operand of a box expression
1750 // * callee in a call expression
1756 fn aggregate_field_ty(
1758 ak: &AggregateKind<'tcx>,
1761 ) -> Result<Ty<'tcx>, FieldAccessError> {
1762 let tcx = self.tcx();
1765 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1766 let variant = &def.variants[variant_index];
1767 let adj_field_index = active_field_index.unwrap_or(field_index);
1768 if let Some(field) = variant.fields.get(adj_field_index) {
1769 Ok(self.normalize(field.ty(tcx, substs), location))
1771 Err(FieldAccessError::OutOfRange {
1772 field_count: variant.fields.len(),
1776 AggregateKind::Closure(def_id, substs) => {
1777 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1779 None => Err(FieldAccessError::OutOfRange {
1780 field_count: substs.upvar_tys(def_id, tcx).count(),
1784 AggregateKind::Generator(def_id, substs, _) => {
1785 // Try pre-transform fields first (upvars and current state)
1786 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1789 // Then try `field_tys` which contains all the fields, but it
1790 // requires the final optimized MIR.
1791 match substs.field_tys(def_id, tcx).nth(field_index) {
1793 None => Err(FieldAccessError::OutOfRange {
1794 field_count: substs.field_tys(def_id, tcx).count(),
1799 AggregateKind::Array(ty) => Ok(ty),
1800 AggregateKind::Tuple => {
1801 unreachable!("This should have been covered in check_rvalues");
1806 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1807 let tcx = self.tcx();
1810 Rvalue::Aggregate(ak, ops) => {
1811 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1814 Rvalue::Repeat(operand, len) => if *len > 1 {
1815 let operand_ty = operand.ty(mir, tcx);
1817 let trait_ref = ty::TraitRef {
1818 def_id: tcx.lang_items().copy_trait().unwrap(),
1819 substs: tcx.mk_substs_trait(operand_ty, &[]),
1822 self.prove_trait_ref(
1824 location.to_locations(),
1825 ConstraintCategory::CopyBound,
1829 Rvalue::NullaryOp(_, ty) => {
1830 // Even with unsized locals cannot box an unsized value.
1831 if self.tcx().features().unsized_locals {
1832 let span = mir.source_info(location).span;
1833 self.ensure_place_sized(ty, span);
1836 let trait_ref = ty::TraitRef {
1837 def_id: tcx.lang_items().sized_trait().unwrap(),
1838 substs: tcx.mk_substs_trait(ty, &[]),
1841 self.prove_trait_ref(
1843 location.to_locations(),
1844 ConstraintCategory::SizedBound,
1848 Rvalue::Cast(cast_kind, op, ty) => {
1850 CastKind::ReifyFnPointer => {
1851 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1853 // The type that we see in the fcx is like
1854 // `foo::<'a, 'b>`, where `foo` is the path to a
1855 // function definition. When we extract the
1856 // signature, it comes from the `fn_sig` query,
1857 // and hence may contain unnormalized results.
1858 let fn_sig = self.normalize(fn_sig, location);
1860 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1862 if let Err(terr) = self.eq_types(
1865 location.to_locations(),
1866 ConstraintCategory::Cast,
1871 "equating {:?} with {:?} yields {:?}",
1879 CastKind::ClosureFnPointer => {
1880 let sig = match op.ty(mir, tcx).sty {
1881 ty::Closure(def_id, substs) => {
1882 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1886 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1888 if let Err(terr) = self.eq_types(
1891 location.to_locations(),
1892 ConstraintCategory::Cast,
1897 "equating {:?} with {:?} yields {:?}",
1905 CastKind::UnsafeFnPointer => {
1906 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1908 // The type that we see in the fcx is like
1909 // `foo::<'a, 'b>`, where `foo` is the path to a
1910 // function definition. When we extract the
1911 // signature, it comes from the `fn_sig` query,
1912 // and hence may contain unnormalized results.
1913 let fn_sig = self.normalize(fn_sig, location);
1915 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1917 if let Err(terr) = self.eq_types(
1920 location.to_locations(),
1921 ConstraintCategory::Cast,
1926 "equating {:?} with {:?} yields {:?}",
1934 CastKind::Unsize => {
1936 let trait_ref = ty::TraitRef {
1937 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1938 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1941 self.prove_trait_ref(
1943 location.to_locations(),
1944 ConstraintCategory::Cast,
1948 CastKind::Misc => {}
1952 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1953 self.add_reborrow_constraint(location, region, borrowed_place);
1956 // FIXME: These other cases have to be implemented in future PRs
1959 | Rvalue::BinaryOp(..)
1960 | Rvalue::CheckedBinaryOp(..)
1961 | Rvalue::UnaryOp(..)
1962 | Rvalue::Discriminant(..) => {}
1966 /// If this rvalue supports a user-given type annotation, then
1967 /// extract and return it. This represents the final type of the
1968 /// rvalue and will be unified with the inferred type.
1969 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotation<'tcx>> {
1972 | Rvalue::Repeat(..)
1976 | Rvalue::BinaryOp(..)
1977 | Rvalue::CheckedBinaryOp(..)
1978 | Rvalue::NullaryOp(..)
1979 | Rvalue::UnaryOp(..)
1980 | Rvalue::Discriminant(..) => None,
1982 Rvalue::Aggregate(aggregate, _) => match **aggregate {
1983 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
1984 AggregateKind::Array(_) => None,
1985 AggregateKind::Tuple => None,
1986 AggregateKind::Closure(_, _) => None,
1987 AggregateKind::Generator(_, _, _) => None,
1992 fn check_aggregate_rvalue(
1995 rvalue: &Rvalue<'tcx>,
1996 aggregate_kind: &AggregateKind<'tcx>,
1997 operands: &[Operand<'tcx>],
2000 let tcx = self.tcx();
2002 self.prove_aggregate_predicates(aggregate_kind, location);
2004 if *aggregate_kind == AggregateKind::Tuple {
2005 // tuple rvalue field type is always the type of the op. Nothing to check here.
2009 for (i, operand) in operands.iter().enumerate() {
2010 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2011 Ok(field_ty) => field_ty,
2012 Err(FieldAccessError::OutOfRange { field_count }) => {
2016 "accessed field #{} but variant only has {}",
2023 let operand_ty = operand.ty(mir, tcx);
2025 if let Err(terr) = self.sub_types(
2028 location.to_locations(),
2029 ConstraintCategory::Boring,
2034 "{:?} is not a subtype of {:?}: {:?}",
2043 /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
2047 /// - `location`: the location `L` where the borrow expression occurs
2048 /// - `borrow_region`: the region `'a` associated with the borrow
2049 /// - `borrowed_place`: the place `P` being borrowed
2050 fn add_reborrow_constraint(
2053 borrow_region: ty::Region<'tcx>,
2054 borrowed_place: &Place<'tcx>,
2056 // These constraints are only meaningful during borrowck:
2057 let BorrowCheckContext {
2063 } = match self.borrowck_context {
2064 Some(ref mut borrowck_context) => borrowck_context,
2068 // In Polonius mode, we also push a `borrow_region` fact
2069 // linking the loan to the region (in some cases, though,
2070 // there is no loan associated with this borrow expression --
2071 // that occurs when we are borrowing an unsafe place, for
2073 if let Some(all_facts) = all_facts {
2074 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2075 let region_vid = borrow_region.to_region_vid();
2076 all_facts.borrow_region.push((
2079 location_table.mid_index(location),
2084 // If we are reborrowing the referent of another reference, we
2085 // need to add outlives relationships. In a case like `&mut
2086 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2087 // need to ensure that `'b: 'a`.
2089 let mut borrowed_place = borrowed_place;
2092 "add_reborrow_constraint({:?}, {:?}, {:?})",
2093 location, borrow_region, borrowed_place
2095 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2096 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2099 ProjectionElem::Deref => {
2100 let tcx = self.infcx.tcx;
2101 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
2103 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2105 ty::Ref(ref_region, _, mutbl) => {
2106 constraints.outlives_constraints.push(OutlivesConstraint {
2107 sup: ref_region.to_region_vid(),
2108 sub: borrow_region.to_region_vid(),
2109 locations: location.to_locations(),
2110 category: ConstraintCategory::Boring,
2114 hir::Mutability::MutImmutable => {
2115 // Immutable reference. We don't need the base
2116 // to be valid for the entire lifetime of
2120 hir::Mutability::MutMutable => {
2121 // Mutable reference. We *do* need the base
2122 // to be valid, because after the base becomes
2123 // invalid, someone else can use our mutable deref.
2125 // This is in order to make the following function
2128 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2133 // As otherwise you could clone `&mut T` using the
2134 // following function:
2136 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2137 // let my_clone = unsafe_deref(&'a x);
2146 // deref of raw pointer, guaranteed to be valid
2149 ty::Adt(def, _) if def.is_box() => {
2150 // deref of `Box`, need the base to be valid - propagate
2152 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2155 ProjectionElem::Field(..)
2156 | ProjectionElem::Downcast(..)
2157 | ProjectionElem::Index(..)
2158 | ProjectionElem::ConstantIndex { .. }
2159 | ProjectionElem::Subslice { .. } => {
2160 // other field access
2164 // The "propagate" case. We need to check that our base is valid
2165 // for the borrow's lifetime.
2166 borrowed_place = base;
2170 fn prove_aggregate_predicates(
2172 aggregate_kind: &AggregateKind<'tcx>,
2175 let tcx = self.tcx();
2178 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2179 aggregate_kind, location
2182 let instantiated_predicates = match aggregate_kind {
2183 AggregateKind::Adt(def, _, substs, _, _) => {
2184 tcx.predicates_of(def.did).instantiate(tcx, substs)
2187 // For closures, we have some **extra requirements** we
2189 // have to check. In particular, in their upvars and
2190 // signatures, closures often reference various regions
2191 // from the surrounding function -- we call those the
2192 // closure's free regions. When we borrow-check (and hence
2193 // region-check) closures, we may find that the closure
2194 // requires certain relationships between those free
2195 // regions. However, because those free regions refer to
2196 // portions of the CFG of their caller, the closure is not
2197 // in a position to verify those relationships. In that
2198 // case, the requirements get "propagated" to us, and so
2199 // we have to solve them here where we instantiate the
2202 // Despite the opacity of the previous parapgrah, this is
2203 // actually relatively easy to understand in terms of the
2204 // desugaring. A closure gets desugared to a struct, and
2205 // these extra requirements are basically like where
2206 // clauses on the struct.
2207 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2208 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2209 self.prove_closure_bounds(tcx, *def_id, substs, location)
2212 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2215 self.normalize_and_prove_instantiated_predicates(
2216 instantiated_predicates,
2217 location.to_locations(),
2221 fn prove_closure_bounds(
2223 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2225 substs: &'tcx Substs<'tcx>,
2227 ) -> ty::InstantiatedPredicates<'tcx> {
2228 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2229 let closure_constraints =
2230 closure_region_requirements.apply_requirements(tcx, location, def_id, substs);
2232 if let Some(ref mut borrowck_context) = self.borrowck_context {
2233 let bounds_mapping = closure_constraints
2236 .filter_map(|(idx, constraint)| {
2237 let ty::OutlivesPredicate(k1, r2) =
2238 constraint.no_bound_vars().unwrap_or_else(|| {
2239 bug!("query_constraint {:?} contained bound vars", constraint,);
2243 UnpackedKind::Lifetime(r1) => {
2244 // constraint is r1: r2
2245 let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
2246 let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
2247 let outlives_requirements =
2248 &closure_region_requirements.outlives_requirements[idx];
2252 outlives_requirements.category,
2253 outlives_requirements.blame_span,
2257 UnpackedKind::Type(_) => None,
2262 let existing = borrowck_context
2264 .closure_bounds_mapping
2265 .insert(location, bounds_mapping);
2268 "Multiple closures at the same location."
2272 self.push_region_constraints(
2273 location.to_locations(),
2274 ConstraintCategory::ClosureBounds,
2275 &closure_constraints,
2279 tcx.predicates_of(def_id).instantiate(tcx, substs)
2284 trait_ref: ty::TraitRef<'tcx>,
2285 locations: Locations,
2286 category: ConstraintCategory,
2288 self.prove_predicates(
2289 Some(ty::Predicate::Trait(
2290 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2297 fn normalize_and_prove_instantiated_predicates(
2299 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2300 locations: Locations,
2302 for predicate in instantiated_predicates.predicates {
2303 let predicate = self.normalize(predicate, locations);
2304 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2308 fn prove_predicates(
2310 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2311 locations: Locations,
2312 category: ConstraintCategory,
2314 for predicate in predicates {
2316 "prove_predicates(predicate={:?}, locations={:?})",
2317 predicate, locations,
2320 self.prove_predicate(predicate, locations, category);
2326 predicate: ty::Predicate<'tcx>,
2327 locations: Locations,
2328 category: ConstraintCategory,
2331 "prove_predicate(predicate={:?}, location={:?})",
2332 predicate, locations,
2335 let param_env = self.param_env;
2336 self.fully_perform_op(
2339 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2340 ).unwrap_or_else(|NoSolution| {
2341 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2345 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2346 self.last_span = mir.span;
2347 debug!("run_on_mir: {:?}", mir.span);
2349 for (local, local_decl) in mir.local_decls.iter_enumerated() {
2350 self.check_local(mir, local, local_decl);
2353 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2354 let mut location = Location {
2358 for stmt in &block_data.statements {
2359 if !stmt.source_info.span.is_dummy() {
2360 self.last_span = stmt.source_info.span;
2362 self.check_stmt(mir, stmt, location);
2363 location.statement_index += 1;
2366 self.check_terminator(mir, block_data.terminator(), location);
2367 self.check_iscleanup(mir, block_data);
2371 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2373 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2375 debug!("normalize(value={:?}, location={:?})", value, location);
2376 let param_env = self.param_env;
2377 self.fully_perform_op(
2378 location.to_locations(),
2379 ConstraintCategory::Boring,
2380 param_env.and(type_op::normalize::Normalize::new(value)),
2381 ).unwrap_or_else(|NoSolution| {
2382 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2388 pub struct TypeckMir;
2390 impl MirPass for TypeckMir {
2391 fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
2392 let def_id = src.def_id;
2393 debug!("run_pass: {:?}", def_id);
2395 // When NLL is enabled, the borrow checker runs the typeck
2396 // itself, so we don't need this MIR pass anymore.
2397 if tcx.use_mir_borrowck() {
2401 if tcx.sess.err_count() > 0 {
2402 // compiling a broken program can obviously result in a
2403 // broken MIR, so try not to report duplicate errors.
2407 if tcx.is_struct_constructor(def_id) {
2408 // We just assume that the automatically generated struct constructors are
2409 // correct. See the comment in the `mir_borrowck` implementation for an
2410 // explanation why we need this.
2414 let param_env = tcx.param_env(def_id);
2415 tcx.infer_ctxt().enter(|infcx| {
2416 type_check_internal(
2428 // For verification purposes, we just ignore the resulting
2429 // region constraint sets. Not our problem. =)
2434 trait NormalizeLocation: fmt::Debug + Copy {
2435 fn to_locations(self) -> Locations;
2438 impl NormalizeLocation for Locations {
2439 fn to_locations(self) -> Locations {
2444 impl NormalizeLocation for Location {
2445 fn to_locations(self) -> Locations {
2446 Locations::Single(self)
2450 #[derive(Debug, Default)]
2451 struct ObligationAccumulator<'tcx> {
2452 obligations: PredicateObligations<'tcx>,
2455 impl<'tcx> ObligationAccumulator<'tcx> {
2456 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2457 let InferOk { value, obligations } = value;
2458 self.obligations.extend(obligations);
2462 fn into_vec(self) -> PredicateObligations<'tcx> {