]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/type_check/mod.rs
Auto merge of #55126 - GuillaumeGomez:improve-search-tabs, r=QuietMisdreavus
[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::{DefiningTy, 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, Substs, UnpackedKind, UserSelfTy, UserSubsts};
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: Default::default(),
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:
757         FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
758
759     crate type_tests: Vec<TypeTest<'tcx>>,
760 }
761
762 /// The `Locations` type summarizes *where* region constraints are
763 /// required to hold. Normally, this is at a particular point which
764 /// created the obligation, but for constraints that the user gave, we
765 /// want the constraint to hold at all points.
766 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
767 pub enum Locations {
768     /// Indicates that a type constraint should always be true. This
769     /// is particularly important in the new borrowck analysis for
770     /// things like the type of the return slot. Consider this
771     /// example:
772     ///
773     /// ```
774     /// fn foo<'a>(x: &'a u32) -> &'a u32 {
775     ///     let y = 22;
776     ///     return &y; // error
777     /// }
778     /// ```
779     ///
780     /// Here, we wind up with the signature from the return type being
781     /// something like `&'1 u32` where `'1` is a universal region. But
782     /// the type of the return slot `_0` is something like `&'2 u32`
783     /// where `'2` is an existential region variable. The type checker
784     /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
785     /// older NLL analysis, we required this only at the entry point
786     /// to the function. By the nature of the constraints, this wound
787     /// up propagating to all points reachable from start (because
788     /// `'1` -- as a universal region -- is live everywhere).  In the
789     /// newer analysis, though, this doesn't work: `_0` is considered
790     /// dead at the start (it has no usable value) and hence this type
791     /// equality is basically a no-op. Then, later on, when we do `_0
792     /// = &'3 y`, that region `'3` never winds up related to the
793     /// universal region `'1` and hence no error occurs. Therefore, we
794     /// use Locations::All instead, which ensures that the `'1` and
795     /// `'2` are equal everything. We also use this for other
796     /// user-given type annotations; e.g., if the user wrote `let mut
797     /// x: &'static u32 = ...`, we would ensure that all values
798     /// assigned to `x` are of `'static` lifetime.
799     ///
800     /// The span points to the place the constraint arose. For example,
801     /// it points to the type in a user-given type annotation. If
802     /// there's no sensible span then it's DUMMY_SP.
803     All(Span),
804
805     /// An outlives constraint that only has to hold at a single location,
806     /// usually it represents a point where references flow from one spot to
807     /// another (e.g., `x = y`)
808     Single(Location),
809 }
810
811 impl Locations {
812     pub fn from_location(&self) -> Option<Location> {
813         match self {
814             Locations::All(_) => None,
815             Locations::Single(from_location) => Some(*from_location),
816         }
817     }
818
819     /// Gets a span representing the location.
820     pub fn span(&self, mir: &Mir<'_>) -> Span {
821         match self {
822             Locations::All(span) => *span,
823             Locations::Single(l) => mir.source_info(*l).span,
824         }
825     }
826 }
827
828 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
829     fn new(
830         infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
831         mir: &'a Mir<'tcx>,
832         mir_def_id: DefId,
833         param_env: ty::ParamEnv<'gcx>,
834         region_bound_pairs: &'a RegionBoundPairs<'tcx>,
835         implicit_region_bound: Option<ty::Region<'tcx>>,
836         borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
837         universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
838     ) -> Self {
839         TypeChecker {
840             infcx,
841             last_span: DUMMY_SP,
842             mir,
843             mir_def_id,
844             param_env,
845             region_bound_pairs,
846             implicit_region_bound,
847             borrowck_context,
848             reported_errors: Default::default(),
849             universal_region_relations,
850         }
851     }
852
853     /// Given some operation `op` that manipulates types, proves
854     /// predicates, or otherwise uses the inference context, executes
855     /// `op` and then executes all the further obligations that `op`
856     /// returns. This will yield a set of outlives constraints amongst
857     /// regions which are extracted and stored as having occurred at
858     /// `locations`.
859     ///
860     /// **Any `rustc::infer` operations that might generate region
861     /// constraints should occur within this method so that those
862     /// constraints can be properly localized!**
863     fn fully_perform_op<R>(
864         &mut self,
865         locations: Locations,
866         category: ConstraintCategory,
867         op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
868     ) -> Fallible<R> {
869         let (r, opt_data) = op.fully_perform(self.infcx)?;
870
871         if let Some(data) = &opt_data {
872             self.push_region_constraints(locations, category, data);
873         }
874
875         Ok(r)
876     }
877
878     fn push_region_constraints(
879         &mut self,
880         locations: Locations,
881         category: ConstraintCategory,
882         data: &[QueryRegionConstraint<'tcx>],
883     ) {
884         debug!(
885             "push_region_constraints: constraints generated at {:?} are {:#?}",
886             locations, data
887         );
888
889         if let Some(ref mut borrowck_context) = self.borrowck_context {
890             constraint_conversion::ConstraintConversion::new(
891                 self.infcx.tcx,
892                 borrowck_context.universal_regions,
893                 self.region_bound_pairs,
894                 self.implicit_region_bound,
895                 self.param_env,
896                 locations,
897                 category,
898                 &mut borrowck_context.constraints.outlives_constraints,
899                 &mut borrowck_context.constraints.type_tests,
900             ).convert_all(&data);
901         }
902     }
903
904     /// Convenient wrapper around `relate_tys::relate_types` -- see
905     /// that fn for docs.
906     fn relate_types(
907         &mut self,
908         a: Ty<'tcx>,
909         v: ty::Variance,
910         b: Ty<'tcx>,
911         locations: Locations,
912         category: ConstraintCategory,
913     ) -> Fallible<()> {
914         relate_tys::relate_types(
915             self.infcx,
916             a,
917             v,
918             b,
919             locations,
920             category,
921             self.borrowck_context.as_mut().map(|x| &mut **x),
922         )
923     }
924
925     fn sub_types(
926         &mut self,
927         sub: Ty<'tcx>,
928         sup: Ty<'tcx>,
929         locations: Locations,
930         category: ConstraintCategory,
931     ) -> Fallible<()> {
932         self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
933     }
934
935     /// Try to relate `sub <: sup`; if this fails, instantiate opaque
936     /// variables in `sub` with their inferred definitions and try
937     /// again. This is used for opaque types in places (e.g., `let x:
938     /// impl Foo = ..`).
939     fn sub_types_or_anon(
940         &mut self,
941         sub: Ty<'tcx>,
942         sup: Ty<'tcx>,
943         locations: Locations,
944         category: ConstraintCategory,
945     ) -> Fallible<()> {
946         if let Err(terr) = self.sub_types(sub, sup, locations, category) {
947             if let TyKind::Opaque(..) = sup.sty {
948                 // When you have `let x: impl Foo = ...` in a closure,
949                 // the resulting inferend values are stored with the
950                 // def-id of the base function.
951                 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
952                 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
953             } else {
954                 return Err(terr);
955             }
956         }
957         Ok(())
958     }
959
960     fn eq_types(
961         &mut self,
962         a: Ty<'tcx>,
963         b: Ty<'tcx>,
964         locations: Locations,
965         category: ConstraintCategory,
966     ) -> Fallible<()> {
967         self.relate_types(a, ty::Variance::Invariant, b, locations, category)
968     }
969
970     fn relate_type_and_user_type(
971         &mut self,
972         a: Ty<'tcx>,
973         v: ty::Variance,
974         user_ty: UserTypeAnnotation<'tcx>,
975         locations: Locations,
976         category: ConstraintCategory,
977     ) -> Fallible<()> {
978         let tcx = self.tcx();
979
980         debug!(
981             "relate_type_and_user_type(a={:?}, v={:?}, b={:?}, locations={:?})",
982             a, v, user_ty, locations
983         );
984
985         // The `TypeRelating` code assumes that "unresolved inference
986         // variables" appear in the "a" side, so flip `Contravariant`
987         // ambient variance to get the right relationship.
988         let v1 = ty::Contravariant.xform(v);
989
990         match user_ty {
991             UserTypeAnnotation::Ty(canonical_ty) => {
992                 let (ty, _) = self.infcx
993                     .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_ty);
994
995                 self.relate_types(ty, v1, a, locations, category)?;
996
997                 self.prove_predicate(ty::Predicate::WellFormed(ty), locations, category);
998             }
999             UserTypeAnnotation::TypeOf(def_id, canonical_substs) => {
1000                 let (
1001                     UserSubsts {
1002                         substs,
1003                         user_self_ty,
1004                     },
1005                     _,
1006                 ) = self.infcx
1007                     .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
1008
1009                 let ty = self.tcx().type_of(def_id);
1010                 let ty = ty.subst(tcx, substs);
1011                 let ty = self.normalize(ty, locations);
1012
1013                 self.relate_types(ty, v1, a, locations, category)?;
1014
1015                 if let Some(UserSelfTy {
1016                     impl_def_id,
1017                     self_ty,
1018                 }) = user_self_ty
1019                 {
1020                     let impl_self_ty = tcx.type_of(impl_def_id);
1021                     let impl_self_ty = impl_self_ty.subst(tcx, &substs);
1022                     let impl_self_ty = self.normalize(impl_self_ty, locations);
1023
1024                     // There may be type variables in `substs` and hence
1025                     // in `impl_self_ty`, but they should all have been
1026                     // resolved to some fixed value during the first call
1027                     // to `relate`, above. Therefore, if we use
1028                     // `resolve_type_vars_if_possible` we should get to
1029                     // something without type variables. This is important
1030                     // because the `b` type in `relate_with_variance`
1031                     // below is not permitted to have inference variables.
1032                     let impl_self_ty = self.infcx.resolve_type_vars_if_possible(&impl_self_ty);
1033                     assert!(!impl_self_ty.has_infer_types());
1034
1035                     self.eq_types(self_ty, impl_self_ty, locations, category)?;
1036                 }
1037
1038                 // Prove the predicates coming along with `def_id`.
1039                 //
1040                 // Also, normalize the `instantiated_predicates`
1041                 // because otherwise we wind up with duplicate "type
1042                 // outlives" error messages.
1043                 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
1044                 let instantiated_predicates = self.fold_to_region_vid(instantiated_predicates);
1045                 self.normalize_and_prove_instantiated_predicates(
1046                     instantiated_predicates,
1047                     locations,
1048                 );
1049
1050                 // In addition to proving the predicates, we have to
1051                 // prove that `ty` is well-formed -- this is because
1052                 // the WF of `ty` is predicated on the substs being
1053                 // well-formed, and we haven't proven *that*. We don't
1054                 // want to prove the WF of types from  `substs` directly because they
1055                 // haven't been normalized.
1056                 //
1057                 // FIXME(nmatsakis): Well, perhaps we should normalize
1058                 // them?  This would only be relevant if some input
1059                 // type were ill-formed but did not appear in `ty`,
1060                 // which...could happen with normalization...
1061                 self.prove_predicate(ty::Predicate::WellFormed(ty), locations, category);
1062             }
1063         }
1064
1065         Ok(())
1066     }
1067
1068     /// Replace all free regions in `value` with their NLL `RegionVid`
1069     /// equivalents; if not in NLL, does nothing. This is never
1070     /// particularly necessary -- we'll do it lazilly as we process
1071     /// the value anyway -- but in some specific cases it is useful to
1072     /// normalize so we can suppress duplicate error messages.
1073     fn fold_to_region_vid<T>(
1074         &self,
1075         value: T
1076     ) -> T
1077     where T: TypeFoldable<'tcx>
1078     {
1079         if let Some(borrowck_context) = &self.borrowck_context {
1080             self.tcx().fold_regions(&value, &mut false, |r, _debruijn| {
1081                 if r.has_free_regions() {
1082                     self.tcx().mk_region(ty::RegionKind::ReVar(
1083                         borrowck_context.universal_regions.to_region_vid(r),
1084                     ))
1085                 } else {
1086                     r
1087                 }
1088             })
1089         } else {
1090             value
1091         }
1092     }
1093
1094     fn eq_opaque_type_and_type(
1095         &mut self,
1096         revealed_ty: Ty<'tcx>,
1097         anon_ty: Ty<'tcx>,
1098         anon_owner_def_id: DefId,
1099         locations: Locations,
1100         category: ConstraintCategory,
1101     ) -> Fallible<()> {
1102         debug!(
1103             "eq_opaque_type_and_type( \
1104              revealed_ty={:?}, \
1105              anon_ty={:?})",
1106             revealed_ty, anon_ty
1107         );
1108         let infcx = self.infcx;
1109         let tcx = infcx.tcx;
1110         let param_env = self.param_env;
1111         debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1112         let opaque_type_map = self.fully_perform_op(
1113             locations,
1114             category,
1115             CustomTypeOp::new(
1116                 |infcx| {
1117                     let mut obligations = ObligationAccumulator::default();
1118
1119                     let dummy_body_id = ObligationCause::dummy().body_id;
1120                     let (output_ty, opaque_type_map) =
1121                         obligations.add(infcx.instantiate_opaque_types(
1122                             anon_owner_def_id,
1123                             dummy_body_id,
1124                             param_env,
1125                             &anon_ty,
1126                         ));
1127                     debug!(
1128                         "eq_opaque_type_and_type: \
1129                          instantiated output_ty={:?} \
1130                          opaque_type_map={:#?} \
1131                          revealed_ty={:?}",
1132                         output_ty, opaque_type_map, revealed_ty
1133                     );
1134                     obligations.add(infcx
1135                         .at(&ObligationCause::dummy(), param_env)
1136                         .eq(output_ty, revealed_ty)?);
1137
1138                     for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1139                         let opaque_defn_ty = tcx.type_of(opaque_def_id);
1140                         let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1141                         let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1142                         debug!(
1143                             "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1144                             opaque_decl.concrete_ty,
1145                             infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1146                             opaque_defn_ty
1147                         );
1148                         obligations.add(infcx
1149                             .at(&ObligationCause::dummy(), param_env)
1150                             .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1151                     }
1152
1153                     debug!("eq_opaque_type_and_type: equated");
1154
1155                     Ok(InferOk {
1156                         value: Some(opaque_type_map),
1157                         obligations: obligations.into_vec(),
1158                     })
1159                 },
1160                 || "input_output".to_string(),
1161             ),
1162         )?;
1163
1164         let universal_region_relations = match self.universal_region_relations {
1165             Some(rel) => rel,
1166             None => return Ok(()),
1167         };
1168
1169         // Finally, if we instantiated the anon types successfully, we
1170         // have to solve any bounds (e.g., `-> impl Iterator` needs to
1171         // prove that `T: Iterator` where `T` is the type we
1172         // instantiated it with).
1173         if let Some(opaque_type_map) = opaque_type_map {
1174             for (opaque_def_id, opaque_decl) in opaque_type_map {
1175                 self.fully_perform_op(
1176                     locations,
1177                     ConstraintCategory::OpaqueType,
1178                     CustomTypeOp::new(
1179                         |_cx| {
1180                             infcx.constrain_opaque_type(
1181                                 opaque_def_id,
1182                                 &opaque_decl,
1183                                 universal_region_relations,
1184                             );
1185                             Ok(InferOk {
1186                                 value: (),
1187                                 obligations: vec![],
1188                             })
1189                         },
1190                         || "opaque_type_map".to_string(),
1191                     ),
1192                 )?;
1193             }
1194         }
1195         Ok(())
1196     }
1197
1198     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1199         self.infcx.tcx
1200     }
1201
1202     fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1203         debug!("check_stmt: {:?}", stmt);
1204         let tcx = self.tcx();
1205         match stmt.kind {
1206             StatementKind::Assign(ref place, ref rv) => {
1207                 // Assignments to temporaries are not "interesting";
1208                 // they are not caused by the user, but rather artifacts
1209                 // of lowering. Assignments to other sorts of places *are* interesting
1210                 // though.
1211                 let category = match *place {
1212                     Place::Local(RETURN_PLACE) => if let Some(BorrowCheckContext {
1213                         universal_regions: UniversalRegions {
1214                             defining_ty: DefiningTy::Const(def_id, _),
1215                             ..
1216                         },
1217                         ..
1218                     }) = self.borrowck_context {
1219                         if tcx.is_static(*def_id).is_some() {
1220                             ConstraintCategory::UseAsStatic
1221                         } else {
1222                             ConstraintCategory::UseAsConst
1223                         }
1224                     } else {
1225                         ConstraintCategory::Return
1226                     }
1227                     Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1228                         ConstraintCategory::Boring
1229                     }
1230                     _ => ConstraintCategory::Assignment,
1231                 };
1232
1233                 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1234                 let rv_ty = rv.ty(mir, tcx);
1235                 if let Err(terr) =
1236                     self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1237                 {
1238                     span_mirbug!(
1239                         self,
1240                         stmt,
1241                         "bad assignment ({:?} = {:?}): {:?}",
1242                         place_ty,
1243                         rv_ty,
1244                         terr
1245                     );
1246                 }
1247
1248                 if let Some(user_ty) = self.rvalue_user_ty(rv) {
1249                     if let Err(terr) = self.relate_type_and_user_type(
1250                         rv_ty,
1251                         ty::Variance::Invariant,
1252                         user_ty,
1253                         location.to_locations(),
1254                         ConstraintCategory::Boring,
1255                     ) {
1256                         span_mirbug!(
1257                             self,
1258                             stmt,
1259                             "bad user type on rvalue ({:?} = {:?}): {:?}",
1260                             user_ty,
1261                             rv_ty,
1262                             terr
1263                         );
1264                     }
1265                 }
1266
1267                 self.check_rvalue(mir, rv, location);
1268                 if !self.tcx().features().unsized_locals {
1269                     let trait_ref = ty::TraitRef {
1270                         def_id: tcx.lang_items().sized_trait().unwrap(),
1271                         substs: tcx.mk_substs_trait(place_ty, &[]),
1272                     };
1273                     self.prove_trait_ref(
1274                         trait_ref,
1275                         location.to_locations(),
1276                         ConstraintCategory::SizedBound,
1277                     );
1278                 }
1279             }
1280             StatementKind::SetDiscriminant {
1281                 ref place,
1282                 variant_index,
1283             } => {
1284                 let place_type = place.ty(mir, tcx).to_ty(tcx);
1285                 let adt = match place_type.sty {
1286                     TyKind::Adt(adt, _) if adt.is_enum() => adt,
1287                     _ => {
1288                         span_bug!(
1289                             stmt.source_info.span,
1290                             "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1291                             place,
1292                             variant_index
1293                         );
1294                     }
1295                 };
1296                 if variant_index >= adt.variants.len() {
1297                     span_bug!(
1298                         stmt.source_info.span,
1299                         "bad set discriminant ({:?} = {:?}): value of of range",
1300                         place,
1301                         variant_index
1302                     );
1303                 };
1304             }
1305             StatementKind::AscribeUserType(ref place, variance, c_ty) => {
1306                 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1307                 if let Err(terr) = self.relate_type_and_user_type(
1308                     place_ty,
1309                     variance,
1310                     c_ty,
1311                     Locations::All(stmt.source_info.span),
1312                     ConstraintCategory::TypeAnnotation,
1313                 ) {
1314                     span_mirbug!(
1315                         self,
1316                         stmt,
1317                         "bad type assert ({:?} <: {:?}): {:?}",
1318                         place_ty,
1319                         c_ty,
1320                         terr
1321                     );
1322                 }
1323             }
1324             StatementKind::FakeRead(..)
1325             | StatementKind::StorageLive(_)
1326             | StatementKind::StorageDead(_)
1327             | StatementKind::InlineAsm { .. }
1328             | StatementKind::EndRegion(_)
1329             | StatementKind::Validate(..)
1330             | StatementKind::Nop => {}
1331         }
1332     }
1333
1334     fn check_terminator(
1335         &mut self,
1336         mir: &Mir<'tcx>,
1337         term: &Terminator<'tcx>,
1338         term_location: Location,
1339     ) {
1340         debug!("check_terminator: {:?}", term);
1341         let tcx = self.tcx();
1342         match term.kind {
1343             TerminatorKind::Goto { .. }
1344             | TerminatorKind::Resume
1345             | TerminatorKind::Abort
1346             | TerminatorKind::Return
1347             | TerminatorKind::GeneratorDrop
1348             | TerminatorKind::Unreachable
1349             | TerminatorKind::Drop { .. }
1350             | TerminatorKind::FalseEdges { .. }
1351             | TerminatorKind::FalseUnwind { .. } => {
1352                 // no checks needed for these
1353             }
1354
1355             TerminatorKind::DropAndReplace {
1356                 ref location,
1357                 ref value,
1358                 target: _,
1359                 unwind: _,
1360             } => {
1361                 let place_ty = location.ty(mir, tcx).to_ty(tcx);
1362                 let rv_ty = value.ty(mir, tcx);
1363
1364                 let locations = term_location.to_locations();
1365                 if let Err(terr) =
1366                     self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1367                 {
1368                     span_mirbug!(
1369                         self,
1370                         term,
1371                         "bad DropAndReplace ({:?} = {:?}): {:?}",
1372                         place_ty,
1373                         rv_ty,
1374                         terr
1375                     );
1376                 }
1377             }
1378             TerminatorKind::SwitchInt {
1379                 ref discr,
1380                 switch_ty,
1381                 ..
1382             } => {
1383                 let discr_ty = discr.ty(mir, tcx);
1384                 if let Err(terr) = self.sub_types(
1385                     discr_ty,
1386                     switch_ty,
1387                     term_location.to_locations(),
1388                     ConstraintCategory::Assignment,
1389                 ) {
1390                     span_mirbug!(
1391                         self,
1392                         term,
1393                         "bad SwitchInt ({:?} on {:?}): {:?}",
1394                         switch_ty,
1395                         discr_ty,
1396                         terr
1397                     );
1398                 }
1399                 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1400                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1401                 }
1402                 // FIXME: check the values
1403             }
1404             TerminatorKind::Call {
1405                 ref func,
1406                 ref args,
1407                 ref destination,
1408                 from_hir_call,
1409                 ..
1410             } => {
1411                 let func_ty = func.ty(mir, tcx);
1412                 debug!("check_terminator: call, func_ty={:?}", func_ty);
1413                 let sig = match func_ty.sty {
1414                     ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1415                     _ => {
1416                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1417                         return;
1418                     }
1419                 };
1420                 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
1421                     term.source_info.span,
1422                     LateBoundRegionConversionTime::FnCall,
1423                     &sig,
1424                 );
1425                 let sig = self.normalize(sig, term_location);
1426                 self.check_call_dest(mir, term, &sig, destination, term_location);
1427
1428                 self.prove_predicates(
1429                     sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1430                     term_location.to_locations(),
1431                     ConstraintCategory::Boring,
1432                 );
1433
1434                 // The ordinary liveness rules will ensure that all
1435                 // regions in the type of the callee are live here. We
1436                 // then further constrain the late-bound regions that
1437                 // were instantiated at the call site to be live as
1438                 // well. The resulting is that all the input (and
1439                 // output) types in the signature must be live, since
1440                 // all the inputs that fed into it were live.
1441                 for &late_bound_region in map.values() {
1442                     if let Some(ref mut borrowck_context) = self.borrowck_context {
1443                         let region_vid = borrowck_context
1444                             .universal_regions
1445                             .to_region_vid(late_bound_region);
1446                         borrowck_context
1447                             .constraints
1448                             .liveness_constraints
1449                             .add_element(region_vid, term_location);
1450                     }
1451                 }
1452
1453                 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1454             }
1455             TerminatorKind::Assert {
1456                 ref cond, ref msg, ..
1457             } => {
1458                 let cond_ty = cond.ty(mir, tcx);
1459                 if cond_ty != tcx.types.bool {
1460                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1461                 }
1462
1463                 if let BoundsCheck { ref len, ref index } = *msg {
1464                     if len.ty(mir, tcx) != tcx.types.usize {
1465                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1466                     }
1467                     if index.ty(mir, tcx) != tcx.types.usize {
1468                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1469                     }
1470                 }
1471             }
1472             TerminatorKind::Yield { ref value, .. } => {
1473                 let value_ty = value.ty(mir, tcx);
1474                 match mir.yield_ty {
1475                     None => span_mirbug!(self, term, "yield in non-generator"),
1476                     Some(ty) => {
1477                         if let Err(terr) = self.sub_types(
1478                             value_ty,
1479                             ty,
1480                             term_location.to_locations(),
1481                             ConstraintCategory::Return,
1482                         ) {
1483                             span_mirbug!(
1484                                 self,
1485                                 term,
1486                                 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1487                                 value_ty,
1488                                 ty,
1489                                 terr
1490                             );
1491                         }
1492                     }
1493                 }
1494             }
1495         }
1496     }
1497
1498     fn check_call_dest(
1499         &mut self,
1500         mir: &Mir<'tcx>,
1501         term: &Terminator<'tcx>,
1502         sig: &ty::FnSig<'tcx>,
1503         destination: &Option<(Place<'tcx>, BasicBlock)>,
1504         term_location: Location,
1505     ) {
1506         let tcx = self.tcx();
1507         match *destination {
1508             Some((ref dest, _target_block)) => {
1509                 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1510                 let category = match *dest {
1511                     Place::Local(RETURN_PLACE) => {
1512                         if let Some(BorrowCheckContext {
1513                             universal_regions: UniversalRegions {
1514                                 defining_ty: DefiningTy::Const(def_id, _),
1515                                 ..
1516                             },
1517                             ..
1518                         }) = self.borrowck_context {
1519                             if tcx.is_static(*def_id).is_some() {
1520                                 ConstraintCategory::UseAsStatic
1521                             } else {
1522                                 ConstraintCategory::UseAsConst
1523                             }
1524                         } else {
1525                             ConstraintCategory::Return
1526                         }
1527                     },
1528                     Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1529                         ConstraintCategory::Boring
1530                     }
1531                     _ => ConstraintCategory::Assignment,
1532                 };
1533
1534                 let locations = term_location.to_locations();
1535
1536                 if let Err(terr) =
1537                     self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1538                 {
1539                     span_mirbug!(
1540                         self,
1541                         term,
1542                         "call dest mismatch ({:?} <- {:?}): {:?}",
1543                         dest_ty,
1544                         sig.output(),
1545                         terr
1546                     );
1547                 }
1548
1549                 // When `#![feature(unsized_locals)]` is not enabled,
1550                 // this check is done at `check_local`.
1551                 if self.tcx().features().unsized_locals {
1552                     let span = term.source_info.span;
1553                     self.ensure_place_sized(dest_ty, span);
1554                 }
1555             }
1556             None => {
1557                 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1558                 if !sig.output().is_never() {
1559                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1560                 }
1561             }
1562         }
1563     }
1564
1565     fn check_call_inputs(
1566         &mut self,
1567         mir: &Mir<'tcx>,
1568         term: &Terminator<'tcx>,
1569         sig: &ty::FnSig<'tcx>,
1570         args: &[Operand<'tcx>],
1571         term_location: Location,
1572         from_hir_call: bool,
1573     ) {
1574         debug!("check_call_inputs({:?}, {:?})", sig, args);
1575         if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1576             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1577         }
1578         for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1579             let op_arg_ty = op_arg.ty(mir, self.tcx());
1580             let category = if from_hir_call {
1581                 ConstraintCategory::CallArgument
1582             } else {
1583                 ConstraintCategory::Boring
1584             };
1585             if let Err(terr) = self.sub_types(
1586                 op_arg_ty,
1587                 fn_arg,
1588                 term_location.to_locations(),
1589                 category,
1590             ) {
1591                 span_mirbug!(
1592                     self,
1593                     term,
1594                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1595                     n,
1596                     fn_arg,
1597                     op_arg_ty,
1598                     terr
1599                 );
1600             }
1601         }
1602     }
1603
1604     fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1605         let is_cleanup = block_data.is_cleanup;
1606         self.last_span = block_data.terminator().source_info.span;
1607         match block_data.terminator().kind {
1608             TerminatorKind::Goto { target } => {
1609                 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1610             }
1611             TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1612                 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1613             },
1614             TerminatorKind::Resume => if !is_cleanup {
1615                 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1616             },
1617             TerminatorKind::Abort => if !is_cleanup {
1618                 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1619             },
1620             TerminatorKind::Return => if is_cleanup {
1621                 span_mirbug!(self, block_data, "return on cleanup block")
1622             },
1623             TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1624                 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1625             },
1626             TerminatorKind::Yield { resume, drop, .. } => {
1627                 if is_cleanup {
1628                     span_mirbug!(self, block_data, "yield in cleanup block")
1629                 }
1630                 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1631                 if let Some(drop) = drop {
1632                     self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1633                 }
1634             }
1635             TerminatorKind::Unreachable => {}
1636             TerminatorKind::Drop { target, unwind, .. }
1637             | TerminatorKind::DropAndReplace { target, unwind, .. }
1638             | TerminatorKind::Assert {
1639                 target,
1640                 cleanup: unwind,
1641                 ..
1642             } => {
1643                 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1644                 if let Some(unwind) = unwind {
1645                     if is_cleanup {
1646                         span_mirbug!(self, block_data, "unwind on cleanup block")
1647                     }
1648                     self.assert_iscleanup(mir, block_data, unwind, true);
1649                 }
1650             }
1651             TerminatorKind::Call {
1652                 ref destination,
1653                 cleanup,
1654                 ..
1655             } => {
1656                 if let &Some((_, target)) = destination {
1657                     self.assert_iscleanup(mir, block_data, target, is_cleanup);
1658                 }
1659                 if let Some(cleanup) = cleanup {
1660                     if is_cleanup {
1661                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1662                     }
1663                     self.assert_iscleanup(mir, block_data, cleanup, true);
1664                 }
1665             }
1666             TerminatorKind::FalseEdges {
1667                 real_target,
1668                 ref imaginary_targets,
1669             } => {
1670                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1671                 for target in imaginary_targets {
1672                     self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1673                 }
1674             }
1675             TerminatorKind::FalseUnwind {
1676                 real_target,
1677                 unwind,
1678             } => {
1679                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1680                 if let Some(unwind) = unwind {
1681                     if is_cleanup {
1682                         span_mirbug!(
1683                             self,
1684                             block_data,
1685                             "cleanup in cleanup block via false unwind"
1686                         );
1687                     }
1688                     self.assert_iscleanup(mir, block_data, unwind, true);
1689                 }
1690             }
1691         }
1692     }
1693
1694     fn assert_iscleanup(
1695         &mut self,
1696         mir: &Mir<'tcx>,
1697         ctxt: &dyn fmt::Debug,
1698         bb: BasicBlock,
1699         iscleanuppad: bool,
1700     ) {
1701         if mir[bb].is_cleanup != iscleanuppad {
1702             span_mirbug!(
1703                 self,
1704                 ctxt,
1705                 "cleanuppad mismatch: {:?} should be {:?}",
1706                 bb,
1707                 iscleanuppad
1708             );
1709         }
1710     }
1711
1712     fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1713         match mir.local_kind(local) {
1714             LocalKind::ReturnPointer | LocalKind::Arg => {
1715                 // return values of normal functions are required to be
1716                 // sized by typeck, but return values of ADT constructors are
1717                 // not because we don't include a `Self: Sized` bounds on them.
1718                 //
1719                 // Unbound parts of arguments were never required to be Sized
1720                 // - maybe we should make that a warning.
1721                 return;
1722             }
1723             LocalKind::Var | LocalKind::Temp => {}
1724         }
1725
1726         // When `#![feature(unsized_locals)]` is enabled, only function calls
1727         // and nullary ops are checked in `check_call_dest`.
1728         if !self.tcx().features().unsized_locals {
1729             let span = local_decl.source_info.span;
1730             let ty = local_decl.ty;
1731             self.ensure_place_sized(ty, span);
1732         }
1733     }
1734
1735     fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1736         let tcx = self.tcx();
1737
1738         // Erase the regions from `ty` to get a global type.  The
1739         // `Sized` bound in no way depends on precise regions, so this
1740         // shouldn't affect `is_sized`.
1741         let gcx = tcx.global_tcx();
1742         let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1743         if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1744             // in current MIR construction, all non-control-flow rvalue
1745             // expressions evaluate through `as_temp` or `into` a return
1746             // slot or local, so to find all unsized rvalues it is enough
1747             // to check all temps, return slots and locals.
1748             if let None = self.reported_errors.replace((ty, span)) {
1749                 let mut diag = struct_span_err!(
1750                     self.tcx().sess,
1751                     span,
1752                     E0161,
1753                     "cannot move a value of type {0}: the size of {0} \
1754                      cannot be statically determined",
1755                     ty
1756                 );
1757
1758                 // While this is located in `nll::typeck` this error is not
1759                 // an NLL error, it's a required check to prevent creation
1760                 // of unsized rvalues in certain cases:
1761                 // * operand of a box expression
1762                 // * callee in a call expression
1763                 diag.emit();
1764             }
1765         }
1766     }
1767
1768     fn aggregate_field_ty(
1769         &mut self,
1770         ak: &AggregateKind<'tcx>,
1771         field_index: usize,
1772         location: Location,
1773     ) -> Result<Ty<'tcx>, FieldAccessError> {
1774         let tcx = self.tcx();
1775
1776         match *ak {
1777             AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1778                 let variant = &def.variants[variant_index];
1779                 let adj_field_index = active_field_index.unwrap_or(field_index);
1780                 if let Some(field) = variant.fields.get(adj_field_index) {
1781                     Ok(self.normalize(field.ty(tcx, substs), location))
1782                 } else {
1783                     Err(FieldAccessError::OutOfRange {
1784                         field_count: variant.fields.len(),
1785                     })
1786                 }
1787             }
1788             AggregateKind::Closure(def_id, substs) => {
1789                 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1790                     Some(ty) => Ok(ty),
1791                     None => Err(FieldAccessError::OutOfRange {
1792                         field_count: substs.upvar_tys(def_id, tcx).count(),
1793                     }),
1794                 }
1795             }
1796             AggregateKind::Generator(def_id, substs, _) => {
1797                 // Try pre-transform fields first (upvars and current state)
1798                 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1799                     Ok(ty)
1800                 } else {
1801                     // Then try `field_tys` which contains all the fields, but it
1802                     // requires the final optimized MIR.
1803                     match substs.field_tys(def_id, tcx).nth(field_index) {
1804                         Some(ty) => Ok(ty),
1805                         None => Err(FieldAccessError::OutOfRange {
1806                             field_count: substs.field_tys(def_id, tcx).count(),
1807                         }),
1808                     }
1809                 }
1810             }
1811             AggregateKind::Array(ty) => Ok(ty),
1812             AggregateKind::Tuple => {
1813                 unreachable!("This should have been covered in check_rvalues");
1814             }
1815         }
1816     }
1817
1818     fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1819         let tcx = self.tcx();
1820
1821         match rvalue {
1822             Rvalue::Aggregate(ak, ops) => {
1823                 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1824             }
1825
1826             Rvalue::Repeat(operand, len) => if *len > 1 {
1827                 let operand_ty = operand.ty(mir, tcx);
1828
1829                 let trait_ref = ty::TraitRef {
1830                     def_id: tcx.lang_items().copy_trait().unwrap(),
1831                     substs: tcx.mk_substs_trait(operand_ty, &[]),
1832                 };
1833
1834                 self.prove_trait_ref(
1835                     trait_ref,
1836                     location.to_locations(),
1837                     ConstraintCategory::CopyBound,
1838                 );
1839             },
1840
1841             Rvalue::NullaryOp(_, ty) => {
1842                 // Even with unsized locals cannot box an unsized value.
1843                 if self.tcx().features().unsized_locals {
1844                     let span = mir.source_info(location).span;
1845                     self.ensure_place_sized(ty, span);
1846                 }
1847
1848                 let trait_ref = ty::TraitRef {
1849                     def_id: tcx.lang_items().sized_trait().unwrap(),
1850                     substs: tcx.mk_substs_trait(ty, &[]),
1851                 };
1852
1853                 self.prove_trait_ref(
1854                     trait_ref,
1855                     location.to_locations(),
1856                     ConstraintCategory::SizedBound,
1857                 );
1858             }
1859
1860             Rvalue::Cast(cast_kind, op, ty) => {
1861                 match cast_kind {
1862                     CastKind::ReifyFnPointer => {
1863                         let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1864
1865                         // The type that we see in the fcx is like
1866                         // `foo::<'a, 'b>`, where `foo` is the path to a
1867                         // function definition. When we extract the
1868                         // signature, it comes from the `fn_sig` query,
1869                         // and hence may contain unnormalized results.
1870                         let fn_sig = self.normalize(fn_sig, location);
1871
1872                         let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1873
1874                         if let Err(terr) = self.eq_types(
1875                             ty_fn_ptr_from,
1876                             ty,
1877                             location.to_locations(),
1878                             ConstraintCategory::Cast,
1879                         ) {
1880                             span_mirbug!(
1881                                 self,
1882                                 rvalue,
1883                                 "equating {:?} with {:?} yields {:?}",
1884                                 ty_fn_ptr_from,
1885                                 ty,
1886                                 terr
1887                             );
1888                         }
1889                     }
1890
1891                     CastKind::ClosureFnPointer => {
1892                         let sig = match op.ty(mir, tcx).sty {
1893                             ty::Closure(def_id, substs) => {
1894                                 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1895                             }
1896                             _ => bug!(),
1897                         };
1898                         let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1899
1900                         if let Err(terr) = self.eq_types(
1901                             ty_fn_ptr_from,
1902                             ty,
1903                             location.to_locations(),
1904                             ConstraintCategory::Cast,
1905                         ) {
1906                             span_mirbug!(
1907                                 self,
1908                                 rvalue,
1909                                 "equating {:?} with {:?} yields {:?}",
1910                                 ty_fn_ptr_from,
1911                                 ty,
1912                                 terr
1913                             );
1914                         }
1915                     }
1916
1917                     CastKind::UnsafeFnPointer => {
1918                         let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1919
1920                         // The type that we see in the fcx is like
1921                         // `foo::<'a, 'b>`, where `foo` is the path to a
1922                         // function definition. When we extract the
1923                         // signature, it comes from the `fn_sig` query,
1924                         // and hence may contain unnormalized results.
1925                         let fn_sig = self.normalize(fn_sig, location);
1926
1927                         let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1928
1929                         if let Err(terr) = self.eq_types(
1930                             ty_fn_ptr_from,
1931                             ty,
1932                             location.to_locations(),
1933                             ConstraintCategory::Cast,
1934                         ) {
1935                             span_mirbug!(
1936                                 self,
1937                                 rvalue,
1938                                 "equating {:?} with {:?} yields {:?}",
1939                                 ty_fn_ptr_from,
1940                                 ty,
1941                                 terr
1942                             );
1943                         }
1944                     }
1945
1946                     CastKind::Unsize => {
1947                         let &ty = ty;
1948                         let trait_ref = ty::TraitRef {
1949                             def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1950                             substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1951                         };
1952
1953                         self.prove_trait_ref(
1954                             trait_ref,
1955                             location.to_locations(),
1956                             ConstraintCategory::Cast,
1957                         );
1958                     }
1959
1960                     CastKind::Misc => {}
1961                 }
1962             }
1963
1964             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1965                 self.add_reborrow_constraint(location, region, borrowed_place);
1966             }
1967
1968             // FIXME: These other cases have to be implemented in future PRs
1969             Rvalue::Use(..)
1970             | Rvalue::Len(..)
1971             | Rvalue::BinaryOp(..)
1972             | Rvalue::CheckedBinaryOp(..)
1973             | Rvalue::UnaryOp(..)
1974             | Rvalue::Discriminant(..) => {}
1975         }
1976     }
1977
1978     /// If this rvalue supports a user-given type annotation, then
1979     /// extract and return it. This represents the final type of the
1980     /// rvalue and will be unified with the inferred type.
1981     fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotation<'tcx>> {
1982         match rvalue {
1983             Rvalue::Use(_)
1984             | Rvalue::Repeat(..)
1985             | Rvalue::Ref(..)
1986             | Rvalue::Len(..)
1987             | Rvalue::Cast(..)
1988             | Rvalue::BinaryOp(..)
1989             | Rvalue::CheckedBinaryOp(..)
1990             | Rvalue::NullaryOp(..)
1991             | Rvalue::UnaryOp(..)
1992             | Rvalue::Discriminant(..) => None,
1993
1994             Rvalue::Aggregate(aggregate, _) => match **aggregate {
1995                 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
1996                 AggregateKind::Array(_) => None,
1997                 AggregateKind::Tuple => None,
1998                 AggregateKind::Closure(_, _) => None,
1999                 AggregateKind::Generator(_, _, _) => None,
2000             },
2001         }
2002     }
2003
2004     fn check_aggregate_rvalue(
2005         &mut self,
2006         mir: &Mir<'tcx>,
2007         rvalue: &Rvalue<'tcx>,
2008         aggregate_kind: &AggregateKind<'tcx>,
2009         operands: &[Operand<'tcx>],
2010         location: Location,
2011     ) {
2012         let tcx = self.tcx();
2013
2014         self.prove_aggregate_predicates(aggregate_kind, location);
2015
2016         if *aggregate_kind == AggregateKind::Tuple {
2017             // tuple rvalue field type is always the type of the op. Nothing to check here.
2018             return;
2019         }
2020
2021         for (i, operand) in operands.iter().enumerate() {
2022             let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2023                 Ok(field_ty) => field_ty,
2024                 Err(FieldAccessError::OutOfRange { field_count }) => {
2025                     span_mirbug!(
2026                         self,
2027                         rvalue,
2028                         "accessed field #{} but variant only has {}",
2029                         i,
2030                         field_count
2031                     );
2032                     continue;
2033                 }
2034             };
2035             let operand_ty = operand.ty(mir, tcx);
2036
2037             if let Err(terr) = self.sub_types(
2038                 operand_ty,
2039                 field_ty,
2040                 location.to_locations(),
2041                 ConstraintCategory::Boring,
2042             ) {
2043                 span_mirbug!(
2044                     self,
2045                     rvalue,
2046                     "{:?} is not a subtype of {:?}: {:?}",
2047                     operand_ty,
2048                     field_ty,
2049                     terr
2050                 );
2051             }
2052         }
2053     }
2054
2055     /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
2056     ///
2057     /// # Parameters
2058     ///
2059     /// - `location`: the location `L` where the borrow expression occurs
2060     /// - `borrow_region`: the region `'a` associated with the borrow
2061     /// - `borrowed_place`: the place `P` being borrowed
2062     fn add_reborrow_constraint(
2063         &mut self,
2064         location: Location,
2065         borrow_region: ty::Region<'tcx>,
2066         borrowed_place: &Place<'tcx>,
2067     ) {
2068         // These constraints are only meaningful during borrowck:
2069         let BorrowCheckContext {
2070             borrow_set,
2071             location_table,
2072             all_facts,
2073             constraints,
2074             ..
2075         } = match self.borrowck_context {
2076             Some(ref mut borrowck_context) => borrowck_context,
2077             None => return,
2078         };
2079
2080         // In Polonius mode, we also push a `borrow_region` fact
2081         // linking the loan to the region (in some cases, though,
2082         // there is no loan associated with this borrow expression --
2083         // that occurs when we are borrowing an unsafe place, for
2084         // example).
2085         if let Some(all_facts) = all_facts {
2086             if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2087                 let region_vid = borrow_region.to_region_vid();
2088                 all_facts.borrow_region.push((
2089                     region_vid,
2090                     *borrow_index,
2091                     location_table.mid_index(location),
2092                 ));
2093             }
2094         }
2095
2096         // If we are reborrowing the referent of another reference, we
2097         // need to add outlives relationships. In a case like `&mut
2098         // *p`, where the `p` has type `&'b mut Foo`, for example, we
2099         // need to ensure that `'b: 'a`.
2100
2101         let mut borrowed_place = borrowed_place;
2102
2103         debug!(
2104             "add_reborrow_constraint({:?}, {:?}, {:?})",
2105             location, borrow_region, borrowed_place
2106         );
2107         while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2108             debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2109
2110             match *elem {
2111                 ProjectionElem::Deref => {
2112                     let tcx = self.infcx.tcx;
2113                     let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
2114
2115                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2116                     match base_ty.sty {
2117                         ty::Ref(ref_region, _, mutbl) => {
2118                             constraints.outlives_constraints.push(OutlivesConstraint {
2119                                 sup: ref_region.to_region_vid(),
2120                                 sub: borrow_region.to_region_vid(),
2121                                 locations: location.to_locations(),
2122                                 category: ConstraintCategory::Boring,
2123                             });
2124
2125                             match mutbl {
2126                                 hir::Mutability::MutImmutable => {
2127                                     // Immutable reference. We don't need the base
2128                                     // to be valid for the entire lifetime of
2129                                     // the borrow.
2130                                     break;
2131                                 }
2132                                 hir::Mutability::MutMutable => {
2133                                     // Mutable reference. We *do* need the base
2134                                     // to be valid, because after the base becomes
2135                                     // invalid, someone else can use our mutable deref.
2136
2137                                     // This is in order to make the following function
2138                                     // illegal:
2139                                     // ```
2140                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2141                                     //     &mut *x
2142                                     // }
2143                                     // ```
2144                                     //
2145                                     // As otherwise you could clone `&mut T` using the
2146                                     // following function:
2147                                     // ```
2148                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
2149                                     //     let my_clone = unsafe_deref(&'a x);
2150                                     //     ENDREGION 'a;
2151                                     //     (my_clone, x)
2152                                     // }
2153                                     // ```
2154                                 }
2155                             }
2156                         }
2157                         ty::RawPtr(..) => {
2158                             // deref of raw pointer, guaranteed to be valid
2159                             break;
2160                         }
2161                         ty::Adt(def, _) if def.is_box() => {
2162                             // deref of `Box`, need the base to be valid - propagate
2163                         }
2164                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2165                     }
2166                 }
2167                 ProjectionElem::Field(..)
2168                 | ProjectionElem::Downcast(..)
2169                 | ProjectionElem::Index(..)
2170                 | ProjectionElem::ConstantIndex { .. }
2171                 | ProjectionElem::Subslice { .. } => {
2172                     // other field access
2173                 }
2174             }
2175
2176             // The "propagate" case. We need to check that our base is valid
2177             // for the borrow's lifetime.
2178             borrowed_place = base;
2179         }
2180     }
2181
2182     fn prove_aggregate_predicates(
2183         &mut self,
2184         aggregate_kind: &AggregateKind<'tcx>,
2185         location: Location,
2186     ) {
2187         let tcx = self.tcx();
2188
2189         debug!(
2190             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2191             aggregate_kind, location
2192         );
2193
2194         let instantiated_predicates = match aggregate_kind {
2195             AggregateKind::Adt(def, _, substs, _, _) => {
2196                 tcx.predicates_of(def.did).instantiate(tcx, substs)
2197             }
2198
2199             // For closures, we have some **extra requirements** we
2200             //
2201             // have to check. In particular, in their upvars and
2202             // signatures, closures often reference various regions
2203             // from the surrounding function -- we call those the
2204             // closure's free regions. When we borrow-check (and hence
2205             // region-check) closures, we may find that the closure
2206             // requires certain relationships between those free
2207             // regions. However, because those free regions refer to
2208             // portions of the CFG of their caller, the closure is not
2209             // in a position to verify those relationships. In that
2210             // case, the requirements get "propagated" to us, and so
2211             // we have to solve them here where we instantiate the
2212             // closure.
2213             //
2214             // Despite the opacity of the previous parapgrah, this is
2215             // actually relatively easy to understand in terms of the
2216             // desugaring. A closure gets desugared to a struct, and
2217             // these extra requirements are basically like where
2218             // clauses on the struct.
2219             AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2220             | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2221                 self.prove_closure_bounds(tcx, *def_id, substs, location)
2222             }
2223
2224             AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2225         };
2226
2227         self.normalize_and_prove_instantiated_predicates(
2228             instantiated_predicates,
2229             location.to_locations(),
2230         );
2231     }
2232
2233     fn prove_closure_bounds(
2234         &mut self,
2235         tcx: TyCtxt<'a, 'gcx, 'tcx>,
2236         def_id: DefId,
2237         substs: &'tcx Substs<'tcx>,
2238         location: Location,
2239     ) -> ty::InstantiatedPredicates<'tcx> {
2240         if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2241             let closure_constraints =
2242                 closure_region_requirements.apply_requirements(tcx, location, def_id, substs);
2243
2244             if let Some(ref mut borrowck_context) = self.borrowck_context {
2245                 let bounds_mapping = closure_constraints
2246                     .iter()
2247                     .enumerate()
2248                     .filter_map(|(idx, constraint)| {
2249                         let ty::OutlivesPredicate(k1, r2) =
2250                             constraint.no_late_bound_regions().unwrap_or_else(|| {
2251                                 bug!("query_constraint {:?} contained bound regions", constraint,);
2252                             });
2253
2254                         match k1.unpack() {
2255                             UnpackedKind::Lifetime(r1) => {
2256                                 // constraint is r1: r2
2257                                 let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
2258                                 let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
2259                                 let outlives_requirements =
2260                                     &closure_region_requirements.outlives_requirements[idx];
2261                                 Some((
2262                                     (r1_vid, r2_vid),
2263                                     (
2264                                         outlives_requirements.category,
2265                                         outlives_requirements.blame_span,
2266                                     ),
2267                                 ))
2268                             }
2269                             UnpackedKind::Type(_) => None,
2270                         }
2271                     })
2272                     .collect();
2273
2274                 let existing = borrowck_context
2275                     .constraints
2276                     .closure_bounds_mapping
2277                     .insert(location, bounds_mapping);
2278                 assert!(
2279                     existing.is_none(),
2280                     "Multiple closures at the same location."
2281                 );
2282             }
2283
2284             self.push_region_constraints(
2285                 location.to_locations(),
2286                 ConstraintCategory::ClosureBounds,
2287                 &closure_constraints,
2288             );
2289         }
2290
2291         tcx.predicates_of(def_id).instantiate(tcx, substs)
2292     }
2293
2294     fn prove_trait_ref(
2295         &mut self,
2296         trait_ref: ty::TraitRef<'tcx>,
2297         locations: Locations,
2298         category: ConstraintCategory,
2299     ) {
2300         self.prove_predicates(
2301             Some(ty::Predicate::Trait(
2302                 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2303             )),
2304             locations,
2305             category,
2306         );
2307     }
2308
2309     fn normalize_and_prove_instantiated_predicates(
2310         &mut self,
2311         instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2312         locations: Locations,
2313     ) {
2314         for predicate in instantiated_predicates.predicates {
2315             let predicate = self.normalize(predicate, locations);
2316             self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2317         }
2318     }
2319
2320     fn prove_predicates(
2321         &mut self,
2322         predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2323         locations: Locations,
2324         category: ConstraintCategory,
2325     ) {
2326         for predicate in predicates {
2327             debug!(
2328                 "prove_predicates(predicate={:?}, locations={:?})",
2329                 predicate, locations,
2330             );
2331
2332             self.prove_predicate(predicate, locations, category);
2333         }
2334     }
2335
2336     fn prove_predicate(
2337         &mut self,
2338         predicate: ty::Predicate<'tcx>,
2339         locations: Locations,
2340         category: ConstraintCategory,
2341     ) {
2342         debug!(
2343             "prove_predicate(predicate={:?}, location={:?})",
2344             predicate, locations,
2345         );
2346
2347         let param_env = self.param_env;
2348         self.fully_perform_op(
2349             locations,
2350             category,
2351             param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2352         ).unwrap_or_else(|NoSolution| {
2353             span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2354         })
2355     }
2356
2357     fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2358         self.last_span = mir.span;
2359         debug!("run_on_mir: {:?}", mir.span);
2360
2361         for (local, local_decl) in mir.local_decls.iter_enumerated() {
2362             self.check_local(mir, local, local_decl);
2363         }
2364
2365         for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2366             let mut location = Location {
2367                 block,
2368                 statement_index: 0,
2369             };
2370             for stmt in &block_data.statements {
2371                 if !stmt.source_info.span.is_dummy() {
2372                     self.last_span = stmt.source_info.span;
2373                 }
2374                 self.check_stmt(mir, stmt, location);
2375                 location.statement_index += 1;
2376             }
2377
2378             self.check_terminator(mir, block_data.terminator(), location);
2379             self.check_iscleanup(mir, block_data);
2380         }
2381     }
2382
2383     fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2384     where
2385         T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2386     {
2387         debug!("normalize(value={:?}, location={:?})", value, location);
2388         let param_env = self.param_env;
2389         self.fully_perform_op(
2390             location.to_locations(),
2391             ConstraintCategory::Boring,
2392             param_env.and(type_op::normalize::Normalize::new(value)),
2393         ).unwrap_or_else(|NoSolution| {
2394             span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2395             value
2396         })
2397     }
2398 }
2399
2400 pub struct TypeckMir;
2401
2402 impl MirPass for TypeckMir {
2403     fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
2404         let def_id = src.def_id;
2405         debug!("run_pass: {:?}", def_id);
2406
2407         // When NLL is enabled, the borrow checker runs the typeck
2408         // itself, so we don't need this MIR pass anymore.
2409         if tcx.use_mir_borrowck() {
2410             return;
2411         }
2412
2413         if tcx.sess.err_count() > 0 {
2414             // compiling a broken program can obviously result in a
2415             // broken MIR, so try not to report duplicate errors.
2416             return;
2417         }
2418
2419         if tcx.is_struct_constructor(def_id) {
2420             // We just assume that the automatically generated struct constructors are
2421             // correct. See the comment in the `mir_borrowck` implementation for an
2422             // explanation why we need this.
2423             return;
2424         }
2425
2426         let param_env = tcx.param_env(def_id);
2427         tcx.infer_ctxt().enter(|infcx| {
2428             type_check_internal(
2429                 &infcx,
2430                 def_id,
2431                 param_env,
2432                 mir,
2433                 &vec![],
2434                 None,
2435                 None,
2436                 None,
2437                 |_| (),
2438             );
2439
2440             // For verification purposes, we just ignore the resulting
2441             // region constraint sets. Not our problem. =)
2442         });
2443     }
2444 }
2445
2446 trait NormalizeLocation: fmt::Debug + Copy {
2447     fn to_locations(self) -> Locations;
2448 }
2449
2450 impl NormalizeLocation for Locations {
2451     fn to_locations(self) -> Locations {
2452         self
2453     }
2454 }
2455
2456 impl NormalizeLocation for Location {
2457     fn to_locations(self) -> Locations {
2458         Locations::Single(self)
2459     }
2460 }
2461
2462 #[derive(Debug, Default)]
2463 struct ObligationAccumulator<'tcx> {
2464     obligations: PredicateObligations<'tcx>,
2465 }
2466
2467 impl<'tcx> ObligationAccumulator<'tcx> {
2468     fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2469         let InferOk { value, obligations } = value;
2470         self.obligations.extend(obligations);
2471         value
2472     }
2473
2474     fn into_vec(self) -> PredicateObligations<'tcx> {
2475         self.obligations
2476     }
2477 }