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