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