]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/type_check/mod.rs
Rollup merge of #55784 - meltinglava:master, r=KodrAus
[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::Placeholder,
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::EndRegion(_)
1318             | StatementKind::Retag { .. }
1319             | StatementKind::EscapeToRaw { .. }
1320             | StatementKind::Nop => {}
1321         }
1322     }
1323
1324     fn check_terminator(
1325         &mut self,
1326         mir: &Mir<'tcx>,
1327         term: &Terminator<'tcx>,
1328         term_location: Location,
1329     ) {
1330         debug!("check_terminator: {:?}", term);
1331         let tcx = self.tcx();
1332         match term.kind {
1333             TerminatorKind::Goto { .. }
1334             | TerminatorKind::Resume
1335             | TerminatorKind::Abort
1336             | TerminatorKind::Return
1337             | TerminatorKind::GeneratorDrop
1338             | TerminatorKind::Unreachable
1339             | TerminatorKind::Drop { .. }
1340             | TerminatorKind::FalseEdges { .. }
1341             | TerminatorKind::FalseUnwind { .. } => {
1342                 // no checks needed for these
1343             }
1344
1345             TerminatorKind::DropAndReplace {
1346                 ref location,
1347                 ref value,
1348                 target: _,
1349                 unwind: _,
1350             } => {
1351                 let place_ty = location.ty(mir, tcx).to_ty(tcx);
1352                 let rv_ty = value.ty(mir, tcx);
1353
1354                 let locations = term_location.to_locations();
1355                 if let Err(terr) =
1356                     self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1357                 {
1358                     span_mirbug!(
1359                         self,
1360                         term,
1361                         "bad DropAndReplace ({:?} = {:?}): {:?}",
1362                         place_ty,
1363                         rv_ty,
1364                         terr
1365                     );
1366                 }
1367             }
1368             TerminatorKind::SwitchInt {
1369                 ref discr,
1370                 switch_ty,
1371                 ..
1372             } => {
1373                 let discr_ty = discr.ty(mir, tcx);
1374                 if let Err(terr) = self.sub_types(
1375                     discr_ty,
1376                     switch_ty,
1377                     term_location.to_locations(),
1378                     ConstraintCategory::Assignment,
1379                 ) {
1380                     span_mirbug!(
1381                         self,
1382                         term,
1383                         "bad SwitchInt ({:?} on {:?}): {:?}",
1384                         switch_ty,
1385                         discr_ty,
1386                         terr
1387                     );
1388                 }
1389                 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1390                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1391                 }
1392                 // FIXME: check the values
1393             }
1394             TerminatorKind::Call {
1395                 ref func,
1396                 ref args,
1397                 ref destination,
1398                 from_hir_call,
1399                 ..
1400             } => {
1401                 let func_ty = func.ty(mir, tcx);
1402                 debug!("check_terminator: call, func_ty={:?}", func_ty);
1403                 let sig = match func_ty.sty {
1404                     ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1405                     _ => {
1406                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1407                         return;
1408                     }
1409                 };
1410                 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1411                     term.source_info.span,
1412                     LateBoundRegionConversionTime::FnCall,
1413                     &sig,
1414                 );
1415                 let sig = self.normalize(sig, term_location);
1416                 self.check_call_dest(mir, term, &sig, destination, term_location);
1417
1418                 self.prove_predicates(
1419                     sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1420                     term_location.to_locations(),
1421                     ConstraintCategory::Boring,
1422                 );
1423
1424                 // The ordinary liveness rules will ensure that all
1425                 // regions in the type of the callee are live here. We
1426                 // then further constrain the late-bound regions that
1427                 // were instantiated at the call site to be live as
1428                 // well. The resulting is that all the input (and
1429                 // output) types in the signature must be live, since
1430                 // all the inputs that fed into it were live.
1431                 for &late_bound_region in map.values() {
1432                     if let Some(ref mut borrowck_context) = self.borrowck_context {
1433                         let region_vid = borrowck_context
1434                             .universal_regions
1435                             .to_region_vid(late_bound_region);
1436                         borrowck_context
1437                             .constraints
1438                             .liveness_constraints
1439                             .add_element(region_vid, term_location);
1440                     }
1441                 }
1442
1443                 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1444             }
1445             TerminatorKind::Assert {
1446                 ref cond, ref msg, ..
1447             } => {
1448                 let cond_ty = cond.ty(mir, tcx);
1449                 if cond_ty != tcx.types.bool {
1450                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1451                 }
1452
1453                 if let BoundsCheck { ref len, ref index } = *msg {
1454                     if len.ty(mir, tcx) != tcx.types.usize {
1455                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1456                     }
1457                     if index.ty(mir, tcx) != tcx.types.usize {
1458                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1459                     }
1460                 }
1461             }
1462             TerminatorKind::Yield { ref value, .. } => {
1463                 let value_ty = value.ty(mir, tcx);
1464                 match mir.yield_ty {
1465                     None => span_mirbug!(self, term, "yield in non-generator"),
1466                     Some(ty) => {
1467                         if let Err(terr) = self.sub_types(
1468                             value_ty,
1469                             ty,
1470                             term_location.to_locations(),
1471                             ConstraintCategory::Return,
1472                         ) {
1473                             span_mirbug!(
1474                                 self,
1475                                 term,
1476                                 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1477                                 value_ty,
1478                                 ty,
1479                                 terr
1480                             );
1481                         }
1482                     }
1483                 }
1484             }
1485         }
1486     }
1487
1488     fn check_call_dest(
1489         &mut self,
1490         mir: &Mir<'tcx>,
1491         term: &Terminator<'tcx>,
1492         sig: &ty::FnSig<'tcx>,
1493         destination: &Option<(Place<'tcx>, BasicBlock)>,
1494         term_location: Location,
1495     ) {
1496         let tcx = self.tcx();
1497         match *destination {
1498             Some((ref dest, _target_block)) => {
1499                 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1500                 let category = match *dest {
1501                     Place::Local(RETURN_PLACE) => {
1502                         if let Some(BorrowCheckContext {
1503                             universal_regions:
1504                                 UniversalRegions {
1505                                     defining_ty: DefiningTy::Const(def_id, _),
1506                                     ..
1507                                 },
1508                             ..
1509                         }) = self.borrowck_context
1510                         {
1511                             if tcx.is_static(*def_id).is_some() {
1512                                 ConstraintCategory::UseAsStatic
1513                             } else {
1514                                 ConstraintCategory::UseAsConst
1515                             }
1516                         } else {
1517                             ConstraintCategory::Return
1518                         }
1519                     }
1520                     Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1521                         ConstraintCategory::Boring
1522                     }
1523                     _ => ConstraintCategory::Assignment,
1524                 };
1525
1526                 let locations = term_location.to_locations();
1527
1528                 if let Err(terr) =
1529                     self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1530                 {
1531                     span_mirbug!(
1532                         self,
1533                         term,
1534                         "call dest mismatch ({:?} <- {:?}): {:?}",
1535                         dest_ty,
1536                         sig.output(),
1537                         terr
1538                     );
1539                 }
1540
1541                 // When `#![feature(unsized_locals)]` is not enabled,
1542                 // this check is done at `check_local`.
1543                 if self.tcx().features().unsized_locals {
1544                     let span = term.source_info.span;
1545                     self.ensure_place_sized(dest_ty, span);
1546                 }
1547             }
1548             None => {
1549                 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1550                 if !sig.output().is_never() {
1551                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1552                 }
1553             }
1554         }
1555     }
1556
1557     fn check_call_inputs(
1558         &mut self,
1559         mir: &Mir<'tcx>,
1560         term: &Terminator<'tcx>,
1561         sig: &ty::FnSig<'tcx>,
1562         args: &[Operand<'tcx>],
1563         term_location: Location,
1564         from_hir_call: bool,
1565     ) {
1566         debug!("check_call_inputs({:?}, {:?})", sig, args);
1567         if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1568             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1569         }
1570         for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1571             let op_arg_ty = op_arg.ty(mir, self.tcx());
1572             let category = if from_hir_call {
1573                 ConstraintCategory::CallArgument
1574             } else {
1575                 ConstraintCategory::Boring
1576             };
1577             if let Err(terr) =
1578                 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1579             {
1580                 span_mirbug!(
1581                     self,
1582                     term,
1583                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1584                     n,
1585                     fn_arg,
1586                     op_arg_ty,
1587                     terr
1588                 );
1589             }
1590         }
1591     }
1592
1593     fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1594         let is_cleanup = block_data.is_cleanup;
1595         self.last_span = block_data.terminator().source_info.span;
1596         match block_data.terminator().kind {
1597             TerminatorKind::Goto { target } => {
1598                 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1599             }
1600             TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1601                 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1602             },
1603             TerminatorKind::Resume => if !is_cleanup {
1604                 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1605             },
1606             TerminatorKind::Abort => if !is_cleanup {
1607                 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1608             },
1609             TerminatorKind::Return => if is_cleanup {
1610                 span_mirbug!(self, block_data, "return on cleanup block")
1611             },
1612             TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1613                 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1614             },
1615             TerminatorKind::Yield { resume, drop, .. } => {
1616                 if is_cleanup {
1617                     span_mirbug!(self, block_data, "yield in cleanup block")
1618                 }
1619                 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1620                 if let Some(drop) = drop {
1621                     self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1622                 }
1623             }
1624             TerminatorKind::Unreachable => {}
1625             TerminatorKind::Drop { target, unwind, .. }
1626             | TerminatorKind::DropAndReplace { target, unwind, .. }
1627             | TerminatorKind::Assert {
1628                 target,
1629                 cleanup: unwind,
1630                 ..
1631             } => {
1632                 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1633                 if let Some(unwind) = unwind {
1634                     if is_cleanup {
1635                         span_mirbug!(self, block_data, "unwind on cleanup block")
1636                     }
1637                     self.assert_iscleanup(mir, block_data, unwind, true);
1638                 }
1639             }
1640             TerminatorKind::Call {
1641                 ref destination,
1642                 cleanup,
1643                 ..
1644             } => {
1645                 if let &Some((_, target)) = destination {
1646                     self.assert_iscleanup(mir, block_data, target, is_cleanup);
1647                 }
1648                 if let Some(cleanup) = cleanup {
1649                     if is_cleanup {
1650                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1651                     }
1652                     self.assert_iscleanup(mir, block_data, cleanup, true);
1653                 }
1654             }
1655             TerminatorKind::FalseEdges {
1656                 real_target,
1657                 ref imaginary_targets,
1658             } => {
1659                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1660                 for target in imaginary_targets {
1661                     self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1662                 }
1663             }
1664             TerminatorKind::FalseUnwind {
1665                 real_target,
1666                 unwind,
1667             } => {
1668                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1669                 if let Some(unwind) = unwind {
1670                     if is_cleanup {
1671                         span_mirbug!(
1672                             self,
1673                             block_data,
1674                             "cleanup in cleanup block via false unwind"
1675                         );
1676                     }
1677                     self.assert_iscleanup(mir, block_data, unwind, true);
1678                 }
1679             }
1680         }
1681     }
1682
1683     fn assert_iscleanup(
1684         &mut self,
1685         mir: &Mir<'tcx>,
1686         ctxt: &dyn fmt::Debug,
1687         bb: BasicBlock,
1688         iscleanuppad: bool,
1689     ) {
1690         if mir[bb].is_cleanup != iscleanuppad {
1691             span_mirbug!(
1692                 self,
1693                 ctxt,
1694                 "cleanuppad mismatch: {:?} should be {:?}",
1695                 bb,
1696                 iscleanuppad
1697             );
1698         }
1699     }
1700
1701     fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1702         match mir.local_kind(local) {
1703             LocalKind::ReturnPointer | LocalKind::Arg => {
1704                 // return values of normal functions are required to be
1705                 // sized by typeck, but return values of ADT constructors are
1706                 // not because we don't include a `Self: Sized` bounds on them.
1707                 //
1708                 // Unbound parts of arguments were never required to be Sized
1709                 // - maybe we should make that a warning.
1710                 return;
1711             }
1712             LocalKind::Var | LocalKind::Temp => {}
1713         }
1714
1715         // When `#![feature(unsized_locals)]` is enabled, only function calls
1716         // and nullary ops are checked in `check_call_dest`.
1717         if !self.tcx().features().unsized_locals {
1718             let span = local_decl.source_info.span;
1719             let ty = local_decl.ty;
1720             self.ensure_place_sized(ty, span);
1721         }
1722     }
1723
1724     fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1725         let tcx = self.tcx();
1726
1727         // Erase the regions from `ty` to get a global type.  The
1728         // `Sized` bound in no way depends on precise regions, so this
1729         // shouldn't affect `is_sized`.
1730         let gcx = tcx.global_tcx();
1731         let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1732         if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1733             // in current MIR construction, all non-control-flow rvalue
1734             // expressions evaluate through `as_temp` or `into` a return
1735             // slot or local, so to find all unsized rvalues it is enough
1736             // to check all temps, return slots and locals.
1737             if let None = self.reported_errors.replace((ty, span)) {
1738                 let mut diag = struct_span_err!(
1739                     self.tcx().sess,
1740                     span,
1741                     E0161,
1742                     "cannot move a value of type {0}: the size of {0} \
1743                      cannot be statically determined",
1744                     ty
1745                 );
1746
1747                 // While this is located in `nll::typeck` this error is not
1748                 // an NLL error, it's a required check to prevent creation
1749                 // of unsized rvalues in certain cases:
1750                 // * operand of a box expression
1751                 // * callee in a call expression
1752                 diag.emit();
1753             }
1754         }
1755     }
1756
1757     fn aggregate_field_ty(
1758         &mut self,
1759         ak: &AggregateKind<'tcx>,
1760         field_index: usize,
1761         location: Location,
1762     ) -> Result<Ty<'tcx>, FieldAccessError> {
1763         let tcx = self.tcx();
1764
1765         match *ak {
1766             AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1767                 let variant = &def.variants[variant_index];
1768                 let adj_field_index = active_field_index.unwrap_or(field_index);
1769                 if let Some(field) = variant.fields.get(adj_field_index) {
1770                     Ok(self.normalize(field.ty(tcx, substs), location))
1771                 } else {
1772                     Err(FieldAccessError::OutOfRange {
1773                         field_count: variant.fields.len(),
1774                     })
1775                 }
1776             }
1777             AggregateKind::Closure(def_id, substs) => {
1778                 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1779                     Some(ty) => Ok(ty),
1780                     None => Err(FieldAccessError::OutOfRange {
1781                         field_count: substs.upvar_tys(def_id, tcx).count(),
1782                     }),
1783                 }
1784             }
1785             AggregateKind::Generator(def_id, substs, _) => {
1786                 // Try pre-transform fields first (upvars and current state)
1787                 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1788                     Ok(ty)
1789                 } else {
1790                     // Then try `field_tys` which contains all the fields, but it
1791                     // requires the final optimized MIR.
1792                     match substs.field_tys(def_id, tcx).nth(field_index) {
1793                         Some(ty) => Ok(ty),
1794                         None => Err(FieldAccessError::OutOfRange {
1795                             field_count: substs.field_tys(def_id, tcx).count(),
1796                         }),
1797                     }
1798                 }
1799             }
1800             AggregateKind::Array(ty) => Ok(ty),
1801             AggregateKind::Tuple => {
1802                 unreachable!("This should have been covered in check_rvalues");
1803             }
1804         }
1805     }
1806
1807     fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1808         let tcx = self.tcx();
1809
1810         match rvalue {
1811             Rvalue::Aggregate(ak, ops) => {
1812                 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1813             }
1814
1815             Rvalue::Repeat(operand, len) => if *len > 1 {
1816                 let operand_ty = operand.ty(mir, tcx);
1817
1818                 let trait_ref = ty::TraitRef {
1819                     def_id: tcx.lang_items().copy_trait().unwrap(),
1820                     substs: tcx.mk_substs_trait(operand_ty, &[]),
1821                 };
1822
1823                 self.prove_trait_ref(
1824                     trait_ref,
1825                     location.to_locations(),
1826                     ConstraintCategory::CopyBound,
1827                 );
1828             },
1829
1830             Rvalue::NullaryOp(_, ty) => {
1831                 // Even with unsized locals cannot box an unsized value.
1832                 if self.tcx().features().unsized_locals {
1833                     let span = mir.source_info(location).span;
1834                     self.ensure_place_sized(ty, span);
1835                 }
1836
1837                 let trait_ref = ty::TraitRef {
1838                     def_id: tcx.lang_items().sized_trait().unwrap(),
1839                     substs: tcx.mk_substs_trait(ty, &[]),
1840                 };
1841
1842                 self.prove_trait_ref(
1843                     trait_ref,
1844                     location.to_locations(),
1845                     ConstraintCategory::SizedBound,
1846                 );
1847             }
1848
1849             Rvalue::Cast(cast_kind, op, ty) => {
1850                 match cast_kind {
1851                     CastKind::ReifyFnPointer => {
1852                         let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1853
1854                         // The type that we see in the fcx is like
1855                         // `foo::<'a, 'b>`, where `foo` is the path to a
1856                         // function definition. When we extract the
1857                         // signature, it comes from the `fn_sig` query,
1858                         // and hence may contain unnormalized results.
1859                         let fn_sig = self.normalize(fn_sig, location);
1860
1861                         let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1862
1863                         if let Err(terr) = self.eq_types(
1864                             ty_fn_ptr_from,
1865                             ty,
1866                             location.to_locations(),
1867                             ConstraintCategory::Cast,
1868                         ) {
1869                             span_mirbug!(
1870                                 self,
1871                                 rvalue,
1872                                 "equating {:?} with {:?} yields {:?}",
1873                                 ty_fn_ptr_from,
1874                                 ty,
1875                                 terr
1876                             );
1877                         }
1878                     }
1879
1880                     CastKind::ClosureFnPointer => {
1881                         let sig = match op.ty(mir, tcx).sty {
1882                             ty::Closure(def_id, substs) => {
1883                                 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1884                             }
1885                             _ => bug!(),
1886                         };
1887                         let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1888
1889                         if let Err(terr) = self.eq_types(
1890                             ty_fn_ptr_from,
1891                             ty,
1892                             location.to_locations(),
1893                             ConstraintCategory::Cast,
1894                         ) {
1895                             span_mirbug!(
1896                                 self,
1897                                 rvalue,
1898                                 "equating {:?} with {:?} yields {:?}",
1899                                 ty_fn_ptr_from,
1900                                 ty,
1901                                 terr
1902                             );
1903                         }
1904                     }
1905
1906                     CastKind::UnsafeFnPointer => {
1907                         let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1908
1909                         // The type that we see in the fcx is like
1910                         // `foo::<'a, 'b>`, where `foo` is the path to a
1911                         // function definition. When we extract the
1912                         // signature, it comes from the `fn_sig` query,
1913                         // and hence may contain unnormalized results.
1914                         let fn_sig = self.normalize(fn_sig, location);
1915
1916                         let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1917
1918                         if let Err(terr) = self.eq_types(
1919                             ty_fn_ptr_from,
1920                             ty,
1921                             location.to_locations(),
1922                             ConstraintCategory::Cast,
1923                         ) {
1924                             span_mirbug!(
1925                                 self,
1926                                 rvalue,
1927                                 "equating {:?} with {:?} yields {:?}",
1928                                 ty_fn_ptr_from,
1929                                 ty,
1930                                 terr
1931                             );
1932                         }
1933                     }
1934
1935                     CastKind::Unsize => {
1936                         let &ty = ty;
1937                         let trait_ref = ty::TraitRef {
1938                             def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1939                             substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1940                         };
1941
1942                         self.prove_trait_ref(
1943                             trait_ref,
1944                             location.to_locations(),
1945                             ConstraintCategory::Cast,
1946                         );
1947                     }
1948
1949                     CastKind::Misc => {}
1950                 }
1951             }
1952
1953             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1954                 self.add_reborrow_constraint(location, region, borrowed_place);
1955             }
1956
1957             // FIXME: These other cases have to be implemented in future PRs
1958             Rvalue::Use(..)
1959             | Rvalue::Len(..)
1960             | Rvalue::BinaryOp(..)
1961             | Rvalue::CheckedBinaryOp(..)
1962             | Rvalue::UnaryOp(..)
1963             | Rvalue::Discriminant(..) => {}
1964         }
1965     }
1966
1967     /// If this rvalue supports a user-given type annotation, then
1968     /// extract and return it. This represents the final type of the
1969     /// rvalue and will be unified with the inferred type.
1970     fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotation<'tcx>> {
1971         match rvalue {
1972             Rvalue::Use(_)
1973             | Rvalue::Repeat(..)
1974             | Rvalue::Ref(..)
1975             | Rvalue::Len(..)
1976             | Rvalue::Cast(..)
1977             | Rvalue::BinaryOp(..)
1978             | Rvalue::CheckedBinaryOp(..)
1979             | Rvalue::NullaryOp(..)
1980             | Rvalue::UnaryOp(..)
1981             | Rvalue::Discriminant(..) => None,
1982
1983             Rvalue::Aggregate(aggregate, _) => match **aggregate {
1984                 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
1985                 AggregateKind::Array(_) => None,
1986                 AggregateKind::Tuple => None,
1987                 AggregateKind::Closure(_, _) => None,
1988                 AggregateKind::Generator(_, _, _) => None,
1989             },
1990         }
1991     }
1992
1993     fn check_aggregate_rvalue(
1994         &mut self,
1995         mir: &Mir<'tcx>,
1996         rvalue: &Rvalue<'tcx>,
1997         aggregate_kind: &AggregateKind<'tcx>,
1998         operands: &[Operand<'tcx>],
1999         location: Location,
2000     ) {
2001         let tcx = self.tcx();
2002
2003         self.prove_aggregate_predicates(aggregate_kind, location);
2004
2005         if *aggregate_kind == AggregateKind::Tuple {
2006             // tuple rvalue field type is always the type of the op. Nothing to check here.
2007             return;
2008         }
2009
2010         for (i, operand) in operands.iter().enumerate() {
2011             let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2012                 Ok(field_ty) => field_ty,
2013                 Err(FieldAccessError::OutOfRange { field_count }) => {
2014                     span_mirbug!(
2015                         self,
2016                         rvalue,
2017                         "accessed field #{} but variant only has {}",
2018                         i,
2019                         field_count
2020                     );
2021                     continue;
2022                 }
2023             };
2024             let operand_ty = operand.ty(mir, tcx);
2025
2026             if let Err(terr) = self.sub_types(
2027                 operand_ty,
2028                 field_ty,
2029                 location.to_locations(),
2030                 ConstraintCategory::Boring,
2031             ) {
2032                 span_mirbug!(
2033                     self,
2034                     rvalue,
2035                     "{:?} is not a subtype of {:?}: {:?}",
2036                     operand_ty,
2037                     field_ty,
2038                     terr
2039                 );
2040             }
2041         }
2042     }
2043
2044     /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
2045     ///
2046     /// # Parameters
2047     ///
2048     /// - `location`: the location `L` where the borrow expression occurs
2049     /// - `borrow_region`: the region `'a` associated with the borrow
2050     /// - `borrowed_place`: the place `P` being borrowed
2051     fn add_reborrow_constraint(
2052         &mut self,
2053         location: Location,
2054         borrow_region: ty::Region<'tcx>,
2055         borrowed_place: &Place<'tcx>,
2056     ) {
2057         // These constraints are only meaningful during borrowck:
2058         let BorrowCheckContext {
2059             borrow_set,
2060             location_table,
2061             all_facts,
2062             constraints,
2063             ..
2064         } = match self.borrowck_context {
2065             Some(ref mut borrowck_context) => borrowck_context,
2066             None => return,
2067         };
2068
2069         // In Polonius mode, we also push a `borrow_region` fact
2070         // linking the loan to the region (in some cases, though,
2071         // there is no loan associated with this borrow expression --
2072         // that occurs when we are borrowing an unsafe place, for
2073         // example).
2074         if let Some(all_facts) = all_facts {
2075             if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2076                 let region_vid = borrow_region.to_region_vid();
2077                 all_facts.borrow_region.push((
2078                     region_vid,
2079                     *borrow_index,
2080                     location_table.mid_index(location),
2081                 ));
2082             }
2083         }
2084
2085         // If we are reborrowing the referent of another reference, we
2086         // need to add outlives relationships. In a case like `&mut
2087         // *p`, where the `p` has type `&'b mut Foo`, for example, we
2088         // need to ensure that `'b: 'a`.
2089
2090         let mut borrowed_place = borrowed_place;
2091
2092         debug!(
2093             "add_reborrow_constraint({:?}, {:?}, {:?})",
2094             location, borrow_region, borrowed_place
2095         );
2096         while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2097             debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2098
2099             match *elem {
2100                 ProjectionElem::Deref => {
2101                     let tcx = self.infcx.tcx;
2102                     let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
2103
2104                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2105                     match base_ty.sty {
2106                         ty::Ref(ref_region, _, mutbl) => {
2107                             constraints.outlives_constraints.push(OutlivesConstraint {
2108                                 sup: ref_region.to_region_vid(),
2109                                 sub: borrow_region.to_region_vid(),
2110                                 locations: location.to_locations(),
2111                                 category: ConstraintCategory::Boring,
2112                             });
2113
2114                             match mutbl {
2115                                 hir::Mutability::MutImmutable => {
2116                                     // Immutable reference. We don't need the base
2117                                     // to be valid for the entire lifetime of
2118                                     // the borrow.
2119                                     break;
2120                                 }
2121                                 hir::Mutability::MutMutable => {
2122                                     // Mutable reference. We *do* need the base
2123                                     // to be valid, because after the base becomes
2124                                     // invalid, someone else can use our mutable deref.
2125
2126                                     // This is in order to make the following function
2127                                     // illegal:
2128                                     // ```
2129                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2130                                     //     &mut *x
2131                                     // }
2132                                     // ```
2133                                     //
2134                                     // As otherwise you could clone `&mut T` using the
2135                                     // following function:
2136                                     // ```
2137                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
2138                                     //     let my_clone = unsafe_deref(&'a x);
2139                                     //     ENDREGION 'a;
2140                                     //     (my_clone, x)
2141                                     // }
2142                                     // ```
2143                                 }
2144                             }
2145                         }
2146                         ty::RawPtr(..) => {
2147                             // deref of raw pointer, guaranteed to be valid
2148                             break;
2149                         }
2150                         ty::Adt(def, _) if def.is_box() => {
2151                             // deref of `Box`, need the base to be valid - propagate
2152                         }
2153                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2154                     }
2155                 }
2156                 ProjectionElem::Field(..)
2157                 | ProjectionElem::Downcast(..)
2158                 | ProjectionElem::Index(..)
2159                 | ProjectionElem::ConstantIndex { .. }
2160                 | ProjectionElem::Subslice { .. } => {
2161                     // other field access
2162                 }
2163             }
2164
2165             // The "propagate" case. We need to check that our base is valid
2166             // for the borrow's lifetime.
2167             borrowed_place = base;
2168         }
2169     }
2170
2171     fn prove_aggregate_predicates(
2172         &mut self,
2173         aggregate_kind: &AggregateKind<'tcx>,
2174         location: Location,
2175     ) {
2176         let tcx = self.tcx();
2177
2178         debug!(
2179             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2180             aggregate_kind, location
2181         );
2182
2183         let instantiated_predicates = match aggregate_kind {
2184             AggregateKind::Adt(def, _, substs, _, _) => {
2185                 tcx.predicates_of(def.did).instantiate(tcx, substs)
2186             }
2187
2188             // For closures, we have some **extra requirements** we
2189             //
2190             // have to check. In particular, in their upvars and
2191             // signatures, closures often reference various regions
2192             // from the surrounding function -- we call those the
2193             // closure's free regions. When we borrow-check (and hence
2194             // region-check) closures, we may find that the closure
2195             // requires certain relationships between those free
2196             // regions. However, because those free regions refer to
2197             // portions of the CFG of their caller, the closure is not
2198             // in a position to verify those relationships. In that
2199             // case, the requirements get "propagated" to us, and so
2200             // we have to solve them here where we instantiate the
2201             // closure.
2202             //
2203             // Despite the opacity of the previous parapgrah, this is
2204             // actually relatively easy to understand in terms of the
2205             // desugaring. A closure gets desugared to a struct, and
2206             // these extra requirements are basically like where
2207             // clauses on the struct.
2208             AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2209             | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2210                 self.prove_closure_bounds(tcx, *def_id, substs, location)
2211             }
2212
2213             AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2214         };
2215
2216         self.normalize_and_prove_instantiated_predicates(
2217             instantiated_predicates,
2218             location.to_locations(),
2219         );
2220     }
2221
2222     fn prove_closure_bounds(
2223         &mut self,
2224         tcx: TyCtxt<'a, 'gcx, 'tcx>,
2225         def_id: DefId,
2226         substs: &'tcx Substs<'tcx>,
2227         location: Location,
2228     ) -> ty::InstantiatedPredicates<'tcx> {
2229         if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2230             let closure_constraints =
2231                 closure_region_requirements.apply_requirements(tcx, location, def_id, substs);
2232
2233             if let Some(ref mut borrowck_context) = self.borrowck_context {
2234                 let bounds_mapping = closure_constraints
2235                     .iter()
2236                     .enumerate()
2237                     .filter_map(|(idx, constraint)| {
2238                         let ty::OutlivesPredicate(k1, r2) =
2239                             constraint.no_bound_vars().unwrap_or_else(|| {
2240                                 bug!("query_constraint {:?} contained bound vars", constraint,);
2241                             });
2242
2243                         match k1.unpack() {
2244                             UnpackedKind::Lifetime(r1) => {
2245                                 // constraint is r1: r2
2246                                 let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
2247                                 let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
2248                                 let outlives_requirements =
2249                                     &closure_region_requirements.outlives_requirements[idx];
2250                                 Some((
2251                                     (r1_vid, r2_vid),
2252                                     (
2253                                         outlives_requirements.category,
2254                                         outlives_requirements.blame_span,
2255                                     ),
2256                                 ))
2257                             }
2258                             UnpackedKind::Type(_) => None,
2259                         }
2260                     })
2261                     .collect();
2262
2263                 let existing = borrowck_context
2264                     .constraints
2265                     .closure_bounds_mapping
2266                     .insert(location, bounds_mapping);
2267                 assert!(
2268                     existing.is_none(),
2269                     "Multiple closures at the same location."
2270                 );
2271             }
2272
2273             self.push_region_constraints(
2274                 location.to_locations(),
2275                 ConstraintCategory::ClosureBounds,
2276                 &closure_constraints,
2277             );
2278         }
2279
2280         tcx.predicates_of(def_id).instantiate(tcx, substs)
2281     }
2282
2283     fn prove_trait_ref(
2284         &mut self,
2285         trait_ref: ty::TraitRef<'tcx>,
2286         locations: Locations,
2287         category: ConstraintCategory,
2288     ) {
2289         self.prove_predicates(
2290             Some(ty::Predicate::Trait(
2291                 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2292             )),
2293             locations,
2294             category,
2295         );
2296     }
2297
2298     fn normalize_and_prove_instantiated_predicates(
2299         &mut self,
2300         instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2301         locations: Locations,
2302     ) {
2303         for predicate in instantiated_predicates.predicates {
2304             let predicate = self.normalize(predicate, locations);
2305             self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2306         }
2307     }
2308
2309     fn prove_predicates(
2310         &mut self,
2311         predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2312         locations: Locations,
2313         category: ConstraintCategory,
2314     ) {
2315         for predicate in predicates {
2316             debug!(
2317                 "prove_predicates(predicate={:?}, locations={:?})",
2318                 predicate, locations,
2319             );
2320
2321             self.prove_predicate(predicate, locations, category);
2322         }
2323     }
2324
2325     fn prove_predicate(
2326         &mut self,
2327         predicate: ty::Predicate<'tcx>,
2328         locations: Locations,
2329         category: ConstraintCategory,
2330     ) {
2331         debug!(
2332             "prove_predicate(predicate={:?}, location={:?})",
2333             predicate, locations,
2334         );
2335
2336         let param_env = self.param_env;
2337         self.fully_perform_op(
2338             locations,
2339             category,
2340             param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2341         ).unwrap_or_else(|NoSolution| {
2342             span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2343         })
2344     }
2345
2346     fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2347         self.last_span = mir.span;
2348         debug!("run_on_mir: {:?}", mir.span);
2349
2350         for (local, local_decl) in mir.local_decls.iter_enumerated() {
2351             self.check_local(mir, local, local_decl);
2352         }
2353
2354         for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2355             let mut location = Location {
2356                 block,
2357                 statement_index: 0,
2358             };
2359             for stmt in &block_data.statements {
2360                 if !stmt.source_info.span.is_dummy() {
2361                     self.last_span = stmt.source_info.span;
2362                 }
2363                 self.check_stmt(mir, stmt, location);
2364                 location.statement_index += 1;
2365             }
2366
2367             self.check_terminator(mir, block_data.terminator(), location);
2368             self.check_iscleanup(mir, block_data);
2369         }
2370     }
2371
2372     fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2373     where
2374         T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2375     {
2376         debug!("normalize(value={:?}, location={:?})", value, location);
2377         let param_env = self.param_env;
2378         self.fully_perform_op(
2379             location.to_locations(),
2380             ConstraintCategory::Boring,
2381             param_env.and(type_op::normalize::Normalize::new(value)),
2382         ).unwrap_or_else(|NoSolution| {
2383             span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2384             value
2385         })
2386     }
2387 }
2388
2389 pub struct TypeckMir;
2390
2391 impl MirPass for TypeckMir {
2392     fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
2393         let def_id = src.def_id;
2394         debug!("run_pass: {:?}", def_id);
2395
2396         // When NLL is enabled, the borrow checker runs the typeck
2397         // itself, so we don't need this MIR pass anymore.
2398         if tcx.use_mir_borrowck() {
2399             return;
2400         }
2401
2402         if tcx.sess.err_count() > 0 {
2403             // compiling a broken program can obviously result in a
2404             // broken MIR, so try not to report duplicate errors.
2405             return;
2406         }
2407
2408         if tcx.is_struct_constructor(def_id) {
2409             // We just assume that the automatically generated struct constructors are
2410             // correct. See the comment in the `mir_borrowck` implementation for an
2411             // explanation why we need this.
2412             return;
2413         }
2414
2415         let param_env = tcx.param_env(def_id);
2416         tcx.infer_ctxt().enter(|infcx| {
2417             type_check_internal(
2418                 &infcx,
2419                 def_id,
2420                 param_env,
2421                 mir,
2422                 &vec![],
2423                 None,
2424                 None,
2425                 None,
2426                 |_| (),
2427             );
2428
2429             // For verification purposes, we just ignore the resulting
2430             // region constraint sets. Not our problem. =)
2431         });
2432     }
2433 }
2434
2435 trait NormalizeLocation: fmt::Debug + Copy {
2436     fn to_locations(self) -> Locations;
2437 }
2438
2439 impl NormalizeLocation for Locations {
2440     fn to_locations(self) -> Locations {
2441         self
2442     }
2443 }
2444
2445 impl NormalizeLocation for Location {
2446     fn to_locations(self) -> Locations {
2447         Locations::Single(self)
2448     }
2449 }
2450
2451 #[derive(Debug, Default)]
2452 struct ObligationAccumulator<'tcx> {
2453     obligations: PredicateObligations<'tcx>,
2454 }
2455
2456 impl<'tcx> ObligationAccumulator<'tcx> {
2457     fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2458         let InferOk { value, obligations } = value;
2459         self.obligations.extend(obligations);
2460         value
2461     }
2462
2463     fn into_vec(self) -> PredicateObligations<'tcx> {
2464         self.obligations
2465     }
2466 }