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