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