1 //! This pass type-checks the MIR to ensure it is not broken.
3 #![allow(unreachable_code)]
5 use crate::borrow_check::borrow_set::BorrowSet;
6 use crate::borrow_check::location::LocationTable;
7 use crate::borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
8 use crate::borrow_check::nll::facts::AllFacts;
9 use crate::borrow_check::nll::region_infer::values::LivenessValues;
10 use crate::borrow_check::nll::region_infer::values::PlaceholderIndex;
11 use crate::borrow_check::nll::region_infer::values::PlaceholderIndices;
12 use crate::borrow_check::nll::region_infer::values::RegionValueElements;
13 use crate::borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
14 use crate::borrow_check::nll::renumber;
15 use crate::borrow_check::nll::type_check::free_region_relations::{
16 CreateResult, UniversalRegionRelations,
18 use crate::borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
19 use crate::borrow_check::nll::ToRegionVid;
20 use crate::dataflow::move_paths::MoveData;
21 use crate::dataflow::FlowAtLocation;
22 use crate::dataflow::MaybeInitializedPlaces;
23 use crate::transform::{MirPass, MirSource};
26 use rustc::hir::def_id::DefId;
27 use rustc::infer::canonical::QueryRegionConstraint;
28 use rustc::infer::outlives::env::RegionBoundPairs;
29 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
30 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
31 use rustc::mir::tcx::PlaceTy;
32 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
34 use rustc::traits::query::type_op;
35 use rustc::traits::query::type_op::custom::CustomTypeOp;
36 use rustc::traits::query::{Fallible, NoSolution};
37 use rustc::traits::{ObligationCause, PredicateObligations};
38 use rustc::ty::fold::TypeFoldable;
39 use rustc::ty::subst::{Subst, Substs, UnpackedKind, UserSubsts};
41 self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TyKind, UserType,
42 CanonicalUserTypeAnnotation, UserTypeAnnotationIndex,
44 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
45 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
46 use rustc::ty::layout::VariantIdx;
49 use syntax_pos::{Span, DUMMY_SP};
51 macro_rules! span_mirbug {
52 ($context:expr, $elem:expr, $($message:tt)*) => ({
53 $crate::borrow_check::nll::type_check::mirbug(
57 "broken MIR in {:?} ({:?}): {}",
60 format_args!($($message)*),
66 macro_rules! span_mirbug_and_err {
67 ($context:expr, $elem:expr, $($message:tt)*) => ({
69 span_mirbug!($context, $elem, $($message)*);
75 mod constraint_conversion;
76 pub mod free_region_relations;
81 /// Type checks the given `mir` in the context of the inference
82 /// context `infcx`. Returns any region constraints that have yet to
83 /// be proven. This result is includes liveness constraints that
84 /// ensure that regions appearing in the types of all local variables
85 /// are live at all points where that local variable may later be
88 /// This phase of type-check ought to be infallible -- this is because
89 /// the original, HIR-based type-check succeeded. So if any errors
90 /// occur here, we will get a `bug!` reported.
94 /// - `infcx` -- inference context to use
95 /// - `param_env` -- parameter environment to use for trait solving
96 /// - `mir` -- MIR to type-check
97 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
98 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
99 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
100 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
101 /// to outlive; should represent the fn body
102 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
103 /// the types of the input parameters found in the MIR itself will be equated with these
104 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
105 /// the type for the RETURN_PLACE will be equated with this
106 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
107 /// constraints for the regions in the types of variables
108 /// - `flow_inits` -- results of a maybe-init dataflow analysis
109 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
110 pub(crate) fn type_check<'gcx, 'tcx>(
111 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
112 param_env: ty::ParamEnv<'gcx>,
115 universal_regions: &Rc<UniversalRegions<'tcx>>,
116 location_table: &LocationTable,
117 borrow_set: &BorrowSet<'tcx>,
118 all_facts: &mut Option<AllFacts>,
119 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
120 move_data: &MoveData<'tcx>,
121 elements: &Rc<RegionValueElements>,
122 ) -> MirTypeckResults<'tcx> {
123 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
124 let mut constraints = MirTypeckRegionConstraints {
125 placeholder_indices: PlaceholderIndices::default(),
126 placeholder_index_to_region: IndexVec::default(),
127 liveness_constraints: LivenessValues::new(elements),
128 outlives_constraints: ConstraintSet::default(),
129 closure_bounds_mapping: Default::default(),
130 type_tests: Vec::default(),
134 universal_region_relations,
136 normalized_inputs_and_output,
137 } = free_region_relations::create(
140 Some(implicit_region_bound),
145 let mut borrowck_context = BorrowCheckContext {
150 constraints: &mut constraints,
159 Some(implicit_region_bound),
160 Some(&mut borrowck_context),
161 Some(&universal_region_relations),
163 cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
164 liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
168 .map(|bcx| translate_outlives_facts(bcx));
174 universal_region_relations,
178 fn type_check_internal<'a, 'gcx, 'tcx, R>(
179 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
181 param_env: ty::ParamEnv<'gcx>,
183 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
184 implicit_region_bound: Option<ty::Region<'tcx>>,
185 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
186 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
187 mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
189 let mut checker = TypeChecker::new(
195 implicit_region_bound,
197 universal_region_relations,
199 let errors_reported = {
200 let mut verifier = TypeVerifier::new(&mut checker, mir);
201 verifier.visit_mir(mir);
202 verifier.errors_reported
205 if !errors_reported {
206 // if verifier failed, don't do further checks to avoid ICEs
207 checker.typeck_mir(mir);
213 fn translate_outlives_facts(cx: &mut BorrowCheckContext<'_, '_>) {
214 if let Some(facts) = cx.all_facts {
215 let location_table = cx.location_table;
218 .extend(cx.constraints.outlives_constraints.iter().flat_map(
219 |constraint: &OutlivesConstraint| {
220 if let Some(from_location) = constraint.locations.from_location() {
221 Either::Left(iter::once((
224 location_table.mid_index(from_location),
230 .map(move |location| (constraint.sup, constraint.sub, location)),
238 fn mirbug(tcx: TyCtxt<'_, '_, '_>, span: Span, msg: &str) {
239 // We sometimes see MIR failures (notably predicate failures) due to
240 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
241 // to avoid reporting bugs in those cases.
242 tcx.sess.diagnostic().delay_span_bug(span, msg);
245 enum FieldAccessError {
246 OutOfRange { field_count: usize },
249 /// Verifies that MIR types are sane to not crash further checks.
251 /// The sanitize_XYZ methods here take an MIR object and compute its
252 /// type, calling `span_mirbug` and returning an error type if there
254 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
255 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
259 errors_reported: bool,
262 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
263 fn visit_span(&mut self, span: &Span) {
264 if !span.is_dummy() {
265 self.last_span = *span;
269 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext<'_>, location: Location) {
270 self.sanitize_place(place, location, context);
273 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
274 self.super_constant(constant, location);
275 self.sanitize_constant(constant, location);
276 self.sanitize_type(constant, constant.ty);
278 if let Some(annotation_index) = constant.user_ty {
279 if let Err(terr) = self.cx.relate_type_and_user_type(
281 ty::Variance::Invariant,
282 &UserTypeProjection { base: annotation_index, projs: vec![], },
283 location.to_locations(),
284 ConstraintCategory::Boring,
286 let annotation = &self.mir.user_type_annotations[annotation_index];
290 "bad constant user type {:?} vs {:?}: {:?}",
297 match *constant.literal {
298 ty::LazyConst::Unevaluated(def_id, substs) => {
299 if let Err(terr) = self.cx.fully_perform_op(
300 location.to_locations(),
301 ConstraintCategory::Boring,
302 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
303 constant.ty, def_id, UserSubsts { substs, user_self_ty: None },
309 "bad constant type {:?} ({:?})",
315 ty::LazyConst::Evaluated(lit) => {
316 if let ty::FnDef(def_id, substs) = lit.ty.sty {
317 let tcx = self.tcx();
319 let instantiated_predicates = tcx
320 .predicates_of(def_id)
321 .instantiate(tcx, substs);
322 self.cx.normalize_and_prove_instantiated_predicates(
323 instantiated_predicates,
324 location.to_locations(),
332 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
333 self.super_rvalue(rvalue, location);
334 let rval_ty = rvalue.ty(self.mir, self.tcx());
335 self.sanitize_type(rvalue, rval_ty);
338 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
339 self.super_local_decl(local, local_decl);
340 self.sanitize_type(local_decl, local_decl.ty);
342 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
343 let ty = if !local_decl.is_nonref_binding() {
344 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
345 // reference so we can check the type annotation for the remaining type.
346 if let ty::Ref(_, rty, _) = local_decl.ty.sty {
349 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
355 if let Err(terr) = self.cx.relate_type_and_user_type(
357 ty::Variance::Invariant,
359 Locations::All(*span),
360 ConstraintCategory::TypeAnnotation,
365 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
375 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
376 self.sanitize_type(&"return type", mir.return_ty());
377 for local_decl in &mir.local_decls {
378 self.sanitize_type(local_decl, local_decl.ty);
380 if self.errors_reported {
387 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
388 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
391 mir_def_id: cx.mir_def_id,
394 errors_reported: false,
398 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
402 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
403 if ty.has_escaping_bound_vars() || ty.references_error() {
404 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
410 /// Checks that the constant's `ty` field matches up with what would be
411 /// expected from its literal. Unevaluated constants and well-formed
412 /// constraints are checked by `visit_constant`.
413 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
415 "sanitize_constant(constant={:?}, location={:?})",
419 let literal = match constant.literal {
420 ty::LazyConst::Evaluated(lit) => lit,
421 ty::LazyConst::Unevaluated(..) => return,
424 debug!("sanitize_constant: expected_ty={:?}", literal.ty);
426 if let Err(terr) = self.cx.eq_types(
429 location.to_locations(),
430 ConstraintCategory::Boring,
435 "constant {:?} should have type {:?} but has {:?} ({:?})",
444 /// Checks that the types internal to the `place` match up with
445 /// what would be expected.
450 context: PlaceContext<'_>,
452 debug!("sanitize_place: {:?}", place);
453 let place_ty = match *place {
454 Place::Local(index) => PlaceTy::Ty {
455 ty: self.mir.local_decls[index].ty,
457 Place::Promoted(box (_index, sty)) => {
458 let sty = self.sanitize_type(place, sty);
459 // FIXME -- promoted MIR return types reference
460 // various "free regions" (e.g., scopes and things)
461 // that they ought not to do. We have to figure out
462 // how best to handle that -- probably we want treat
463 // promoted MIR much like closures, renumbering all
464 // their free regions and propagating constraints
465 // upwards. We have the same acyclic guarantees, so
466 // that should be possible. But for now, ignore them.
468 // let promoted_mir = &self.mir.promoted[index];
469 // promoted_mir.return_ty()
470 PlaceTy::Ty { ty: sty }
472 Place::Static(box Static { def_id, ty: sty }) => {
473 let sty = self.sanitize_type(place, sty);
474 let ty = self.tcx().type_of(def_id);
475 let ty = self.cx.normalize(ty, location);
478 .eq_types(ty, sty, location.to_locations(), ConstraintCategory::Boring)
483 "bad static type ({:?}: {:?}): {:?}",
489 PlaceTy::Ty { ty: sty }
491 Place::Projection(ref proj) => {
492 let base_context = if context.is_mutating_use() {
493 PlaceContext::MutatingUse(MutatingUseContext::Projection)
495 PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
497 let base_ty = self.sanitize_place(&proj.base, location, base_context);
498 if let PlaceTy::Ty { ty } = base_ty {
499 if ty.references_error() {
500 assert!(self.errors_reported);
502 ty: self.tcx().types.err,
506 self.sanitize_projection(base_ty, &proj.elem, place, location)
509 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
510 let tcx = self.tcx();
511 let trait_ref = ty::TraitRef {
512 def_id: tcx.lang_items().copy_trait().unwrap(),
513 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
516 // In order to have a Copy operand, the type T of the
517 // value must be Copy. Note that we prove that T: Copy,
518 // rather than using the `is_copy_modulo_regions`
519 // test. This is important because
520 // `is_copy_modulo_regions` ignores the resulting region
521 // obligations and assumes they pass. This can result in
522 // bounds from Copy impls being unsoundly ignored (e.g.,
523 // #29149). Note that we decide to use Copy before knowing
524 // whether the bounds fully apply: in effect, the rule is
525 // that if a value of some type could implement Copy, then
527 self.cx.prove_trait_ref(
529 location.to_locations(),
530 ConstraintCategory::CopyBound,
536 fn sanitize_projection(
539 pi: &PlaceElem<'tcx>,
543 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
544 let tcx = self.tcx();
545 let base_ty = base.to_ty(tcx);
547 ProjectionElem::Deref => {
548 let deref_ty = base_ty.builtin_deref(true);
550 ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
551 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
555 ProjectionElem::Index(i) => {
556 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
557 if index_ty != tcx.types.usize {
559 ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
563 ty: base_ty.builtin_index().unwrap_or_else(|| {
564 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
569 ProjectionElem::ConstantIndex { .. } => {
570 // consider verifying in-bounds
572 ty: base_ty.builtin_index().unwrap_or_else(|| {
573 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
577 ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
578 ty: match base_ty.sty {
579 ty::Array(inner, size) => {
580 let size = size.unwrap_usize(tcx);
581 let min_size = (from as u64) + (to as u64);
582 if let Some(rest_size) = size.checked_sub(min_size) {
583 tcx.mk_array(inner, rest_size)
585 span_mirbug_and_err!(
588 "taking too-small slice of {:?}",
593 ty::Slice(..) => base_ty,
594 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
597 ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
598 ty::Adt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
599 if index.as_usize() >= adt_def.variants.len() {
601 ty: span_mirbug_and_err!(
604 "cast to variant #{:?} but enum only has {:?}",
606 adt_def.variants.len()
613 variant_index: index,
618 ty: span_mirbug_and_err!(
621 "can't downcast {:?} as {:?}",
627 ProjectionElem::Field(field, fty) => {
628 let fty = self.sanitize_type(place, fty);
629 match self.field_ty(place, base, field, location) {
630 Ok(ty) => if let Err(terr) = self.cx.eq_types(
633 location.to_locations(),
634 ConstraintCategory::Boring,
639 "bad field access ({:?}: {:?}): {:?}",
645 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
648 "accessed field #{} but variant only has {}",
653 PlaceTy::Ty { ty: fty }
658 fn error(&mut self) -> Ty<'tcx> {
659 self.errors_reported = true;
665 parent: &dyn fmt::Debug,
666 base_ty: PlaceTy<'tcx>,
669 ) -> Result<Ty<'tcx>, FieldAccessError> {
670 let tcx = self.tcx();
672 let (variant, substs) = match base_ty {
677 } => (&adt_def.variants[variant_index], substs),
678 PlaceTy::Ty { ty } => match ty.sty {
679 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
680 (&adt_def.variants[VariantIdx::new(0)], substs),
681 ty::Closure(def_id, substs) => {
682 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
684 None => Err(FieldAccessError::OutOfRange {
685 field_count: substs.upvar_tys(def_id, tcx).count(),
689 ty::Generator(def_id, substs, _) => {
690 // Try pre-transform fields first (upvars and current state)
691 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
695 // Then try `field_tys` which contains all the fields, but it
696 // requires the final optimized MIR.
697 return match substs.field_tys(def_id, tcx).nth(field.index()) {
699 None => Err(FieldAccessError::OutOfRange {
700 field_count: substs.field_tys(def_id, tcx).count(),
705 return match tys.get(field.index()) {
707 None => Err(FieldAccessError::OutOfRange {
708 field_count: tys.len(),
713 return Ok(span_mirbug_and_err!(
716 "can't project out of {:?}",
723 if let Some(field) = variant.fields.get(field.index()) {
724 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
726 Err(FieldAccessError::OutOfRange {
727 field_count: variant.fields.len(),
733 /// The MIR type checker. Visits the MIR and enforces all the
734 /// constraints needed for it to be valid and well-typed. Along the
735 /// way, it accrues region constraints -- these can later be used by
736 /// NLL region checking.
737 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
738 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
739 param_env: ty::ParamEnv<'gcx>,
743 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
744 implicit_region_bound: Option<ty::Region<'tcx>>,
745 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
746 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
747 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
750 struct BorrowCheckContext<'a, 'tcx: 'a> {
751 universal_regions: &'a UniversalRegions<'tcx>,
752 location_table: &'a LocationTable,
753 all_facts: &'a mut Option<AllFacts>,
754 borrow_set: &'a BorrowSet<'tcx>,
755 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
758 crate struct MirTypeckResults<'tcx> {
759 crate constraints: MirTypeckRegionConstraints<'tcx>,
760 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
763 /// A collection of region constraints that must be satisfied for the
764 /// program to be considered well-typed.
765 crate struct MirTypeckRegionConstraints<'tcx> {
766 /// Maps from a `ty::Placeholder` to the corresponding
767 /// `PlaceholderIndex` bit that we will use for it.
769 /// To keep everything in sync, do not insert this set
770 /// directly. Instead, use the `placeholder_region` helper.
771 crate placeholder_indices: PlaceholderIndices,
773 /// Each time we add a placeholder to `placeholder_indices`, we
774 /// also create a corresponding "representative" region vid for
775 /// that wraps it. This vector tracks those. This way, when we
776 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
777 /// the same underlying `RegionVid`.
778 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
780 /// In general, the type-checker is not responsible for enforcing
781 /// liveness constraints; this job falls to the region inferencer,
782 /// which performs a liveness analysis. However, in some limited
783 /// cases, the MIR type-checker creates temporary regions that do
784 /// not otherwise appear in the MIR -- in particular, the
785 /// late-bound regions that it instantiates at call-sites -- and
786 /// hence it must report on their liveness constraints.
787 crate liveness_constraints: LivenessValues<RegionVid>,
789 crate outlives_constraints: ConstraintSet,
791 crate closure_bounds_mapping:
792 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
794 crate type_tests: Vec<TypeTest<'tcx>>,
797 impl MirTypeckRegionConstraints<'tcx> {
798 fn placeholder_region(
800 infcx: &InferCtxt<'_, '_, 'tcx>,
801 placeholder: ty::PlaceholderRegion,
802 ) -> ty::Region<'tcx> {
803 let placeholder_index = self.placeholder_indices.insert(placeholder);
804 match self.placeholder_index_to_region.get(placeholder_index) {
807 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
808 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
809 self.placeholder_index_to_region.push(region);
816 /// The `Locations` type summarizes *where* region constraints are
817 /// required to hold. Normally, this is at a particular point which
818 /// created the obligation, but for constraints that the user gave, we
819 /// want the constraint to hold at all points.
820 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
822 /// Indicates that a type constraint should always be true. This
823 /// is particularly important in the new borrowck analysis for
824 /// things like the type of the return slot. Consider this
828 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
830 /// return &y; // error
834 /// Here, we wind up with the signature from the return type being
835 /// something like `&'1 u32` where `'1` is a universal region. But
836 /// the type of the return slot `_0` is something like `&'2 u32`
837 /// where `'2` is an existential region variable. The type checker
838 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
839 /// older NLL analysis, we required this only at the entry point
840 /// to the function. By the nature of the constraints, this wound
841 /// up propagating to all points reachable from start (because
842 /// `'1` -- as a universal region -- is live everywhere). In the
843 /// newer analysis, though, this doesn't work: `_0` is considered
844 /// dead at the start (it has no usable value) and hence this type
845 /// equality is basically a no-op. Then, later on, when we do `_0
846 /// = &'3 y`, that region `'3` never winds up related to the
847 /// universal region `'1` and hence no error occurs. Therefore, we
848 /// use Locations::All instead, which ensures that the `'1` and
849 /// `'2` are equal everything. We also use this for other
850 /// user-given type annotations; e.g., if the user wrote `let mut
851 /// x: &'static u32 = ...`, we would ensure that all values
852 /// assigned to `x` are of `'static` lifetime.
854 /// The span points to the place the constraint arose. For example,
855 /// it points to the type in a user-given type annotation. If
856 /// there's no sensible span then it's DUMMY_SP.
859 /// An outlives constraint that only has to hold at a single location,
860 /// usually it represents a point where references flow from one spot to
861 /// another (e.g., `x = y`)
866 pub fn from_location(&self) -> Option<Location> {
868 Locations::All(_) => None,
869 Locations::Single(from_location) => Some(*from_location),
873 /// Gets a span representing the location.
874 pub fn span(&self, mir: &Mir<'_>) -> Span {
876 Locations::All(span) => *span,
877 Locations::Single(l) => mir.source_info(*l).span,
882 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
884 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
887 param_env: ty::ParamEnv<'gcx>,
888 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
889 implicit_region_bound: Option<ty::Region<'tcx>>,
890 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
891 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
893 let mut checker = Self {
900 implicit_region_bound,
902 reported_errors: Default::default(),
903 universal_region_relations,
905 checker.check_user_type_annotations();
909 /// Equate the inferred type and the annotated type for user type annotations
910 fn check_user_type_annotations(&mut self) {
912 "check_user_type_annotations: user_type_annotations={:?}",
913 self.mir.user_type_annotations
915 for user_annotation in &self.mir.user_type_annotations {
916 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
917 let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
921 UserType::Ty(mut ty) => {
922 ty = self.normalize(ty, Locations::All(span));
924 if let Err(terr) = self.eq_types(
927 Locations::All(span),
928 ConstraintCategory::BoringNoLocation,
933 "bad user type ({:?} = {:?}): {:?}",
940 self.prove_predicate(
941 ty::Predicate::WellFormed(inferred_ty),
942 Locations::All(span),
943 ConstraintCategory::TypeAnnotation,
946 UserType::TypeOf(def_id, user_substs) => {
947 if let Err(terr) = self.fully_perform_op(
948 Locations::All(span),
949 ConstraintCategory::BoringNoLocation,
950 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
951 inferred_ty, def_id, user_substs,
957 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
969 /// Given some operation `op` that manipulates types, proves
970 /// predicates, or otherwise uses the inference context, executes
971 /// `op` and then executes all the further obligations that `op`
972 /// returns. This will yield a set of outlives constraints amongst
973 /// regions which are extracted and stored as having occurred at
976 /// **Any `rustc::infer` operations that might generate region
977 /// constraints should occur within this method so that those
978 /// constraints can be properly localized!**
979 fn fully_perform_op<R>(
981 locations: Locations,
982 category: ConstraintCategory,
983 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
985 let (r, opt_data) = op.fully_perform(self.infcx)?;
987 if let Some(data) = &opt_data {
988 self.push_region_constraints(locations, category, data);
994 fn push_region_constraints(
996 locations: Locations,
997 category: ConstraintCategory,
998 data: &[QueryRegionConstraint<'tcx>],
1001 "push_region_constraints: constraints generated at {:?} are {:#?}",
1005 if let Some(ref mut borrowck_context) = self.borrowck_context {
1006 constraint_conversion::ConstraintConversion::new(
1008 borrowck_context.universal_regions,
1009 self.region_bound_pairs,
1010 self.implicit_region_bound,
1014 &mut borrowck_context.constraints,
1015 ).convert_all(&data);
1019 /// Convenient wrapper around `relate_tys::relate_types` -- see
1020 /// that fn for docs.
1026 locations: Locations,
1027 category: ConstraintCategory,
1029 relate_tys::relate_types(
1036 self.borrowck_context.as_mut().map(|x| &mut **x),
1044 locations: Locations,
1045 category: ConstraintCategory,
1047 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1050 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1051 /// variables in `sub` with their inferred definitions and try
1052 /// again. This is used for opaque types in places (e.g., `let x:
1053 /// impl Foo = ..`).
1054 fn sub_types_or_anon(
1058 locations: Locations,
1059 category: ConstraintCategory,
1061 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1062 if let TyKind::Opaque(..) = sup.sty {
1063 // When you have `let x: impl Foo = ...` in a closure,
1064 // the resulting inferend values are stored with the
1065 // def-id of the base function.
1066 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1067 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1079 locations: Locations,
1080 category: ConstraintCategory,
1082 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1085 fn relate_type_and_user_type(
1089 user_ty: &UserTypeProjection<'tcx>,
1090 locations: Locations,
1091 category: ConstraintCategory,
1094 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1095 a, v, user_ty, locations,
1098 let annotated_type = self.mir.user_type_annotations[user_ty.base].inferred_ty;
1099 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1101 let tcx = self.infcx.tcx;
1103 for proj in &user_ty.projs {
1104 let projected_ty = curr_projected_ty.projection_ty_core(tcx, proj, |this, field, &()| {
1105 let ty = this.field_ty(tcx, field);
1106 self.normalize(ty, locations)
1108 curr_projected_ty = projected_ty;
1110 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1111 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1113 let ty = curr_projected_ty.to_ty(tcx);
1114 self.relate_types(a, v, ty, locations, category)?;
1119 fn eq_opaque_type_and_type(
1121 revealed_ty: Ty<'tcx>,
1123 anon_owner_def_id: DefId,
1124 locations: Locations,
1125 category: ConstraintCategory,
1128 "eq_opaque_type_and_type( \
1131 revealed_ty, anon_ty
1133 let infcx = self.infcx;
1134 let tcx = infcx.tcx;
1135 let param_env = self.param_env;
1136 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1137 let opaque_type_map = self.fully_perform_op(
1142 let mut obligations = ObligationAccumulator::default();
1144 let dummy_body_id = ObligationCause::dummy().body_id;
1145 let (output_ty, opaque_type_map) =
1146 obligations.add(infcx.instantiate_opaque_types(
1153 "eq_opaque_type_and_type: \
1154 instantiated output_ty={:?} \
1155 opaque_type_map={:#?} \
1157 output_ty, opaque_type_map, revealed_ty
1159 obligations.add(infcx
1160 .at(&ObligationCause::dummy(), param_env)
1161 .eq(output_ty, revealed_ty)?);
1163 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1164 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1165 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1166 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1168 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1169 opaque_decl.concrete_ty,
1170 infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1173 obligations.add(infcx
1174 .at(&ObligationCause::dummy(), param_env)
1175 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1178 debug!("eq_opaque_type_and_type: equated");
1181 value: Some(opaque_type_map),
1182 obligations: obligations.into_vec(),
1185 || "input_output".to_string(),
1189 let universal_region_relations = match self.universal_region_relations {
1191 None => return Ok(()),
1194 // Finally, if we instantiated the anon types successfully, we
1195 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1196 // prove that `T: Iterator` where `T` is the type we
1197 // instantiated it with).
1198 if let Some(opaque_type_map) = opaque_type_map {
1199 for (opaque_def_id, opaque_decl) in opaque_type_map {
1200 self.fully_perform_op(
1202 ConstraintCategory::OpaqueType,
1205 infcx.constrain_opaque_type(
1208 universal_region_relations,
1212 obligations: vec![],
1215 || "opaque_type_map".to_string(),
1223 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1227 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1228 debug!("check_stmt: {:?}", stmt);
1229 let tcx = self.tcx();
1231 StatementKind::Assign(ref place, ref rv) => {
1232 // Assignments to temporaries are not "interesting";
1233 // they are not caused by the user, but rather artifacts
1234 // of lowering. Assignments to other sorts of places *are* interesting
1236 let category = match *place {
1237 Place::Local(RETURN_PLACE) => if let Some(BorrowCheckContext {
1240 defining_ty: DefiningTy::Const(def_id, _),
1244 }) = self.borrowck_context
1246 if tcx.is_static(*def_id).is_some() {
1247 ConstraintCategory::UseAsStatic
1249 ConstraintCategory::UseAsConst
1252 ConstraintCategory::Return
1254 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1255 ConstraintCategory::Boring
1257 _ => ConstraintCategory::Assignment,
1260 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1261 let rv_ty = rv.ty(mir, tcx);
1263 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1268 "bad assignment ({:?} = {:?}): {:?}",
1275 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1276 if let Err(terr) = self.relate_type_and_user_type(
1278 ty::Variance::Invariant,
1279 &UserTypeProjection { base: annotation_index, projs: vec![], },
1280 location.to_locations(),
1281 ConstraintCategory::Boring,
1283 let annotation = &mir.user_type_annotations[annotation_index];
1287 "bad user type on rvalue ({:?} = {:?}): {:?}",
1295 self.check_rvalue(mir, rv, location);
1296 if !self.tcx().features().unsized_locals {
1297 let trait_ref = ty::TraitRef {
1298 def_id: tcx.lang_items().sized_trait().unwrap(),
1299 substs: tcx.mk_substs_trait(place_ty, &[]),
1301 self.prove_trait_ref(
1303 location.to_locations(),
1304 ConstraintCategory::SizedBound,
1308 StatementKind::SetDiscriminant {
1312 let place_type = place.ty(mir, tcx).to_ty(tcx);
1313 let adt = match place_type.sty {
1314 TyKind::Adt(adt, _) if adt.is_enum() => adt,
1317 stmt.source_info.span,
1318 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1324 if variant_index.as_usize() >= adt.variants.len() {
1326 stmt.source_info.span,
1327 "bad set discriminant ({:?} = {:?}): value of of range",
1333 StatementKind::AscribeUserType(ref place, variance, box ref projection) => {
1334 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1335 if let Err(terr) = self.relate_type_and_user_type(
1339 Locations::All(stmt.source_info.span),
1340 ConstraintCategory::TypeAnnotation,
1342 let annotation = &mir.user_type_annotations[projection.base];
1346 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1354 StatementKind::FakeRead(..)
1355 | StatementKind::StorageLive(..)
1356 | StatementKind::StorageDead(..)
1357 | StatementKind::InlineAsm { .. }
1358 | StatementKind::Retag { .. }
1359 | StatementKind::Nop => {}
1363 fn check_terminator(
1366 term: &Terminator<'tcx>,
1367 term_location: Location,
1369 debug!("check_terminator: {:?}", term);
1370 let tcx = self.tcx();
1372 TerminatorKind::Goto { .. }
1373 | TerminatorKind::Resume
1374 | TerminatorKind::Abort
1375 | TerminatorKind::Return
1376 | TerminatorKind::GeneratorDrop
1377 | TerminatorKind::Unreachable
1378 | TerminatorKind::Drop { .. }
1379 | TerminatorKind::FalseEdges { .. }
1380 | TerminatorKind::FalseUnwind { .. } => {
1381 // no checks needed for these
1384 TerminatorKind::DropAndReplace {
1390 let place_ty = location.ty(mir, tcx).to_ty(tcx);
1391 let rv_ty = value.ty(mir, tcx);
1393 let locations = term_location.to_locations();
1395 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1400 "bad DropAndReplace ({:?} = {:?}): {:?}",
1407 TerminatorKind::SwitchInt {
1412 let discr_ty = discr.ty(mir, tcx);
1413 if let Err(terr) = self.sub_types(
1416 term_location.to_locations(),
1417 ConstraintCategory::Assignment,
1422 "bad SwitchInt ({:?} on {:?}): {:?}",
1428 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1429 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1431 // FIXME: check the values
1433 TerminatorKind::Call {
1440 let func_ty = func.ty(mir, tcx);
1441 debug!("check_terminator: call, func_ty={:?}", func_ty);
1442 let sig = match func_ty.sty {
1443 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1445 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1449 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1450 term.source_info.span,
1451 LateBoundRegionConversionTime::FnCall,
1454 let sig = self.normalize(sig, term_location);
1455 self.check_call_dest(mir, term, &sig, destination, term_location);
1457 self.prove_predicates(
1458 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1459 term_location.to_locations(),
1460 ConstraintCategory::Boring,
1463 // The ordinary liveness rules will ensure that all
1464 // regions in the type of the callee are live here. We
1465 // then further constrain the late-bound regions that
1466 // were instantiated at the call site to be live as
1467 // well. The resulting is that all the input (and
1468 // output) types in the signature must be live, since
1469 // all the inputs that fed into it were live.
1470 for &late_bound_region in map.values() {
1471 if let Some(ref mut borrowck_context) = self.borrowck_context {
1472 let region_vid = borrowck_context
1474 .to_region_vid(late_bound_region);
1477 .liveness_constraints
1478 .add_element(region_vid, term_location);
1482 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1484 TerminatorKind::Assert {
1485 ref cond, ref msg, ..
1487 let cond_ty = cond.ty(mir, tcx);
1488 if cond_ty != tcx.types.bool {
1489 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1492 if let BoundsCheck { ref len, ref index } = *msg {
1493 if len.ty(mir, tcx) != tcx.types.usize {
1494 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1496 if index.ty(mir, tcx) != tcx.types.usize {
1497 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1501 TerminatorKind::Yield { ref value, .. } => {
1502 let value_ty = value.ty(mir, tcx);
1503 match mir.yield_ty {
1504 None => span_mirbug!(self, term, "yield in non-generator"),
1506 if let Err(terr) = self.sub_types(
1509 term_location.to_locations(),
1510 ConstraintCategory::Yield,
1515 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1530 term: &Terminator<'tcx>,
1531 sig: &ty::FnSig<'tcx>,
1532 destination: &Option<(Place<'tcx>, BasicBlock)>,
1533 term_location: Location,
1535 let tcx = self.tcx();
1536 match *destination {
1537 Some((ref dest, _target_block)) => {
1538 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1539 let category = match *dest {
1540 Place::Local(RETURN_PLACE) => {
1541 if let Some(BorrowCheckContext {
1544 defining_ty: DefiningTy::Const(def_id, _),
1548 }) = self.borrowck_context
1550 if tcx.is_static(*def_id).is_some() {
1551 ConstraintCategory::UseAsStatic
1553 ConstraintCategory::UseAsConst
1556 ConstraintCategory::Return
1559 Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1560 ConstraintCategory::Boring
1562 _ => ConstraintCategory::Assignment,
1565 let locations = term_location.to_locations();
1568 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1573 "call dest mismatch ({:?} <- {:?}): {:?}",
1580 // When `#![feature(unsized_locals)]` is not enabled,
1581 // this check is done at `check_local`.
1582 if self.tcx().features().unsized_locals {
1583 let span = term.source_info.span;
1584 self.ensure_place_sized(dest_ty, span);
1588 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1589 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1595 fn check_call_inputs(
1598 term: &Terminator<'tcx>,
1599 sig: &ty::FnSig<'tcx>,
1600 args: &[Operand<'tcx>],
1601 term_location: Location,
1602 from_hir_call: bool,
1604 debug!("check_call_inputs({:?}, {:?})", sig, args);
1605 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1606 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1608 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1609 let op_arg_ty = op_arg.ty(mir, self.tcx());
1610 let category = if from_hir_call {
1611 ConstraintCategory::CallArgument
1613 ConstraintCategory::Boring
1616 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1621 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1631 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1632 let is_cleanup = block_data.is_cleanup;
1633 self.last_span = block_data.terminator().source_info.span;
1634 match block_data.terminator().kind {
1635 TerminatorKind::Goto { target } => {
1636 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1638 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1639 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1641 TerminatorKind::Resume => if !is_cleanup {
1642 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1644 TerminatorKind::Abort => if !is_cleanup {
1645 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1647 TerminatorKind::Return => if is_cleanup {
1648 span_mirbug!(self, block_data, "return on cleanup block")
1650 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1651 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1653 TerminatorKind::Yield { resume, drop, .. } => {
1655 span_mirbug!(self, block_data, "yield in cleanup block")
1657 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1658 if let Some(drop) = drop {
1659 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1662 TerminatorKind::Unreachable => {}
1663 TerminatorKind::Drop { target, unwind, .. }
1664 | TerminatorKind::DropAndReplace { target, unwind, .. }
1665 | TerminatorKind::Assert {
1670 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1671 if let Some(unwind) = unwind {
1673 span_mirbug!(self, block_data, "unwind on cleanup block")
1675 self.assert_iscleanup(mir, block_data, unwind, true);
1678 TerminatorKind::Call {
1683 if let &Some((_, target)) = destination {
1684 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1686 if let Some(cleanup) = cleanup {
1688 span_mirbug!(self, block_data, "cleanup on cleanup block")
1690 self.assert_iscleanup(mir, block_data, cleanup, true);
1693 TerminatorKind::FalseEdges {
1695 ref imaginary_targets,
1697 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1698 for target in imaginary_targets {
1699 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1702 TerminatorKind::FalseUnwind {
1706 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1707 if let Some(unwind) = unwind {
1712 "cleanup in cleanup block via false unwind"
1715 self.assert_iscleanup(mir, block_data, unwind, true);
1721 fn assert_iscleanup(
1724 ctxt: &dyn fmt::Debug,
1728 if mir[bb].is_cleanup != iscleanuppad {
1732 "cleanuppad mismatch: {:?} should be {:?}",
1739 fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1740 match mir.local_kind(local) {
1741 LocalKind::ReturnPointer | LocalKind::Arg => {
1742 // return values of normal functions are required to be
1743 // sized by typeck, but return values of ADT constructors are
1744 // not because we don't include a `Self: Sized` bounds on them.
1746 // Unbound parts of arguments were never required to be Sized
1747 // - maybe we should make that a warning.
1750 LocalKind::Var | LocalKind::Temp => {}
1753 // When `#![feature(unsized_locals)]` is enabled, only function calls
1754 // and nullary ops are checked in `check_call_dest`.
1755 if !self.tcx().features().unsized_locals {
1756 let span = local_decl.source_info.span;
1757 let ty = local_decl.ty;
1758 self.ensure_place_sized(ty, span);
1762 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1763 let tcx = self.tcx();
1765 // Erase the regions from `ty` to get a global type. The
1766 // `Sized` bound in no way depends on precise regions, so this
1767 // shouldn't affect `is_sized`.
1768 let gcx = tcx.global_tcx();
1769 let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1770 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1771 // in current MIR construction, all non-control-flow rvalue
1772 // expressions evaluate through `as_temp` or `into` a return
1773 // slot or local, so to find all unsized rvalues it is enough
1774 // to check all temps, return slots and locals.
1775 if let None = self.reported_errors.replace((ty, span)) {
1776 let mut diag = struct_span_err!(
1780 "cannot move a value of type {0}: the size of {0} \
1781 cannot be statically determined",
1785 // While this is located in `nll::typeck` this error is not
1786 // an NLL error, it's a required check to prevent creation
1787 // of unsized rvalues in certain cases:
1788 // * operand of a box expression
1789 // * callee in a call expression
1795 fn aggregate_field_ty(
1797 ak: &AggregateKind<'tcx>,
1800 ) -> Result<Ty<'tcx>, FieldAccessError> {
1801 let tcx = self.tcx();
1804 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1805 let variant = &def.variants[variant_index];
1806 let adj_field_index = active_field_index.unwrap_or(field_index);
1807 if let Some(field) = variant.fields.get(adj_field_index) {
1808 Ok(self.normalize(field.ty(tcx, substs), location))
1810 Err(FieldAccessError::OutOfRange {
1811 field_count: variant.fields.len(),
1815 AggregateKind::Closure(def_id, substs) => {
1816 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1818 None => Err(FieldAccessError::OutOfRange {
1819 field_count: substs.upvar_tys(def_id, tcx).count(),
1823 AggregateKind::Generator(def_id, substs, _) => {
1824 // Try pre-transform fields first (upvars and current state)
1825 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1828 // Then try `field_tys` which contains all the fields, but it
1829 // requires the final optimized MIR.
1830 match substs.field_tys(def_id, tcx).nth(field_index) {
1832 None => Err(FieldAccessError::OutOfRange {
1833 field_count: substs.field_tys(def_id, tcx).count(),
1838 AggregateKind::Array(ty) => Ok(ty),
1839 AggregateKind::Tuple => {
1840 unreachable!("This should have been covered in check_rvalues");
1845 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1846 let tcx = self.tcx();
1849 Rvalue::Aggregate(ak, ops) => {
1850 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1853 Rvalue::Repeat(operand, len) => if *len > 1 {
1854 let operand_ty = operand.ty(mir, tcx);
1856 let trait_ref = ty::TraitRef {
1857 def_id: tcx.lang_items().copy_trait().unwrap(),
1858 substs: tcx.mk_substs_trait(operand_ty, &[]),
1861 self.prove_trait_ref(
1863 location.to_locations(),
1864 ConstraintCategory::CopyBound,
1868 Rvalue::NullaryOp(_, ty) => {
1869 // Even with unsized locals cannot box an unsized value.
1870 if self.tcx().features().unsized_locals {
1871 let span = mir.source_info(location).span;
1872 self.ensure_place_sized(ty, span);
1875 let trait_ref = ty::TraitRef {
1876 def_id: tcx.lang_items().sized_trait().unwrap(),
1877 substs: tcx.mk_substs_trait(ty, &[]),
1880 self.prove_trait_ref(
1882 location.to_locations(),
1883 ConstraintCategory::SizedBound,
1887 Rvalue::Cast(cast_kind, op, ty) => {
1889 CastKind::ReifyFnPointer => {
1890 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1892 // The type that we see in the fcx is like
1893 // `foo::<'a, 'b>`, where `foo` is the path to a
1894 // function definition. When we extract the
1895 // signature, it comes from the `fn_sig` query,
1896 // and hence may contain unnormalized results.
1897 let fn_sig = self.normalize(fn_sig, location);
1899 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1901 if let Err(terr) = self.eq_types(
1904 location.to_locations(),
1905 ConstraintCategory::Cast,
1910 "equating {:?} with {:?} yields {:?}",
1918 CastKind::ClosureFnPointer => {
1919 let sig = match op.ty(mir, tcx).sty {
1920 ty::Closure(def_id, substs) => {
1921 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1925 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1927 if let Err(terr) = self.eq_types(
1930 location.to_locations(),
1931 ConstraintCategory::Cast,
1936 "equating {:?} with {:?} yields {:?}",
1944 CastKind::UnsafeFnPointer => {
1945 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1947 // The type that we see in the fcx is like
1948 // `foo::<'a, 'b>`, where `foo` is the path to a
1949 // function definition. When we extract the
1950 // signature, it comes from the `fn_sig` query,
1951 // and hence may contain unnormalized results.
1952 let fn_sig = self.normalize(fn_sig, location);
1954 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1956 if let Err(terr) = self.eq_types(
1959 location.to_locations(),
1960 ConstraintCategory::Cast,
1965 "equating {:?} with {:?} yields {:?}",
1973 CastKind::Unsize => {
1975 let trait_ref = ty::TraitRef {
1976 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1977 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1980 self.prove_trait_ref(
1982 location.to_locations(),
1983 ConstraintCategory::Cast,
1987 CastKind::Misc => {}
1991 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1992 self.add_reborrow_constraint(location, region, borrowed_place);
1995 // FIXME: These other cases have to be implemented in future PRs
1998 | Rvalue::BinaryOp(..)
1999 | Rvalue::CheckedBinaryOp(..)
2000 | Rvalue::UnaryOp(..)
2001 | Rvalue::Discriminant(..) => {}
2005 /// If this rvalue supports a user-given type annotation, then
2006 /// extract and return it. This represents the final type of the
2007 /// rvalue and will be unified with the inferred type.
2008 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2011 | Rvalue::Repeat(..)
2015 | Rvalue::BinaryOp(..)
2016 | Rvalue::CheckedBinaryOp(..)
2017 | Rvalue::NullaryOp(..)
2018 | Rvalue::UnaryOp(..)
2019 | Rvalue::Discriminant(..) => None,
2021 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2022 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2023 AggregateKind::Array(_) => None,
2024 AggregateKind::Tuple => None,
2025 AggregateKind::Closure(_, _) => None,
2026 AggregateKind::Generator(_, _, _) => None,
2031 fn check_aggregate_rvalue(
2034 rvalue: &Rvalue<'tcx>,
2035 aggregate_kind: &AggregateKind<'tcx>,
2036 operands: &[Operand<'tcx>],
2039 let tcx = self.tcx();
2041 self.prove_aggregate_predicates(aggregate_kind, location);
2043 if *aggregate_kind == AggregateKind::Tuple {
2044 // tuple rvalue field type is always the type of the op. Nothing to check here.
2048 for (i, operand) in operands.iter().enumerate() {
2049 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2050 Ok(field_ty) => field_ty,
2051 Err(FieldAccessError::OutOfRange { field_count }) => {
2055 "accessed field #{} but variant only has {}",
2062 let operand_ty = operand.ty(mir, tcx);
2064 if let Err(terr) = self.sub_types(
2067 location.to_locations(),
2068 ConstraintCategory::Boring,
2073 "{:?} is not a subtype of {:?}: {:?}",
2082 /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
2086 /// - `location`: the location `L` where the borrow expression occurs
2087 /// - `borrow_region`: the region `'a` associated with the borrow
2088 /// - `borrowed_place`: the place `P` being borrowed
2089 fn add_reborrow_constraint(
2092 borrow_region: ty::Region<'tcx>,
2093 borrowed_place: &Place<'tcx>,
2095 // These constraints are only meaningful during borrowck:
2096 let BorrowCheckContext {
2102 } = match self.borrowck_context {
2103 Some(ref mut borrowck_context) => borrowck_context,
2107 // In Polonius mode, we also push a `borrow_region` fact
2108 // linking the loan to the region (in some cases, though,
2109 // there is no loan associated with this borrow expression --
2110 // that occurs when we are borrowing an unsafe place, for
2112 if let Some(all_facts) = all_facts {
2113 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2114 let region_vid = borrow_region.to_region_vid();
2115 all_facts.borrow_region.push((
2118 location_table.mid_index(location),
2123 // If we are reborrowing the referent of another reference, we
2124 // need to add outlives relationships. In a case like `&mut
2125 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2126 // need to ensure that `'b: 'a`.
2128 let mut borrowed_place = borrowed_place;
2131 "add_reborrow_constraint({:?}, {:?}, {:?})",
2132 location, borrow_region, borrowed_place
2134 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2135 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2138 ProjectionElem::Deref => {
2139 let tcx = self.infcx.tcx;
2140 let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
2142 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2144 ty::Ref(ref_region, _, mutbl) => {
2145 constraints.outlives_constraints.push(OutlivesConstraint {
2146 sup: ref_region.to_region_vid(),
2147 sub: borrow_region.to_region_vid(),
2148 locations: location.to_locations(),
2149 category: ConstraintCategory::Boring,
2153 hir::Mutability::MutImmutable => {
2154 // Immutable reference. We don't need the base
2155 // to be valid for the entire lifetime of
2159 hir::Mutability::MutMutable => {
2160 // Mutable reference. We *do* need the base
2161 // to be valid, because after the base becomes
2162 // invalid, someone else can use our mutable deref.
2164 // This is in order to make the following function
2167 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2172 // As otherwise you could clone `&mut T` using the
2173 // following function:
2175 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2176 // let my_clone = unsafe_deref(&'a x);
2185 // deref of raw pointer, guaranteed to be valid
2188 ty::Adt(def, _) if def.is_box() => {
2189 // deref of `Box`, need the base to be valid - propagate
2191 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2194 ProjectionElem::Field(..)
2195 | ProjectionElem::Downcast(..)
2196 | ProjectionElem::Index(..)
2197 | ProjectionElem::ConstantIndex { .. }
2198 | ProjectionElem::Subslice { .. } => {
2199 // other field access
2203 // The "propagate" case. We need to check that our base is valid
2204 // for the borrow's lifetime.
2205 borrowed_place = base;
2209 fn prove_aggregate_predicates(
2211 aggregate_kind: &AggregateKind<'tcx>,
2214 let tcx = self.tcx();
2217 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2218 aggregate_kind, location
2221 let instantiated_predicates = match aggregate_kind {
2222 AggregateKind::Adt(def, _, substs, _, _) => {
2223 tcx.predicates_of(def.did).instantiate(tcx, substs)
2226 // For closures, we have some **extra requirements** we
2228 // have to check. In particular, in their upvars and
2229 // signatures, closures often reference various regions
2230 // from the surrounding function -- we call those the
2231 // closure's free regions. When we borrow-check (and hence
2232 // region-check) closures, we may find that the closure
2233 // requires certain relationships between those free
2234 // regions. However, because those free regions refer to
2235 // portions of the CFG of their caller, the closure is not
2236 // in a position to verify those relationships. In that
2237 // case, the requirements get "propagated" to us, and so
2238 // we have to solve them here where we instantiate the
2241 // Despite the opacity of the previous parapgrah, this is
2242 // actually relatively easy to understand in terms of the
2243 // desugaring. A closure gets desugared to a struct, and
2244 // these extra requirements are basically like where
2245 // clauses on the struct.
2246 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2247 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2248 self.prove_closure_bounds(tcx, *def_id, substs, location)
2251 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2254 self.normalize_and_prove_instantiated_predicates(
2255 instantiated_predicates,
2256 location.to_locations(),
2260 fn prove_closure_bounds(
2262 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2264 substs: &'tcx Substs<'tcx>,
2266 ) -> ty::InstantiatedPredicates<'tcx> {
2267 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2268 let closure_constraints =
2269 closure_region_requirements.apply_requirements(tcx, location, def_id, substs);
2271 if let Some(ref mut borrowck_context) = self.borrowck_context {
2272 let bounds_mapping = closure_constraints
2275 .filter_map(|(idx, constraint)| {
2276 let ty::OutlivesPredicate(k1, r2) =
2277 constraint.no_bound_vars().unwrap_or_else(|| {
2278 bug!("query_constraint {:?} contained bound vars", constraint,);
2282 UnpackedKind::Lifetime(r1) => {
2283 // constraint is r1: r2
2284 let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
2285 let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
2286 let outlives_requirements =
2287 &closure_region_requirements.outlives_requirements[idx];
2291 outlives_requirements.category,
2292 outlives_requirements.blame_span,
2296 UnpackedKind::Type(_) => None,
2301 let existing = borrowck_context
2303 .closure_bounds_mapping
2304 .insert(location, bounds_mapping);
2307 "Multiple closures at the same location."
2311 self.push_region_constraints(
2312 location.to_locations(),
2313 ConstraintCategory::ClosureBounds,
2314 &closure_constraints,
2318 tcx.predicates_of(def_id).instantiate(tcx, substs)
2323 trait_ref: ty::TraitRef<'tcx>,
2324 locations: Locations,
2325 category: ConstraintCategory,
2327 self.prove_predicates(
2328 Some(ty::Predicate::Trait(
2329 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2336 fn normalize_and_prove_instantiated_predicates(
2338 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2339 locations: Locations,
2341 for predicate in instantiated_predicates.predicates {
2342 let predicate = self.normalize(predicate, locations);
2343 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2347 fn prove_predicates(
2349 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2350 locations: Locations,
2351 category: ConstraintCategory,
2353 for predicate in predicates {
2355 "prove_predicates(predicate={:?}, locations={:?})",
2356 predicate, locations,
2359 self.prove_predicate(predicate, locations, category);
2365 predicate: ty::Predicate<'tcx>,
2366 locations: Locations,
2367 category: ConstraintCategory,
2370 "prove_predicate(predicate={:?}, location={:?})",
2371 predicate, locations,
2374 let param_env = self.param_env;
2375 self.fully_perform_op(
2378 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2379 ).unwrap_or_else(|NoSolution| {
2380 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2384 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2385 self.last_span = mir.span;
2386 debug!("run_on_mir: {:?}", mir.span);
2388 for (local, local_decl) in mir.local_decls.iter_enumerated() {
2389 self.check_local(mir, local, local_decl);
2392 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2393 let mut location = Location {
2397 for stmt in &block_data.statements {
2398 if !stmt.source_info.span.is_dummy() {
2399 self.last_span = stmt.source_info.span;
2401 self.check_stmt(mir, stmt, location);
2402 location.statement_index += 1;
2405 self.check_terminator(mir, block_data.terminator(), location);
2406 self.check_iscleanup(mir, block_data);
2410 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2412 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2414 debug!("normalize(value={:?}, location={:?})", value, location);
2415 let param_env = self.param_env;
2416 self.fully_perform_op(
2417 location.to_locations(),
2418 ConstraintCategory::Boring,
2419 param_env.and(type_op::normalize::Normalize::new(value)),
2420 ).unwrap_or_else(|NoSolution| {
2421 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2427 pub struct TypeckMir;
2429 impl MirPass for TypeckMir {
2430 fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
2431 let def_id = src.def_id;
2432 debug!("run_pass: {:?}", def_id);
2434 // When NLL is enabled, the borrow checker runs the typeck
2435 // itself, so we don't need this MIR pass anymore.
2436 if tcx.use_mir_borrowck() {
2440 if tcx.sess.err_count() > 0 {
2441 // compiling a broken program can obviously result in a
2442 // broken MIR, so try not to report duplicate errors.
2446 if tcx.is_struct_constructor(def_id) {
2447 // We just assume that the automatically generated struct constructors are
2448 // correct. See the comment in the `mir_borrowck` implementation for an
2449 // explanation why we need this.
2453 let param_env = tcx.param_env(def_id);
2454 tcx.infer_ctxt().enter(|infcx| {
2455 type_check_internal(
2467 // For verification purposes, we just ignore the resulting
2468 // region constraint sets. Not our problem. =)
2473 trait NormalizeLocation: fmt::Debug + Copy {
2474 fn to_locations(self) -> Locations;
2477 impl NormalizeLocation for Locations {
2478 fn to_locations(self) -> Locations {
2483 impl NormalizeLocation for Location {
2484 fn to_locations(self) -> Locations {
2485 Locations::Single(self)
2489 #[derive(Debug, Default)]
2490 struct ObligationAccumulator<'tcx> {
2491 obligations: PredicateObligations<'tcx>,
2494 impl<'tcx> ObligationAccumulator<'tcx> {
2495 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2496 let InferOk { value, obligations } = value;
2497 self.obligations.extend(obligations);
2501 fn into_vec(self) -> PredicateObligations<'tcx> {