]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/type_check/mod.rs
Rollup merge of #53551 - nnethercote:access_place_error_reported, r=varkor
[rust.git] / src / librustc_mir / borrow_check / nll / type_check / mod.rs
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.
4 //
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.
10
11 //! This pass type-checks the MIR to ensure it is not broken.
12 #![allow(unreachable_code)]
13
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::{RegionValueElements, LivenessValues};
19 use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
20 use borrow_check::nll::type_check::free_region_relations::{CreateResult, UniversalRegionRelations};
21 use borrow_check::nll::type_check::liveness::liveness_map::NllLivenessMap;
22 use borrow_check::nll::universal_regions::UniversalRegions;
23 use borrow_check::nll::LocalWithRegion;
24 use borrow_check::nll::ToRegionVid;
25 use dataflow::move_paths::MoveData;
26 use dataflow::FlowAtLocation;
27 use dataflow::MaybeInitializedPlaces;
28 use rustc::hir;
29 use rustc::hir::def_id::DefId;
30 use rustc::infer::canonical::QueryRegionConstraint;
31 use rustc::infer::region_constraints::GenericKind;
32 use rustc::infer::{InferCtxt, LateBoundRegionConversionTime};
33 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
34 use rustc::mir::tcx::PlaceTy;
35 use rustc::mir::visit::{PlaceContext, Visitor};
36 use rustc::mir::*;
37 use rustc::traits::query::type_op;
38 use rustc::traits::query::{Fallible, NoSolution};
39 use rustc::ty::fold::TypeFoldable;
40 use rustc::ty::{self, CanonicalTy, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TypeVariants};
41 use rustc_errors::Diagnostic;
42 use std::fmt;
43 use std::rc::Rc;
44 use syntax_pos::{Span, DUMMY_SP};
45 use transform::{MirPass, MirSource};
46 use util::liveness::LivenessResults;
47
48 use rustc_data_structures::fx::FxHashSet;
49 use rustc_data_structures::indexed_vec::Idx;
50
51 macro_rules! span_mirbug {
52     ($context:expr, $elem:expr, $($message:tt)*) => ({
53         $crate::borrow_check::nll::type_check::mirbug(
54             $context.tcx(),
55             $context.last_span,
56             &format!(
57                 "broken MIR in {:?} ({:?}): {}",
58                 $context.mir_def_id,
59                 $elem,
60                 format_args!($($message)*),
61             ),
62         )
63     })
64 }
65
66 macro_rules! span_mirbug_and_err {
67     ($context:expr, $elem:expr, $($message:tt)*) => ({
68         {
69             span_mirbug!($context, $elem, $($message)*);
70             $context.error()
71         }
72     })
73 }
74
75 mod constraint_conversion;
76 pub mod free_region_relations;
77 mod input_output;
78 crate mod liveness;
79 mod relate_tys;
80
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
86 /// used.
87 ///
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.
91 ///
92 /// # Parameters
93 ///
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 liberaetd, 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 /// - `errors_buffer` -- errors are sent here for future reporting
111 pub(crate) fn type_check<'gcx, 'tcx>(
112     infcx: &InferCtxt<'_, 'gcx, 'tcx>,
113     param_env: ty::ParamEnv<'gcx>,
114     mir: &Mir<'tcx>,
115     mir_def_id: DefId,
116     universal_regions: &Rc<UniversalRegions<'tcx>>,
117     location_table: &LocationTable,
118     borrow_set: &BorrowSet<'tcx>,
119     all_facts: &mut Option<AllFacts>,
120     flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
121     move_data: &MoveData<'tcx>,
122     elements: &Rc<RegionValueElements>,
123     errors_buffer: &mut Vec<Diagnostic>,
124 ) -> MirTypeckResults<'tcx> {
125     let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
126     let mut constraints = MirTypeckRegionConstraints {
127         liveness_constraints: LivenessValues::new(elements),
128         outlives_constraints: ConstraintSet::default(),
129         type_tests: Vec::default(),
130     };
131
132     let CreateResult {
133         universal_region_relations,
134         region_bound_pairs,
135         normalized_inputs_and_output,
136     } = free_region_relations::create(
137         infcx,
138         mir_def_id,
139         param_env,
140         location_table,
141         Some(implicit_region_bound),
142         universal_regions,
143         &mut constraints,
144         all_facts,
145     );
146
147     let (liveness, liveness_map) = {
148         let mut borrowck_context = BorrowCheckContext {
149             universal_regions,
150             location_table,
151             borrow_set,
152             all_facts,
153             constraints: &mut constraints,
154         };
155
156         type_check_internal(
157             infcx,
158             mir_def_id,
159             param_env,
160             mir,
161             &region_bound_pairs,
162             Some(implicit_region_bound),
163             Some(&mut borrowck_context),
164             Some(errors_buffer),
165             |cx| {
166                 cx.equate_inputs_and_outputs(
167                     mir,
168                     mir_def_id,
169                     universal_regions,
170                     &universal_region_relations,
171                     &normalized_inputs_and_output,
172                 );
173                 liveness::generate(cx, mir, flow_inits, move_data)
174             },
175         )
176     };
177
178     MirTypeckResults {
179         constraints,
180         universal_region_relations,
181         liveness,
182         liveness_map,
183     }
184 }
185
186 fn type_check_internal<'a, 'gcx, 'tcx, R>(
187     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
188     mir_def_id: DefId,
189     param_env: ty::ParamEnv<'gcx>,
190     mir: &'a Mir<'tcx>,
191     region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
192     implicit_region_bound: Option<ty::Region<'tcx>>,
193     borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
194     errors_buffer: Option<&mut Vec<Diagnostic>>,
195     mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
196 ) -> R where {
197     let mut checker = TypeChecker::new(
198         infcx,
199         mir,
200         mir_def_id,
201         param_env,
202         region_bound_pairs,
203         implicit_region_bound,
204         borrowck_context,
205     );
206     let errors_reported = {
207         let mut verifier = TypeVerifier::new(&mut checker, mir);
208         verifier.visit_mir(mir);
209         verifier.errors_reported
210     };
211
212     if !errors_reported {
213         // if verifier failed, don't do further checks to avoid ICEs
214         checker.typeck_mir(mir, errors_buffer);
215     }
216
217     extra(&mut checker)
218 }
219
220 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
221     // We sometimes see MIR failures (notably predicate failures) due to
222     // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
223     // to avoid reporting bugs in those cases.
224     tcx.sess.diagnostic().delay_span_bug(span, msg);
225 }
226
227 enum FieldAccessError {
228     OutOfRange { field_count: usize },
229 }
230
231 /// Verifies that MIR types are sane to not crash further checks.
232 ///
233 /// The sanitize_XYZ methods here take an MIR object and compute its
234 /// type, calling `span_mirbug` and returning an error type if there
235 /// is a problem.
236 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
237     cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
238     mir: &'a Mir<'tcx>,
239     last_span: Span,
240     mir_def_id: DefId,
241     errors_reported: bool,
242 }
243
244 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
245     fn visit_span(&mut self, span: &Span) {
246         if !span.is_dummy() {
247             self.last_span = *span;
248         }
249     }
250
251     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
252         self.sanitize_place(place, location, context);
253     }
254
255     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
256         self.super_constant(constant, location);
257         self.sanitize_constant(constant, location);
258         self.sanitize_type(constant, constant.ty);
259     }
260
261     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
262         self.super_rvalue(rvalue, location);
263         let rval_ty = rvalue.ty(self.mir, self.tcx());
264         self.sanitize_type(rvalue, rval_ty);
265     }
266
267     fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
268         self.super_local_decl(local, local_decl);
269         self.sanitize_type(local_decl, local_decl.ty);
270     }
271
272     fn visit_mir(&mut self, mir: &Mir<'tcx>) {
273         self.sanitize_type(&"return type", mir.return_ty());
274         for local_decl in &mir.local_decls {
275             self.sanitize_type(local_decl, local_decl.ty);
276         }
277         if self.errors_reported {
278             return;
279         }
280         self.super_mir(mir);
281     }
282 }
283
284 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
285     fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
286         TypeVerifier {
287             mir,
288             mir_def_id: cx.mir_def_id,
289             cx,
290             last_span: mir.span,
291             errors_reported: false,
292         }
293     }
294
295     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
296         self.cx.infcx.tcx
297     }
298
299     fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
300         if ty.has_escaping_regions() || ty.references_error() {
301             span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
302         } else {
303             ty
304         }
305     }
306
307     /// Checks that the constant's `ty` field matches up with what
308     /// would be expected from its literal.
309     fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
310         debug!(
311             "sanitize_constant(constant={:?}, location={:?})",
312             constant, location
313         );
314
315         // FIXME(#46702) -- We need some way to get the predicates
316         // associated with the "pre-evaluated" form of the
317         // constant. For example, consider that the constant
318         // may have associated constant projections (`<Foo as
319         // Trait<'a, 'b>>::SOME_CONST`) that impose
320         // constraints on `'a` and `'b`. These constraints
321         // would be lost if we just look at the normalized
322         // value.
323         if let ty::TyFnDef(def_id, substs) = constant.literal.ty.sty {
324             let tcx = self.tcx();
325             let type_checker = &mut self.cx;
326
327             // FIXME -- For now, use the substitutions from
328             // `value.ty` rather than `value.val`. The
329             // renumberer will rewrite them to independent
330             // sets of regions; in principle, we ought to
331             // derive the type of the `value.val` from "first
332             // principles" and equate with value.ty, but as we
333             // are transitioning to the miri-based system, we
334             // don't have a handy function for that, so for
335             // now we just ignore `value.val` regions.
336
337             let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
338             type_checker.normalize_and_prove_instantiated_predicates(
339                 instantiated_predicates,
340                 location.boring(),
341             );
342         }
343
344         debug!("sanitize_constant: expected_ty={:?}", constant.literal.ty);
345
346         if let Err(terr) = self
347             .cx
348             .eq_types(constant.literal.ty, constant.ty, location.boring())
349         {
350             span_mirbug!(
351                 self,
352                 constant,
353                 "constant {:?} should have type {:?} but has {:?} ({:?})",
354                 constant,
355                 constant.literal.ty,
356                 constant.ty,
357                 terr,
358             );
359         }
360     }
361
362     /// Checks that the types internal to the `place` match up with
363     /// what would be expected.
364     fn sanitize_place(
365         &mut self,
366         place: &Place<'tcx>,
367         location: Location,
368         context: PlaceContext,
369     ) -> PlaceTy<'tcx> {
370         debug!("sanitize_place: {:?}", place);
371         let place_ty = match *place {
372             Place::Local(index) => PlaceTy::Ty {
373                 ty: self.mir.local_decls[index].ty,
374             },
375             Place::Promoted(box (_index, sty)) => {
376                 let sty = self.sanitize_type(place, sty);
377                 // FIXME -- promoted MIR return types reference
378                 // various "free regions" (e.g., scopes and things)
379                 // that they ought not to do. We have to figure out
380                 // how best to handle that -- probably we want treat
381                 // promoted MIR much like closures, renumbering all
382                 // their free regions and propagating constraints
383                 // upwards. We have the same acyclic guarantees, so
384                 // that should be possible. But for now, ignore them.
385                 //
386                 // let promoted_mir = &self.mir.promoted[index];
387                 // promoted_mir.return_ty()
388                 PlaceTy::Ty { ty: sty }
389             }
390             Place::Static(box Static { def_id, ty: sty }) => {
391                 let sty = self.sanitize_type(place, sty);
392                 let ty = self.tcx().type_of(def_id);
393                 let ty = self.cx.normalize(ty, location);
394                 if let Err(terr) = self.cx.eq_types(ty, sty, location.boring()) {
395                     span_mirbug!(
396                         self,
397                         place,
398                         "bad static type ({:?}: {:?}): {:?}",
399                         ty,
400                         sty,
401                         terr
402                     );
403                 }
404                 PlaceTy::Ty { ty: sty }
405             }
406             Place::Projection(ref proj) => {
407                 let base_context = if context.is_mutating_use() {
408                     PlaceContext::Projection(Mutability::Mut)
409                 } else {
410                     PlaceContext::Projection(Mutability::Not)
411                 };
412                 let base_ty = self.sanitize_place(&proj.base, location, base_context);
413                 if let PlaceTy::Ty { ty } = base_ty {
414                     if ty.references_error() {
415                         assert!(self.errors_reported);
416                         return PlaceTy::Ty {
417                             ty: self.tcx().types.err,
418                         };
419                     }
420                 }
421                 self.sanitize_projection(base_ty, &proj.elem, place, location)
422             }
423         };
424         if let PlaceContext::Copy = context {
425             let tcx = self.tcx();
426             let trait_ref = ty::TraitRef {
427                 def_id: tcx.lang_items().copy_trait().unwrap(),
428                 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
429             };
430
431             // In order to have a Copy operand, the type T of the value must be Copy. Note that we
432             // prove that T: Copy, rather than using the type_moves_by_default test. This is
433             // important because type_moves_by_default ignores the resulting region obligations and
434             // assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
435             // (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
436             // fully apply: in effect, the rule is that if a value of some type could implement
437             // Copy, then it must.
438             self.cx.prove_trait_ref(trait_ref, location.interesting());
439         }
440         place_ty
441     }
442
443     fn sanitize_projection(
444         &mut self,
445         base: PlaceTy<'tcx>,
446         pi: &PlaceElem<'tcx>,
447         place: &Place<'tcx>,
448         location: Location,
449     ) -> PlaceTy<'tcx> {
450         debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
451         let tcx = self.tcx();
452         let base_ty = base.to_ty(tcx);
453         match *pi {
454             ProjectionElem::Deref => {
455                 let deref_ty = base_ty.builtin_deref(true);
456                 PlaceTy::Ty {
457                     ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
458                         span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
459                     }),
460                 }
461             }
462             ProjectionElem::Index(i) => {
463                 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
464                 if index_ty != tcx.types.usize {
465                     PlaceTy::Ty {
466                         ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
467                     }
468                 } else {
469                     PlaceTy::Ty {
470                         ty: base_ty.builtin_index().unwrap_or_else(|| {
471                             span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
472                         }),
473                     }
474                 }
475             }
476             ProjectionElem::ConstantIndex { .. } => {
477                 // consider verifying in-bounds
478                 PlaceTy::Ty {
479                     ty: base_ty.builtin_index().unwrap_or_else(|| {
480                         span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
481                     }),
482                 }
483             }
484             ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
485                 ty: match base_ty.sty {
486                     ty::TyArray(inner, size) => {
487                         let size = size.unwrap_usize(tcx);
488                         let min_size = (from as u64) + (to as u64);
489                         if let Some(rest_size) = size.checked_sub(min_size) {
490                             tcx.mk_array(inner, rest_size)
491                         } else {
492                             span_mirbug_and_err!(
493                                 self,
494                                 place,
495                                 "taking too-small slice of {:?}",
496                                 base_ty
497                             )
498                         }
499                     }
500                     ty::TySlice(..) => base_ty,
501                     _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
502                 },
503             },
504             ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
505                 ty::TyAdt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
506                     if index >= adt_def.variants.len() {
507                         PlaceTy::Ty {
508                             ty: span_mirbug_and_err!(
509                                 self,
510                                 place,
511                                 "cast to variant #{:?} but enum only has {:?}",
512                                 index,
513                                 adt_def.variants.len()
514                             ),
515                         }
516                     } else {
517                         PlaceTy::Downcast {
518                             adt_def,
519                             substs,
520                             variant_index: index,
521                         }
522                     }
523                 }
524                 _ => PlaceTy::Ty {
525                     ty: span_mirbug_and_err!(
526                         self,
527                         place,
528                         "can't downcast {:?} as {:?}",
529                         base_ty,
530                         adt_def1
531                     ),
532                 },
533             },
534             ProjectionElem::Field(field, fty) => {
535                 let fty = self.sanitize_type(place, fty);
536                 match self.field_ty(place, base, field, location) {
537                     Ok(ty) => if let Err(terr) = self.cx.eq_types(ty, fty, location.boring()) {
538                         span_mirbug!(
539                             self,
540                             place,
541                             "bad field access ({:?}: {:?}): {:?}",
542                             ty,
543                             fty,
544                             terr
545                         );
546                     },
547                     Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
548                         self,
549                         place,
550                         "accessed field #{} but variant only has {}",
551                         field.index(),
552                         field_count
553                     ),
554                 }
555                 PlaceTy::Ty { ty: fty }
556             }
557         }
558     }
559
560     fn error(&mut self) -> Ty<'tcx> {
561         self.errors_reported = true;
562         self.tcx().types.err
563     }
564
565     fn field_ty(
566         &mut self,
567         parent: &dyn fmt::Debug,
568         base_ty: PlaceTy<'tcx>,
569         field: Field,
570         location: Location,
571     ) -> Result<Ty<'tcx>, FieldAccessError> {
572         let tcx = self.tcx();
573
574         let (variant, substs) = match base_ty {
575             PlaceTy::Downcast {
576                 adt_def,
577                 substs,
578                 variant_index,
579             } => (&adt_def.variants[variant_index], substs),
580             PlaceTy::Ty { ty } => match ty.sty {
581                 ty::TyAdt(adt_def, substs) if !adt_def.is_enum() => (&adt_def.variants[0], substs),
582                 ty::TyClosure(def_id, substs) => {
583                     return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
584                         Some(ty) => Ok(ty),
585                         None => Err(FieldAccessError::OutOfRange {
586                             field_count: substs.upvar_tys(def_id, tcx).count(),
587                         }),
588                     }
589                 }
590                 ty::TyGenerator(def_id, substs, _) => {
591                     // Try pre-transform fields first (upvars and current state)
592                     if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
593                         return Ok(ty);
594                     }
595
596                     // Then try `field_tys` which contains all the fields, but it
597                     // requires the final optimized MIR.
598                     return match substs.field_tys(def_id, tcx).nth(field.index()) {
599                         Some(ty) => Ok(ty),
600                         None => Err(FieldAccessError::OutOfRange {
601                             field_count: substs.field_tys(def_id, tcx).count(),
602                         }),
603                     };
604                 }
605                 ty::TyTuple(tys) => {
606                     return match tys.get(field.index()) {
607                         Some(&ty) => Ok(ty),
608                         None => Err(FieldAccessError::OutOfRange {
609                             field_count: tys.len(),
610                         }),
611                     }
612                 }
613                 _ => {
614                     return Ok(span_mirbug_and_err!(
615                         self,
616                         parent,
617                         "can't project out of {:?}",
618                         base_ty
619                     ))
620                 }
621             },
622         };
623
624         if let Some(field) = variant.fields.get(field.index()) {
625             Ok(self.cx.normalize(&field.ty(tcx, substs), location))
626         } else {
627             Err(FieldAccessError::OutOfRange {
628                 field_count: variant.fields.len(),
629             })
630         }
631     }
632 }
633
634 /// The MIR type checker. Visits the MIR and enforces all the
635 /// constraints needed for it to be valid and well-typed. Along the
636 /// way, it accrues region constraints -- these can later be used by
637 /// NLL region checking.
638 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
639     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
640     param_env: ty::ParamEnv<'gcx>,
641     last_span: Span,
642     mir: &'a Mir<'tcx>,
643     mir_def_id: DefId,
644     region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
645     implicit_region_bound: Option<ty::Region<'tcx>>,
646     reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
647     borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
648 }
649
650 struct BorrowCheckContext<'a, 'tcx: 'a> {
651     universal_regions: &'a UniversalRegions<'tcx>,
652     location_table: &'a LocationTable,
653     all_facts: &'a mut Option<AllFacts>,
654     borrow_set: &'a BorrowSet<'tcx>,
655     constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
656 }
657
658 crate struct MirTypeckResults<'tcx> {
659     crate constraints: MirTypeckRegionConstraints<'tcx>,
660     crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
661     crate liveness: LivenessResults<LocalWithRegion>,
662     crate liveness_map: NllLivenessMap,
663 }
664
665 /// A collection of region constraints that must be satisfied for the
666 /// program to be considered well-typed.
667 crate struct MirTypeckRegionConstraints<'tcx> {
668     /// In general, the type-checker is not responsible for enforcing
669     /// liveness constraints; this job falls to the region inferencer,
670     /// which performs a liveness analysis. However, in some limited
671     /// cases, the MIR type-checker creates temporary regions that do
672     /// not otherwise appear in the MIR -- in particular, the
673     /// late-bound regions that it instantiates at call-sites -- and
674     /// hence it must report on their liveness constraints.
675     crate liveness_constraints: LivenessValues<RegionVid>,
676
677     crate outlives_constraints: ConstraintSet,
678
679     crate type_tests: Vec<TypeTest<'tcx>>,
680 }
681
682 /// The `Locations` type summarizes *where* region constraints are
683 /// required to hold. Normally, this is at a particular point which
684 /// created the obligation, but for constraints that the user gave, we
685 /// want the constraint to hold at all points.
686 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
687 pub enum Locations {
688     /// Indicates that a type constraint should always be true. This
689     /// is particularly important in the new borrowck analysis for
690     /// things like the type of the return slot. Consider this
691     /// example:
692     ///
693     /// ```
694     /// fn foo<'a>(x: &'a u32) -> &'a u32 {
695     ///     let y = 22;
696     ///     return &y; // error
697     /// }
698     /// ```
699     ///
700     /// Here, we wind up with the signature from the return type being
701     /// something like `&'1 u32` where `'1` is a universal region. But
702     /// the type of the return slot `_0` is something like `&'2 u32`
703     /// where `'2` is an existential region variable. The type checker
704     /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
705     /// older NLL analysis, we required this only at the entry point
706     /// to the function. By the nature of the constraints, this wound
707     /// up propagating to all points reachable from start (because
708     /// `'1` -- as a universal region -- is live everywhere).  In the
709     /// newer analysis, though, this doesn't work: `_0` is considered
710     /// dead at the start (it has no usable value) and hence this type
711     /// equality is basically a no-op. Then, later on, when we do `_0
712     /// = &'3 y`, that region `'3` never winds up related to the
713     /// universal region `'1` and hence no error occurs. Therefore, we
714     /// use Locations::All instead, which ensures that the `'1` and
715     /// `'2` are equal everything. We also use this for other
716     /// user-given type annotations; e.g., if the user wrote `let mut
717     /// x: &'static u32 = ...`, we would ensure that all values
718     /// assigned to `x` are of `'static` lifetime.
719     All,
720
721     /// A "boring" constraint (caused by the given location) is one that
722     /// the user probably doesn't want to see described in diagnostics,
723     /// because it is kind of an artifact of the type system setup.
724     ///
725     /// Example: `x = Foo { field: y }` technically creates
726     /// intermediate regions representing the "type of `Foo { field: y
727     /// }`", and data flows from `y` into those variables, but they
728     /// are not very interesting. The assignment into `x` on the other
729     /// hand might be.
730     Boring(Location),
731
732     /// An *important* outlives constraint (caused by the given
733     /// location) is one that would be useful to highlight in
734     /// diagnostics, because it represents a point where references
735     /// flow from one spot to another (e.g., `x = y`)
736     Interesting(Location),
737 }
738
739 impl Locations {
740     pub fn from_location(&self) -> Option<Location> {
741         match self {
742             Locations::All => None,
743             Locations::Boring(from_location) | Locations::Interesting(from_location) => {
744                 Some(*from_location)
745             }
746         }
747     }
748
749     /// Gets a span representing the location.
750     pub fn span(&self, mir: &Mir<'_>) -> Span {
751         let span_location = match self {
752             Locations::All => Location::START,
753             Locations::Boring(l) | Locations::Interesting(l) => *l,
754         };
755         mir.source_info(span_location).span
756     }
757 }
758
759 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
760     fn new(
761         infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
762         mir: &'a Mir<'tcx>,
763         mir_def_id: DefId,
764         param_env: ty::ParamEnv<'gcx>,
765         region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
766         implicit_region_bound: Option<ty::Region<'tcx>>,
767         borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
768     ) -> Self {
769         TypeChecker {
770             infcx,
771             last_span: DUMMY_SP,
772             mir,
773             mir_def_id,
774             param_env,
775             region_bound_pairs,
776             implicit_region_bound,
777             borrowck_context,
778             reported_errors: FxHashSet(),
779         }
780     }
781
782     /// Given some operation `op` that manipulates types, proves
783     /// predicates, or otherwise uses the inference context, executes
784     /// `op` and then executes all the further obligations that `op`
785     /// returns. This will yield a set of outlives constraints amongst
786     /// regions which are extracted and stored as having occurred at
787     /// `locations`.
788     ///
789     /// **Any `rustc::infer` operations that might generate region
790     /// constraints should occur within this method so that those
791     /// constraints can be properly localized!**
792     fn fully_perform_op<R>(
793         &mut self,
794         locations: Locations,
795         op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
796     ) -> Fallible<R> {
797         let (r, opt_data) = op.fully_perform(self.infcx)?;
798
799         if let Some(data) = &opt_data {
800             self.push_region_constraints(locations, data);
801         }
802
803         Ok(r)
804     }
805
806     fn push_region_constraints(
807         &mut self,
808         locations: Locations,
809         data: &[QueryRegionConstraint<'tcx>],
810     ) {
811         debug!(
812             "push_region_constraints: constraints generated at {:?} are {:#?}",
813             locations, data
814         );
815
816         if let Some(ref mut borrowck_context) = self.borrowck_context {
817             constraint_conversion::ConstraintConversion::new(
818                 self.infcx.tcx,
819                 borrowck_context.universal_regions,
820                 borrowck_context.location_table,
821                 self.region_bound_pairs,
822                 self.implicit_region_bound,
823                 self.param_env,
824                 locations,
825                 &mut borrowck_context.constraints.outlives_constraints,
826                 &mut borrowck_context.constraints.type_tests,
827                 &mut borrowck_context.all_facts,
828             ).convert_all(&data);
829         }
830     }
831
832     fn sub_types(&mut self, sub: Ty<'tcx>, sup: Ty<'tcx>, locations: Locations) -> Fallible<()> {
833         relate_tys::sub_types(
834             self.infcx,
835             sub,
836             sup,
837             locations,
838             self.borrowck_context.as_mut().map(|x| &mut **x),
839         )
840     }
841
842     fn eq_types(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, locations: Locations) -> Fallible<()> {
843         relate_tys::eq_types(
844             self.infcx,
845             a,
846             b,
847             locations,
848             self.borrowck_context.as_mut().map(|x| &mut **x),
849         )
850     }
851
852     fn eq_canonical_type_and_type(
853         &mut self,
854         a: CanonicalTy<'tcx>,
855         b: Ty<'tcx>,
856         locations: Locations,
857     ) -> Fallible<()> {
858         relate_tys::eq_canonical_type_and_type(
859             self.infcx,
860             a,
861             b,
862             locations,
863             self.borrowck_context.as_mut().map(|x| &mut **x),
864         )
865     }
866
867     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
868         self.infcx.tcx
869     }
870
871     fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
872         debug!("check_stmt: {:?}", stmt);
873         let tcx = self.tcx();
874         match stmt.kind {
875             StatementKind::Assign(ref place, ref rv) => {
876                 // Assignments to temporaries are not "interesting";
877                 // they are not caused by the user, but rather artifacts
878                 // of lowering. Assignments to other sorts of places *are* interesting
879                 // though.
880                 let is_temp = if let Place::Local(l) = *place {
881                     l != RETURN_PLACE &&
882                     !mir.local_decls[l].is_user_variable.is_some()
883                 } else {
884                     false
885                 };
886
887                 let locations = if is_temp {
888                     location.boring()
889                 } else {
890                     location.interesting()
891                 };
892
893                 let place_ty = place.ty(mir, tcx).to_ty(tcx);
894                 let rv_ty = rv.ty(mir, tcx);
895                 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
896                     span_mirbug!(
897                         self,
898                         stmt,
899                         "bad assignment ({:?} = {:?}): {:?}",
900                         place_ty,
901                         rv_ty,
902                         terr
903                     );
904                 }
905                 self.check_rvalue(mir, rv, location);
906                 if !self.tcx().features().unsized_locals {
907                     let trait_ref = ty::TraitRef {
908                         def_id: tcx.lang_items().sized_trait().unwrap(),
909                         substs: tcx.mk_substs_trait(place_ty, &[]),
910                     };
911                     self.prove_trait_ref(trait_ref, location.interesting());
912                 }
913             }
914             StatementKind::SetDiscriminant {
915                 ref place,
916                 variant_index,
917             } => {
918                 let place_type = place.ty(mir, tcx).to_ty(tcx);
919                 let adt = match place_type.sty {
920                     TypeVariants::TyAdt(adt, _) if adt.is_enum() => adt,
921                     _ => {
922                         span_bug!(
923                             stmt.source_info.span,
924                             "bad set discriminant ({:?} = {:?}): lhs is not an enum",
925                             place,
926                             variant_index
927                         );
928                     }
929                 };
930                 if variant_index >= adt.variants.len() {
931                     span_bug!(
932                         stmt.source_info.span,
933                         "bad set discriminant ({:?} = {:?}): value of of range",
934                         place,
935                         variant_index
936                     );
937                 };
938             }
939             StatementKind::UserAssertTy(c_ty, local) => {
940                 let local_ty = mir.local_decls()[local].ty;
941                 if let Err(terr) = self.eq_canonical_type_and_type(c_ty, local_ty, Locations::All) {
942                     span_mirbug!(
943                         self,
944                         stmt,
945                         "bad type assert ({:?} = {:?}): {:?}",
946                         c_ty,
947                         local_ty,
948                         terr
949                     );
950                 }
951             }
952             StatementKind::ReadForMatch(_)
953             | StatementKind::StorageLive(_)
954             | StatementKind::StorageDead(_)
955             | StatementKind::InlineAsm { .. }
956             | StatementKind::EndRegion(_)
957             | StatementKind::Validate(..)
958             | StatementKind::Nop => {}
959         }
960     }
961
962     fn check_terminator(
963         &mut self,
964         mir: &Mir<'tcx>,
965         term: &Terminator<'tcx>,
966         term_location: Location,
967         errors_buffer: &mut Option<&mut Vec<Diagnostic>>,
968     ) {
969         debug!("check_terminator: {:?}", term);
970         let tcx = self.tcx();
971         match term.kind {
972             TerminatorKind::Goto { .. }
973             | TerminatorKind::Resume
974             | TerminatorKind::Abort
975             | TerminatorKind::Return
976             | TerminatorKind::GeneratorDrop
977             | TerminatorKind::Unreachable
978             | TerminatorKind::Drop { .. }
979             | TerminatorKind::FalseEdges { .. }
980             | TerminatorKind::FalseUnwind { .. } => {
981                 // no checks needed for these
982             }
983
984             TerminatorKind::DropAndReplace {
985                 ref location,
986                 ref value,
987                 target: _,
988                 unwind: _,
989             } => {
990                 let place_ty = location.ty(mir, tcx).to_ty(tcx);
991                 let rv_ty = value.ty(mir, tcx);
992
993                 let locations = term_location.interesting();
994                 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
995                     span_mirbug!(
996                         self,
997                         term,
998                         "bad DropAndReplace ({:?} = {:?}): {:?}",
999                         place_ty,
1000                         rv_ty,
1001                         terr
1002                     );
1003                 }
1004             }
1005             TerminatorKind::SwitchInt {
1006                 ref discr,
1007                 switch_ty,
1008                 ..
1009             } => {
1010                 let discr_ty = discr.ty(mir, tcx);
1011                 if let Err(terr) = self.sub_types(discr_ty, switch_ty, term_location.boring()) {
1012                     span_mirbug!(
1013                         self,
1014                         term,
1015                         "bad SwitchInt ({:?} on {:?}): {:?}",
1016                         switch_ty,
1017                         discr_ty,
1018                         terr
1019                     );
1020                 }
1021                 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1022                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1023                 }
1024                 // FIXME: check the values
1025             }
1026             TerminatorKind::Call {
1027                 ref func,
1028                 ref args,
1029                 ref destination,
1030                 ..
1031             } => {
1032                 let func_ty = func.ty(mir, tcx);
1033                 debug!("check_terminator: call, func_ty={:?}", func_ty);
1034                 let sig = match func_ty.sty {
1035                     ty::TyFnDef(..) | ty::TyFnPtr(_) => func_ty.fn_sig(tcx),
1036                     _ => {
1037                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1038                         return;
1039                     }
1040                 };
1041                 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
1042                     term.source_info.span,
1043                     LateBoundRegionConversionTime::FnCall,
1044                     &sig,
1045                 );
1046                 let sig = self.normalize(sig, term_location);
1047                 self.check_call_dest(mir, term, &sig, destination, term_location, errors_buffer);
1048
1049                 self.prove_predicates(
1050                     sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1051                     term_location.boring(),
1052                 );
1053
1054                 // The ordinary liveness rules will ensure that all
1055                 // regions in the type of the callee are live here. We
1056                 // then further constrain the late-bound regions that
1057                 // were instantiated at the call site to be live as
1058                 // well. The resulting is that all the input (and
1059                 // output) types in the signature must be live, since
1060                 // all the inputs that fed into it were live.
1061                 for &late_bound_region in map.values() {
1062                     if let Some(ref mut borrowck_context) = self.borrowck_context {
1063                         let region_vid = borrowck_context
1064                             .universal_regions
1065                             .to_region_vid(late_bound_region);
1066                         borrowck_context
1067                             .constraints
1068                             .liveness_constraints
1069                             .add_element(region_vid, term_location);
1070                     }
1071                 }
1072
1073                 self.check_call_inputs(mir, term, &sig, args, term_location);
1074             }
1075             TerminatorKind::Assert {
1076                 ref cond, ref msg, ..
1077             } => {
1078                 let cond_ty = cond.ty(mir, tcx);
1079                 if cond_ty != tcx.types.bool {
1080                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1081                 }
1082
1083                 if let BoundsCheck { ref len, ref index } = *msg {
1084                     if len.ty(mir, tcx) != tcx.types.usize {
1085                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1086                     }
1087                     if index.ty(mir, tcx) != tcx.types.usize {
1088                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1089                     }
1090                 }
1091             }
1092             TerminatorKind::Yield { ref value, .. } => {
1093                 let value_ty = value.ty(mir, tcx);
1094                 match mir.yield_ty {
1095                     None => span_mirbug!(self, term, "yield in non-generator"),
1096                     Some(ty) => {
1097                         if let Err(terr) = self.sub_types(value_ty, ty, term_location.interesting())
1098                         {
1099                             span_mirbug!(
1100                                 self,
1101                                 term,
1102                                 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1103                                 value_ty,
1104                                 ty,
1105                                 terr
1106                             );
1107                         }
1108                     }
1109                 }
1110             }
1111         }
1112     }
1113
1114     fn check_call_dest(
1115         &mut self,
1116         mir: &Mir<'tcx>,
1117         term: &Terminator<'tcx>,
1118         sig: &ty::FnSig<'tcx>,
1119         destination: &Option<(Place<'tcx>, BasicBlock)>,
1120         term_location: Location,
1121         errors_buffer: &mut Option<&mut Vec<Diagnostic>>,
1122     ) {
1123         let tcx = self.tcx();
1124         match *destination {
1125             Some((ref dest, _target_block)) => {
1126                 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1127                 let is_temp = if let Place::Local(l) = *dest {
1128                     l != RETURN_PLACE &&
1129                     !mir.local_decls[l].is_user_variable.is_some()
1130                 } else {
1131                     false
1132                 };
1133
1134                 let locations = if is_temp {
1135                     term_location.boring()
1136                 } else {
1137                     term_location.interesting()
1138                 };
1139
1140                 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations) {
1141                     span_mirbug!(
1142                         self,
1143                         term,
1144                         "call dest mismatch ({:?} <- {:?}): {:?}",
1145                         dest_ty,
1146                         sig.output(),
1147                         terr
1148                     );
1149                 }
1150
1151                 // When `#![feature(unsized_locals)]` is not enabled,
1152                 // this check is done at `check_local`.
1153                 if self.tcx().features().unsized_locals {
1154                     let span = term.source_info.span;
1155                     self.ensure_place_sized(dest_ty, span, errors_buffer);
1156                 }
1157             }
1158             None => {
1159                 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1160                 if !sig.output().is_never() {
1161                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1162                 }
1163             }
1164         }
1165     }
1166
1167     fn check_call_inputs(
1168         &mut self,
1169         mir: &Mir<'tcx>,
1170         term: &Terminator<'tcx>,
1171         sig: &ty::FnSig<'tcx>,
1172         args: &[Operand<'tcx>],
1173         term_location: Location,
1174     ) {
1175         debug!("check_call_inputs({:?}, {:?})", sig, args);
1176         if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1177             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1178         }
1179         for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1180             let op_arg_ty = op_arg.ty(mir, self.tcx());
1181             if let Err(terr) = self.sub_types(op_arg_ty, fn_arg, term_location.interesting()) {
1182                 span_mirbug!(
1183                     self,
1184                     term,
1185                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1186                     n,
1187                     fn_arg,
1188                     op_arg_ty,
1189                     terr
1190                 );
1191             }
1192         }
1193     }
1194
1195     fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1196         let is_cleanup = block_data.is_cleanup;
1197         self.last_span = block_data.terminator().source_info.span;
1198         match block_data.terminator().kind {
1199             TerminatorKind::Goto { target } => {
1200                 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1201             }
1202             TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1203                 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1204             },
1205             TerminatorKind::Resume => if !is_cleanup {
1206                 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1207             },
1208             TerminatorKind::Abort => if !is_cleanup {
1209                 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1210             },
1211             TerminatorKind::Return => if is_cleanup {
1212                 span_mirbug!(self, block_data, "return on cleanup block")
1213             },
1214             TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1215                 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1216             },
1217             TerminatorKind::Yield { resume, drop, .. } => {
1218                 if is_cleanup {
1219                     span_mirbug!(self, block_data, "yield in cleanup block")
1220                 }
1221                 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1222                 if let Some(drop) = drop {
1223                     self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1224                 }
1225             }
1226             TerminatorKind::Unreachable => {}
1227             TerminatorKind::Drop { target, unwind, .. }
1228             | TerminatorKind::DropAndReplace { target, unwind, .. }
1229             | TerminatorKind::Assert {
1230                 target,
1231                 cleanup: unwind,
1232                 ..
1233             } => {
1234                 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1235                 if let Some(unwind) = unwind {
1236                     if is_cleanup {
1237                         span_mirbug!(self, block_data, "unwind on cleanup block")
1238                     }
1239                     self.assert_iscleanup(mir, block_data, unwind, true);
1240                 }
1241             }
1242             TerminatorKind::Call {
1243                 ref destination,
1244                 cleanup,
1245                 ..
1246             } => {
1247                 if let &Some((_, target)) = destination {
1248                     self.assert_iscleanup(mir, block_data, target, is_cleanup);
1249                 }
1250                 if let Some(cleanup) = cleanup {
1251                     if is_cleanup {
1252                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1253                     }
1254                     self.assert_iscleanup(mir, block_data, cleanup, true);
1255                 }
1256             }
1257             TerminatorKind::FalseEdges {
1258                 real_target,
1259                 ref imaginary_targets,
1260             } => {
1261                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1262                 for target in imaginary_targets {
1263                     self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1264                 }
1265             }
1266             TerminatorKind::FalseUnwind {
1267                 real_target,
1268                 unwind,
1269             } => {
1270                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1271                 if let Some(unwind) = unwind {
1272                     if is_cleanup {
1273                         span_mirbug!(
1274                             self,
1275                             block_data,
1276                             "cleanup in cleanup block via false unwind"
1277                         );
1278                     }
1279                     self.assert_iscleanup(mir, block_data, unwind, true);
1280                 }
1281             }
1282         }
1283     }
1284
1285     fn assert_iscleanup(
1286         &mut self,
1287         mir: &Mir<'tcx>,
1288         ctxt: &dyn fmt::Debug,
1289         bb: BasicBlock,
1290         iscleanuppad: bool,
1291     ) {
1292         if mir[bb].is_cleanup != iscleanuppad {
1293             span_mirbug!(
1294                 self,
1295                 ctxt,
1296                 "cleanuppad mismatch: {:?} should be {:?}",
1297                 bb,
1298                 iscleanuppad
1299             );
1300         }
1301     }
1302
1303     fn check_local(
1304         &mut self,
1305         mir: &Mir<'tcx>,
1306         local: Local,
1307         local_decl: &LocalDecl<'tcx>,
1308         errors_buffer: &mut Option<&mut Vec<Diagnostic>>,
1309     ) {
1310         match mir.local_kind(local) {
1311             LocalKind::ReturnPointer | LocalKind::Arg => {
1312                 // return values of normal functions are required to be
1313                 // sized by typeck, but return values of ADT constructors are
1314                 // not because we don't include a `Self: Sized` bounds on them.
1315                 //
1316                 // Unbound parts of arguments were never required to be Sized
1317                 // - maybe we should make that a warning.
1318                 return;
1319             }
1320             LocalKind::Var | LocalKind::Temp => {}
1321         }
1322
1323         // When `#![feature(unsized_locals)]` is enabled, only function calls
1324         // are checked in `check_call_dest`.
1325         if !self.tcx().features().unsized_locals {
1326             let span = local_decl.source_info.span;
1327             let ty = local_decl.ty;
1328             self.ensure_place_sized(ty, span, errors_buffer);
1329         }
1330     }
1331
1332     fn ensure_place_sized(&mut self,
1333                           ty: Ty<'tcx>,
1334                           span: Span,
1335                           errors_buffer: &mut Option<&mut Vec<Diagnostic>>) {
1336         let tcx = self.tcx();
1337
1338         // Erase the regions from `ty` to get a global type.  The
1339         // `Sized` bound in no way depends on precise regions, so this
1340         // shouldn't affect `is_sized`.
1341         let gcx = tcx.global_tcx();
1342         let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1343         if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1344             // in current MIR construction, all non-control-flow rvalue
1345             // expressions evaluate through `as_temp` or `into` a return
1346             // slot or local, so to find all unsized rvalues it is enough
1347             // to check all temps, return slots and locals.
1348             if let None = self.reported_errors.replace((ty, span)) {
1349                 let mut diag = struct_span_err!(
1350                     self.tcx().sess,
1351                     span,
1352                     E0161,
1353                     "cannot move a value of type {0}: the size of {0} \
1354                      cannot be statically determined",
1355                     ty
1356                 );
1357                 if let Some(ref mut errors_buffer) = *errors_buffer {
1358                     diag.buffer(errors_buffer);
1359                 } else {
1360                     // we're allowed to use emit() here because the
1361                     // NLL migration will be turned on (and thus
1362                     // errors will need to be buffered) *only if*
1363                     // errors_buffer is Some.
1364                     diag.emit();
1365                 }
1366             }
1367         }
1368     }
1369
1370     fn aggregate_field_ty(
1371         &mut self,
1372         ak: &AggregateKind<'tcx>,
1373         field_index: usize,
1374         location: Location,
1375     ) -> Result<Ty<'tcx>, FieldAccessError> {
1376         let tcx = self.tcx();
1377
1378         match *ak {
1379             AggregateKind::Adt(def, variant_index, substs, active_field_index) => {
1380                 let variant = &def.variants[variant_index];
1381                 let adj_field_index = active_field_index.unwrap_or(field_index);
1382                 if let Some(field) = variant.fields.get(adj_field_index) {
1383                     Ok(self.normalize(field.ty(tcx, substs), location))
1384                 } else {
1385                     Err(FieldAccessError::OutOfRange {
1386                         field_count: variant.fields.len(),
1387                     })
1388                 }
1389             }
1390             AggregateKind::Closure(def_id, substs) => {
1391                 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1392                     Some(ty) => Ok(ty),
1393                     None => Err(FieldAccessError::OutOfRange {
1394                         field_count: substs.upvar_tys(def_id, tcx).count(),
1395                     }),
1396                 }
1397             }
1398             AggregateKind::Generator(def_id, substs, _) => {
1399                 // Try pre-transform fields first (upvars and current state)
1400                 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1401                     Ok(ty)
1402                 } else {
1403                     // Then try `field_tys` which contains all the fields, but it
1404                     // requires the final optimized MIR.
1405                     match substs.field_tys(def_id, tcx).nth(field_index) {
1406                         Some(ty) => Ok(ty),
1407                         None => Err(FieldAccessError::OutOfRange {
1408                             field_count: substs.field_tys(def_id, tcx).count(),
1409                         }),
1410                     }
1411                 }
1412             }
1413             AggregateKind::Array(ty) => Ok(ty),
1414             AggregateKind::Tuple => {
1415                 unreachable!("This should have been covered in check_rvalues");
1416             }
1417         }
1418     }
1419
1420     fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1421         let tcx = self.tcx();
1422
1423         match rvalue {
1424             Rvalue::Aggregate(ak, ops) => {
1425                 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1426             }
1427
1428             Rvalue::Repeat(operand, len) => if *len > 1 {
1429                 let operand_ty = operand.ty(mir, tcx);
1430
1431                 let trait_ref = ty::TraitRef {
1432                     def_id: tcx.lang_items().copy_trait().unwrap(),
1433                     substs: tcx.mk_substs_trait(operand_ty, &[]),
1434                 };
1435
1436                 self.prove_trait_ref(trait_ref, location.interesting());
1437             },
1438
1439             Rvalue::NullaryOp(_, ty) => {
1440                 let trait_ref = ty::TraitRef {
1441                     def_id: tcx.lang_items().sized_trait().unwrap(),
1442                     substs: tcx.mk_substs_trait(ty, &[]),
1443                 };
1444
1445                 self.prove_trait_ref(trait_ref, location.interesting());
1446             }
1447
1448             Rvalue::Cast(cast_kind, op, ty) => match cast_kind {
1449                 CastKind::ReifyFnPointer => {
1450                     let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1451
1452                     // The type that we see in the fcx is like
1453                     // `foo::<'a, 'b>`, where `foo` is the path to a
1454                     // function definition. When we extract the
1455                     // signature, it comes from the `fn_sig` query,
1456                     // and hence may contain unnormalized results.
1457                     let fn_sig = self.normalize(fn_sig, location);
1458
1459                     let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1460
1461                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1462                         span_mirbug!(
1463                             self,
1464                             rvalue,
1465                             "equating {:?} with {:?} yields {:?}",
1466                             ty_fn_ptr_from,
1467                             ty,
1468                             terr
1469                         );
1470                     }
1471                 }
1472
1473                 CastKind::ClosureFnPointer => {
1474                     let sig = match op.ty(mir, tcx).sty {
1475                         ty::TyClosure(def_id, substs) => {
1476                             substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1477                         }
1478                         _ => bug!(),
1479                     };
1480                     let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1481
1482                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1483                         span_mirbug!(
1484                             self,
1485                             rvalue,
1486                             "equating {:?} with {:?} yields {:?}",
1487                             ty_fn_ptr_from,
1488                             ty,
1489                             terr
1490                         );
1491                     }
1492                 }
1493
1494                 CastKind::UnsafeFnPointer => {
1495                     let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1496
1497                     // The type that we see in the fcx is like
1498                     // `foo::<'a, 'b>`, where `foo` is the path to a
1499                     // function definition. When we extract the
1500                     // signature, it comes from the `fn_sig` query,
1501                     // and hence may contain unnormalized results.
1502                     let fn_sig = self.normalize(fn_sig, location);
1503
1504                     let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1505
1506                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1507                         span_mirbug!(
1508                             self,
1509                             rvalue,
1510                             "equating {:?} with {:?} yields {:?}",
1511                             ty_fn_ptr_from,
1512                             ty,
1513                             terr
1514                         );
1515                     }
1516                 }
1517
1518                 CastKind::Unsize => {
1519                     let &ty = ty;
1520                     let trait_ref = ty::TraitRef {
1521                         def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1522                         substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1523                     };
1524
1525                     self.prove_trait_ref(trait_ref, location.interesting());
1526                 }
1527
1528                 CastKind::Misc => {}
1529             },
1530
1531             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1532                 self.add_reborrow_constraint(location, region, borrowed_place);
1533             }
1534
1535             // FIXME: These other cases have to be implemented in future PRs
1536             Rvalue::Use(..)
1537             | Rvalue::Len(..)
1538             | Rvalue::BinaryOp(..)
1539             | Rvalue::CheckedBinaryOp(..)
1540             | Rvalue::UnaryOp(..)
1541             | Rvalue::Discriminant(..) => {}
1542         }
1543     }
1544
1545     fn check_aggregate_rvalue(
1546         &mut self,
1547         mir: &Mir<'tcx>,
1548         rvalue: &Rvalue<'tcx>,
1549         aggregate_kind: &AggregateKind<'tcx>,
1550         operands: &[Operand<'tcx>],
1551         location: Location,
1552     ) {
1553         let tcx = self.tcx();
1554
1555         self.prove_aggregate_predicates(aggregate_kind, location);
1556
1557         if *aggregate_kind == AggregateKind::Tuple {
1558             // tuple rvalue field type is always the type of the op. Nothing to check here.
1559             return;
1560         }
1561
1562         for (i, operand) in operands.iter().enumerate() {
1563             let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
1564                 Ok(field_ty) => field_ty,
1565                 Err(FieldAccessError::OutOfRange { field_count }) => {
1566                     span_mirbug!(
1567                         self,
1568                         rvalue,
1569                         "accessed field #{} but variant only has {}",
1570                         i,
1571                         field_count
1572                     );
1573                     continue;
1574                 }
1575             };
1576             let operand_ty = operand.ty(mir, tcx);
1577
1578             if let Err(terr) = self.sub_types(operand_ty, field_ty, location.boring()) {
1579                 span_mirbug!(
1580                     self,
1581                     rvalue,
1582                     "{:?} is not a subtype of {:?}: {:?}",
1583                     operand_ty,
1584                     field_ty,
1585                     terr
1586                 );
1587             }
1588         }
1589     }
1590
1591     /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
1592     ///
1593     /// # Parameters
1594     ///
1595     /// - `location`: the location `L` where the borrow expression occurs
1596     /// - `borrow_region`: the region `'a` associated with the borrow
1597     /// - `borrowed_place`: the place `P` being borrowed
1598     fn add_reborrow_constraint(
1599         &mut self,
1600         location: Location,
1601         borrow_region: ty::Region<'tcx>,
1602         borrowed_place: &Place<'tcx>,
1603     ) {
1604         // These constraints are only meaningful during borrowck:
1605         let BorrowCheckContext {
1606             borrow_set,
1607             location_table,
1608             all_facts,
1609             constraints,
1610             ..
1611         } = match self.borrowck_context {
1612             Some(ref mut borrowck_context) => borrowck_context,
1613             None => return,
1614         };
1615
1616         // In Polonius mode, we also push a `borrow_region` fact
1617         // linking the loan to the region (in some cases, though,
1618         // there is no loan associated with this borrow expression --
1619         // that occurs when we are borrowing an unsafe place, for
1620         // example).
1621         if let Some(all_facts) = all_facts {
1622             if let Some(borrow_index) = borrow_set.location_map.get(&location) {
1623                 let region_vid = borrow_region.to_region_vid();
1624                 all_facts.borrow_region.push((
1625                     region_vid,
1626                     *borrow_index,
1627                     location_table.mid_index(location),
1628                 ));
1629             }
1630         }
1631
1632         // If we are reborrowing the referent of another reference, we
1633         // need to add outlives relationships. In a case like `&mut
1634         // *p`, where the `p` has type `&'b mut Foo`, for example, we
1635         // need to ensure that `'b: 'a`.
1636
1637         let mut borrowed_place = borrowed_place;
1638
1639         debug!(
1640             "add_reborrow_constraint({:?}, {:?}, {:?})",
1641             location, borrow_region, borrowed_place
1642         );
1643         while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
1644             debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
1645
1646             match *elem {
1647                 ProjectionElem::Deref => {
1648                     let tcx = self.infcx.tcx;
1649                     let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1650
1651                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
1652                     match base_ty.sty {
1653                         ty::TyRef(ref_region, _, mutbl) => {
1654                             constraints.outlives_constraints.push(OutlivesConstraint {
1655                                 sup: ref_region.to_region_vid(),
1656                                 sub: borrow_region.to_region_vid(),
1657                                 locations: location.boring(),
1658                             });
1659
1660                             if let Some(all_facts) = all_facts {
1661                                 all_facts.outlives.push((
1662                                     ref_region.to_region_vid(),
1663                                     borrow_region.to_region_vid(),
1664                                     location_table.mid_index(location),
1665                                 ));
1666                             }
1667
1668                             match mutbl {
1669                                 hir::Mutability::MutImmutable => {
1670                                     // Immutable reference. We don't need the base
1671                                     // to be valid for the entire lifetime of
1672                                     // the borrow.
1673                                     break;
1674                                 }
1675                                 hir::Mutability::MutMutable => {
1676                                     // Mutable reference. We *do* need the base
1677                                     // to be valid, because after the base becomes
1678                                     // invalid, someone else can use our mutable deref.
1679
1680                                     // This is in order to make the following function
1681                                     // illegal:
1682                                     // ```
1683                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
1684                                     //     &mut *x
1685                                     // }
1686                                     // ```
1687                                     //
1688                                     // As otherwise you could clone `&mut T` using the
1689                                     // following function:
1690                                     // ```
1691                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
1692                                     //     let my_clone = unsafe_deref(&'a x);
1693                                     //     ENDREGION 'a;
1694                                     //     (my_clone, x)
1695                                     // }
1696                                     // ```
1697                                 }
1698                             }
1699                         }
1700                         ty::TyRawPtr(..) => {
1701                             // deref of raw pointer, guaranteed to be valid
1702                             break;
1703                         }
1704                         ty::TyAdt(def, _) if def.is_box() => {
1705                             // deref of `Box`, need the base to be valid - propagate
1706                         }
1707                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
1708                     }
1709                 }
1710                 ProjectionElem::Field(..)
1711                 | ProjectionElem::Downcast(..)
1712                 | ProjectionElem::Index(..)
1713                 | ProjectionElem::ConstantIndex { .. }
1714                 | ProjectionElem::Subslice { .. } => {
1715                     // other field access
1716                 }
1717             }
1718
1719             // The "propagate" case. We need to check that our base is valid
1720             // for the borrow's lifetime.
1721             borrowed_place = base;
1722         }
1723     }
1724
1725     fn prove_aggregate_predicates(
1726         &mut self,
1727         aggregate_kind: &AggregateKind<'tcx>,
1728         location: Location,
1729     ) {
1730         let tcx = self.tcx();
1731
1732         debug!(
1733             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
1734             aggregate_kind, location
1735         );
1736
1737         let instantiated_predicates = match aggregate_kind {
1738             AggregateKind::Adt(def, _, substs, _) => {
1739                 tcx.predicates_of(def.did).instantiate(tcx, substs)
1740             }
1741
1742             // For closures, we have some **extra requirements** we
1743             //
1744             // have to check. In particular, in their upvars and
1745             // signatures, closures often reference various regions
1746             // from the surrounding function -- we call those the
1747             // closure's free regions. When we borrow-check (and hence
1748             // region-check) closures, we may find that the closure
1749             // requires certain relationships between those free
1750             // regions. However, because those free regions refer to
1751             // portions of the CFG of their caller, the closure is not
1752             // in a position to verify those relationships. In that
1753             // case, the requirements get "propagated" to us, and so
1754             // we have to solve them here where we instantiate the
1755             // closure.
1756             //
1757             // Despite the opacity of the previous parapgrah, this is
1758             // actually relatively easy to understand in terms of the
1759             // desugaring. A closure gets desugared to a struct, and
1760             // these extra requirements are basically like where
1761             // clauses on the struct.
1762             AggregateKind::Closure(def_id, substs) => {
1763                 if let Some(closure_region_requirements) =
1764                     tcx.mir_borrowck(*def_id).closure_requirements
1765                 {
1766                     let closure_constraints = closure_region_requirements.apply_requirements(
1767                         self.infcx.tcx,
1768                         location,
1769                         *def_id,
1770                         *substs,
1771                     );
1772
1773                     // Hmm, are these constraints *really* boring?
1774                     self.push_region_constraints(location.boring(), &closure_constraints);
1775                 }
1776
1777                 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1778             }
1779
1780             AggregateKind::Generator(def_id, substs, _) => {
1781                 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1782             }
1783
1784             AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
1785         };
1786
1787         self.normalize_and_prove_instantiated_predicates(
1788             instantiated_predicates,
1789             location.boring(),
1790         );
1791     }
1792
1793     fn prove_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>, locations: Locations) {
1794         self.prove_predicates(
1795             Some(ty::Predicate::Trait(
1796                 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
1797             )),
1798             locations,
1799         );
1800     }
1801
1802     fn normalize_and_prove_instantiated_predicates(
1803         &mut self,
1804         instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
1805         locations: Locations,
1806     ) {
1807         for predicate in instantiated_predicates.predicates {
1808             let predicate = self.normalize(predicate, locations);
1809             self.prove_predicate(predicate, locations);
1810         }
1811     }
1812
1813     fn prove_predicates(
1814         &mut self,
1815         predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
1816         locations: Locations,
1817     ) {
1818         for predicate in predicates {
1819             debug!(
1820                 "prove_predicates(predicate={:?}, locations={:?})",
1821                 predicate, locations,
1822             );
1823
1824             self.prove_predicate(predicate, locations);
1825         }
1826     }
1827
1828     fn prove_predicate(&mut self, predicate: ty::Predicate<'tcx>, locations: Locations) {
1829         debug!(
1830             "prove_predicate(predicate={:?}, location={:?})",
1831             predicate, locations,
1832         );
1833
1834         let param_env = self.param_env;
1835         self.fully_perform_op(
1836             locations,
1837             param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
1838         ).unwrap_or_else(|NoSolution| {
1839             span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
1840         })
1841     }
1842
1843     fn typeck_mir(&mut self, mir: &Mir<'tcx>, mut errors_buffer: Option<&mut Vec<Diagnostic>>) {
1844         self.last_span = mir.span;
1845         debug!("run_on_mir: {:?}", mir.span);
1846
1847         for (local, local_decl) in mir.local_decls.iter_enumerated() {
1848             self.check_local(mir, local, local_decl, &mut errors_buffer);
1849         }
1850
1851         for (block, block_data) in mir.basic_blocks().iter_enumerated() {
1852             let mut location = Location {
1853                 block,
1854                 statement_index: 0,
1855             };
1856             for stmt in &block_data.statements {
1857                 if !stmt.source_info.span.is_dummy() {
1858                     self.last_span = stmt.source_info.span;
1859                 }
1860                 self.check_stmt(mir, stmt, location);
1861                 location.statement_index += 1;
1862             }
1863
1864             self.check_terminator(mir, block_data.terminator(), location, &mut errors_buffer);
1865             self.check_iscleanup(mir, block_data);
1866         }
1867     }
1868
1869     fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
1870     where
1871         T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
1872     {
1873         debug!("normalize(value={:?}, location={:?})", value, location);
1874         let param_env = self.param_env;
1875         self.fully_perform_op(
1876             location.to_locations(),
1877             param_env.and(type_op::normalize::Normalize::new(value)),
1878         ).unwrap_or_else(|NoSolution| {
1879             span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
1880             value
1881         })
1882     }
1883 }
1884
1885 pub struct TypeckMir;
1886
1887 impl MirPass for TypeckMir {
1888     fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
1889         let def_id = src.def_id;
1890         debug!("run_pass: {:?}", def_id);
1891
1892         // When NLL is enabled, the borrow checker runs the typeck
1893         // itself, so we don't need this MIR pass anymore.
1894         if tcx.use_mir_borrowck() {
1895             return;
1896         }
1897
1898         if tcx.sess.err_count() > 0 {
1899             // compiling a broken program can obviously result in a
1900             // broken MIR, so try not to report duplicate errors.
1901             return;
1902         }
1903
1904         if tcx.is_struct_constructor(def_id) {
1905             // We just assume that the automatically generated struct constructors are
1906             // correct. See the comment in the `mir_borrowck` implementation for an
1907             // explanation why we need this.
1908             return;
1909         }
1910
1911         let param_env = tcx.param_env(def_id);
1912         tcx.infer_ctxt().enter(|infcx| {
1913             type_check_internal(
1914                 &infcx,
1915                 def_id,
1916                 param_env,
1917                 mir,
1918                 &[],
1919                 None,
1920                 None,
1921                 None,
1922                 |_| (),
1923             );
1924
1925             // For verification purposes, we just ignore the resulting
1926             // region constraint sets. Not our problem. =)
1927         });
1928     }
1929 }
1930
1931 pub trait AtLocation {
1932     /// Indicates a "boring" constraint that the user probably
1933     /// woudln't want to see highlights.
1934     fn boring(self) -> Locations;
1935
1936     /// Indicates an "interesting" edge, which is of significance only
1937     /// for diagnostics.
1938     fn interesting(self) -> Locations;
1939 }
1940
1941 impl AtLocation for Location {
1942     fn boring(self) -> Locations {
1943         Locations::Boring(self)
1944     }
1945
1946     fn interesting(self) -> Locations {
1947         Locations::Interesting(self)
1948     }
1949 }
1950
1951 trait NormalizeLocation: fmt::Debug + Copy {
1952     fn to_locations(self) -> Locations;
1953 }
1954
1955 impl NormalizeLocation for Locations {
1956     fn to_locations(self) -> Locations {
1957         self
1958     }
1959 }
1960
1961 impl NormalizeLocation for Location {
1962     fn to_locations(self) -> Locations {
1963         self.boring()
1964     }
1965 }