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