]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/type_check/mod.rs
Auto merge of #53436 - cuviper:trace_fn-stop, 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                     l != RETURN_PLACE &&
882                     !mir.local_decls[l].is_user_variable.is_some()
883                 } else {
884                     false
885                 };
886
887                 let locations = if is_temp {
888                     location.boring()
889                 } else {
890                     location.interesting()
891                 };
892
893                 let place_ty = place.ty(mir, tcx).to_ty(tcx);
894                 let rv_ty = rv.ty(mir, tcx);
895                 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
896                     span_mirbug!(
897                         self,
898                         stmt,
899                         "bad assignment ({:?} = {:?}): {:?}",
900                         place_ty,
901                         rv_ty,
902                         terr
903                     );
904                 }
905                 self.check_rvalue(mir, rv, location);
906                 let trait_ref = ty::TraitRef {
907                     def_id: tcx.lang_items().sized_trait().unwrap(),
908                     substs: tcx.mk_substs_trait(place_ty, &[]),
909                 };
910                 self.prove_trait_ref(trait_ref, location.interesting());
911             }
912             StatementKind::SetDiscriminant {
913                 ref place,
914                 variant_index,
915             } => {
916                 let place_type = place.ty(mir, tcx).to_ty(tcx);
917                 let adt = match place_type.sty {
918                     TypeVariants::TyAdt(adt, _) if adt.is_enum() => adt,
919                     _ => {
920                         span_bug!(
921                             stmt.source_info.span,
922                             "bad set discriminant ({:?} = {:?}): lhs is not an enum",
923                             place,
924                             variant_index
925                         );
926                     }
927                 };
928                 if variant_index >= adt.variants.len() {
929                     span_bug!(
930                         stmt.source_info.span,
931                         "bad set discriminant ({:?} = {:?}): value of of range",
932                         place,
933                         variant_index
934                     );
935                 };
936             }
937             StatementKind::UserAssertTy(c_ty, local) => {
938                 let local_ty = mir.local_decls()[local].ty;
939                 if let Err(terr) = self.eq_canonical_type_and_type(c_ty, local_ty, Locations::All) {
940                     span_mirbug!(
941                         self,
942                         stmt,
943                         "bad type assert ({:?} = {:?}): {:?}",
944                         c_ty,
945                         local_ty,
946                         terr
947                     );
948                 }
949             }
950             StatementKind::ReadForMatch(_)
951             | StatementKind::StorageLive(_)
952             | StatementKind::StorageDead(_)
953             | StatementKind::InlineAsm { .. }
954             | StatementKind::EndRegion(_)
955             | StatementKind::Validate(..)
956             | StatementKind::Nop => {}
957         }
958     }
959
960     fn check_terminator(
961         &mut self,
962         mir: &Mir<'tcx>,
963         term: &Terminator<'tcx>,
964         term_location: Location,
965     ) {
966         debug!("check_terminator: {:?}", term);
967         let tcx = self.tcx();
968         match term.kind {
969             TerminatorKind::Goto { .. }
970             | TerminatorKind::Resume
971             | TerminatorKind::Abort
972             | TerminatorKind::Return
973             | TerminatorKind::GeneratorDrop
974             | TerminatorKind::Unreachable
975             | TerminatorKind::Drop { .. }
976             | TerminatorKind::FalseEdges { .. }
977             | TerminatorKind::FalseUnwind { .. } => {
978                 // no checks needed for these
979             }
980
981             TerminatorKind::DropAndReplace {
982                 ref location,
983                 ref value,
984                 target: _,
985                 unwind: _,
986             } => {
987                 let place_ty = location.ty(mir, tcx).to_ty(tcx);
988                 let rv_ty = value.ty(mir, tcx);
989
990                 let locations = term_location.interesting();
991                 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
992                     span_mirbug!(
993                         self,
994                         term,
995                         "bad DropAndReplace ({:?} = {:?}): {:?}",
996                         place_ty,
997                         rv_ty,
998                         terr
999                     );
1000                 }
1001             }
1002             TerminatorKind::SwitchInt {
1003                 ref discr,
1004                 switch_ty,
1005                 ..
1006             } => {
1007                 let discr_ty = discr.ty(mir, tcx);
1008                 if let Err(terr) = self.sub_types(discr_ty, switch_ty, term_location.boring()) {
1009                     span_mirbug!(
1010                         self,
1011                         term,
1012                         "bad SwitchInt ({:?} on {:?}): {:?}",
1013                         switch_ty,
1014                         discr_ty,
1015                         terr
1016                     );
1017                 }
1018                 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1019                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1020                 }
1021                 // FIXME: check the values
1022             }
1023             TerminatorKind::Call {
1024                 ref func,
1025                 ref args,
1026                 ref destination,
1027                 ..
1028             } => {
1029                 let func_ty = func.ty(mir, tcx);
1030                 debug!("check_terminator: call, func_ty={:?}", func_ty);
1031                 let sig = match func_ty.sty {
1032                     ty::TyFnDef(..) | ty::TyFnPtr(_) => func_ty.fn_sig(tcx),
1033                     _ => {
1034                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1035                         return;
1036                     }
1037                 };
1038                 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
1039                     term.source_info.span,
1040                     LateBoundRegionConversionTime::FnCall,
1041                     &sig,
1042                 );
1043                 let sig = self.normalize(sig, term_location);
1044                 self.check_call_dest(mir, term, &sig, destination, term_location);
1045
1046                 self.prove_predicates(
1047                     sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1048                     term_location.boring(),
1049                 );
1050
1051                 // The ordinary liveness rules will ensure that all
1052                 // regions in the type of the callee are live here. We
1053                 // then further constrain the late-bound regions that
1054                 // were instantiated at the call site to be live as
1055                 // well. The resulting is that all the input (and
1056                 // output) types in the signature must be live, since
1057                 // all the inputs that fed into it were live.
1058                 for &late_bound_region in map.values() {
1059                     if let Some(ref mut borrowck_context) = self.borrowck_context {
1060                         let region_vid = borrowck_context
1061                             .universal_regions
1062                             .to_region_vid(late_bound_region);
1063                         borrowck_context
1064                             .constraints
1065                             .liveness_constraints
1066                             .add_element(region_vid, term_location);
1067                     }
1068                 }
1069
1070                 self.check_call_inputs(mir, term, &sig, args, term_location);
1071             }
1072             TerminatorKind::Assert {
1073                 ref cond, ref msg, ..
1074             } => {
1075                 let cond_ty = cond.ty(mir, tcx);
1076                 if cond_ty != tcx.types.bool {
1077                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1078                 }
1079
1080                 if let BoundsCheck { ref len, ref index } = *msg {
1081                     if len.ty(mir, tcx) != tcx.types.usize {
1082                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1083                     }
1084                     if index.ty(mir, tcx) != tcx.types.usize {
1085                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1086                     }
1087                 }
1088             }
1089             TerminatorKind::Yield { ref value, .. } => {
1090                 let value_ty = value.ty(mir, tcx);
1091                 match mir.yield_ty {
1092                     None => span_mirbug!(self, term, "yield in non-generator"),
1093                     Some(ty) => {
1094                         if let Err(terr) = self.sub_types(value_ty, ty, term_location.interesting())
1095                         {
1096                             span_mirbug!(
1097                                 self,
1098                                 term,
1099                                 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1100                                 value_ty,
1101                                 ty,
1102                                 terr
1103                             );
1104                         }
1105                     }
1106                 }
1107             }
1108         }
1109     }
1110
1111     fn check_call_dest(
1112         &mut self,
1113         mir: &Mir<'tcx>,
1114         term: &Terminator<'tcx>,
1115         sig: &ty::FnSig<'tcx>,
1116         destination: &Option<(Place<'tcx>, BasicBlock)>,
1117         term_location: Location,
1118     ) {
1119         let tcx = self.tcx();
1120         match *destination {
1121             Some((ref dest, _target_block)) => {
1122                 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1123                 let is_temp = if let Place::Local(l) = *dest {
1124                     l != RETURN_PLACE &&
1125                     !mir.local_decls[l].is_user_variable.is_some()
1126                 } else {
1127                     false
1128                 };
1129
1130                 let locations = if is_temp {
1131                     term_location.boring()
1132                 } else {
1133                     term_location.interesting()
1134                 };
1135
1136                 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations) {
1137                     span_mirbug!(
1138                         self,
1139                         term,
1140                         "call dest mismatch ({:?} <- {:?}): {:?}",
1141                         dest_ty,
1142                         sig.output(),
1143                         terr
1144                     );
1145                 }
1146             }
1147             None => {
1148                 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1149                 if !sig.output().is_never() {
1150                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1151                 }
1152             }
1153         }
1154     }
1155
1156     fn check_call_inputs(
1157         &mut self,
1158         mir: &Mir<'tcx>,
1159         term: &Terminator<'tcx>,
1160         sig: &ty::FnSig<'tcx>,
1161         args: &[Operand<'tcx>],
1162         term_location: Location,
1163     ) {
1164         debug!("check_call_inputs({:?}, {:?})", sig, args);
1165         if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1166             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1167         }
1168         for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1169             let op_arg_ty = op_arg.ty(mir, self.tcx());
1170             if let Err(terr) = self.sub_types(op_arg_ty, fn_arg, term_location.interesting()) {
1171                 span_mirbug!(
1172                     self,
1173                     term,
1174                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1175                     n,
1176                     fn_arg,
1177                     op_arg_ty,
1178                     terr
1179                 );
1180             }
1181         }
1182     }
1183
1184     fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1185         let is_cleanup = block_data.is_cleanup;
1186         self.last_span = block_data.terminator().source_info.span;
1187         match block_data.terminator().kind {
1188             TerminatorKind::Goto { target } => {
1189                 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1190             }
1191             TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1192                 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1193             },
1194             TerminatorKind::Resume => if !is_cleanup {
1195                 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1196             },
1197             TerminatorKind::Abort => if !is_cleanup {
1198                 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1199             },
1200             TerminatorKind::Return => if is_cleanup {
1201                 span_mirbug!(self, block_data, "return on cleanup block")
1202             },
1203             TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1204                 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1205             },
1206             TerminatorKind::Yield { resume, drop, .. } => {
1207                 if is_cleanup {
1208                     span_mirbug!(self, block_data, "yield in cleanup block")
1209                 }
1210                 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1211                 if let Some(drop) = drop {
1212                     self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1213                 }
1214             }
1215             TerminatorKind::Unreachable => {}
1216             TerminatorKind::Drop { target, unwind, .. }
1217             | TerminatorKind::DropAndReplace { target, unwind, .. }
1218             | TerminatorKind::Assert {
1219                 target,
1220                 cleanup: unwind,
1221                 ..
1222             } => {
1223                 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1224                 if let Some(unwind) = unwind {
1225                     if is_cleanup {
1226                         span_mirbug!(self, block_data, "unwind on cleanup block")
1227                     }
1228                     self.assert_iscleanup(mir, block_data, unwind, true);
1229                 }
1230             }
1231             TerminatorKind::Call {
1232                 ref destination,
1233                 cleanup,
1234                 ..
1235             } => {
1236                 if let &Some((_, target)) = destination {
1237                     self.assert_iscleanup(mir, block_data, target, is_cleanup);
1238                 }
1239                 if let Some(cleanup) = cleanup {
1240                     if is_cleanup {
1241                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1242                     }
1243                     self.assert_iscleanup(mir, block_data, cleanup, true);
1244                 }
1245             }
1246             TerminatorKind::FalseEdges {
1247                 real_target,
1248                 ref imaginary_targets,
1249             } => {
1250                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1251                 for target in imaginary_targets {
1252                     self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1253                 }
1254             }
1255             TerminatorKind::FalseUnwind {
1256                 real_target,
1257                 unwind,
1258             } => {
1259                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1260                 if let Some(unwind) = unwind {
1261                     if is_cleanup {
1262                         span_mirbug!(
1263                             self,
1264                             block_data,
1265                             "cleanup in cleanup block via false unwind"
1266                         );
1267                     }
1268                     self.assert_iscleanup(mir, block_data, unwind, true);
1269                 }
1270             }
1271         }
1272     }
1273
1274     fn assert_iscleanup(
1275         &mut self,
1276         mir: &Mir<'tcx>,
1277         ctxt: &dyn fmt::Debug,
1278         bb: BasicBlock,
1279         iscleanuppad: bool,
1280     ) {
1281         if mir[bb].is_cleanup != iscleanuppad {
1282             span_mirbug!(
1283                 self,
1284                 ctxt,
1285                 "cleanuppad mismatch: {:?} should be {:?}",
1286                 bb,
1287                 iscleanuppad
1288             );
1289         }
1290     }
1291
1292     fn check_local(
1293         &mut self,
1294         mir: &Mir<'tcx>,
1295         local: Local,
1296         local_decl: &LocalDecl<'tcx>,
1297         errors_buffer: &mut Option<&mut Vec<Diagnostic>>,
1298     ) {
1299         match mir.local_kind(local) {
1300             LocalKind::ReturnPointer | LocalKind::Arg => {
1301                 // return values of normal functions are required to be
1302                 // sized by typeck, but return values of ADT constructors are
1303                 // not because we don't include a `Self: Sized` bounds on them.
1304                 //
1305                 // Unbound parts of arguments were never required to be Sized
1306                 // - maybe we should make that a warning.
1307                 return;
1308             }
1309             LocalKind::Var | LocalKind::Temp => {}
1310         }
1311
1312         let span = local_decl.source_info.span;
1313         let ty = local_decl.ty;
1314
1315         // Erase the regions from `ty` to get a global type.  The
1316         // `Sized` bound in no way depends on precise regions, so this
1317         // shouldn't affect `is_sized`.
1318         let gcx = self.tcx().global_tcx();
1319         let erased_ty = gcx.lift(&self.tcx().erase_regions(&ty)).unwrap();
1320         if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1321             // in current MIR construction, all non-control-flow rvalue
1322             // expressions evaluate through `as_temp` or `into` a return
1323             // slot or local, so to find all unsized rvalues it is enough
1324             // to check all temps, return slots and locals.
1325             if let None = self.reported_errors.replace((ty, span)) {
1326                 let mut diag = struct_span_err!(
1327                     self.tcx().sess,
1328                     span,
1329                     E0161,
1330                     "cannot move a value of type {0}: the size of {0} \
1331                      cannot be statically determined",
1332                     ty
1333                 );
1334                 if let Some(ref mut errors_buffer) = *errors_buffer {
1335                     diag.buffer(errors_buffer);
1336                 } else {
1337                     // we're allowed to use emit() here because the
1338                     // NLL migration will be turned on (and thus
1339                     // errors will need to be buffered) *only if*
1340                     // errors_buffer is Some.
1341                     diag.emit();
1342                 }
1343             }
1344         }
1345     }
1346
1347     fn aggregate_field_ty(
1348         &mut self,
1349         ak: &AggregateKind<'tcx>,
1350         field_index: usize,
1351         location: Location,
1352     ) -> Result<Ty<'tcx>, FieldAccessError> {
1353         let tcx = self.tcx();
1354
1355         match *ak {
1356             AggregateKind::Adt(def, variant_index, substs, active_field_index) => {
1357                 let variant = &def.variants[variant_index];
1358                 let adj_field_index = active_field_index.unwrap_or(field_index);
1359                 if let Some(field) = variant.fields.get(adj_field_index) {
1360                     Ok(self.normalize(field.ty(tcx, substs), location))
1361                 } else {
1362                     Err(FieldAccessError::OutOfRange {
1363                         field_count: variant.fields.len(),
1364                     })
1365                 }
1366             }
1367             AggregateKind::Closure(def_id, substs) => {
1368                 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1369                     Some(ty) => Ok(ty),
1370                     None => Err(FieldAccessError::OutOfRange {
1371                         field_count: substs.upvar_tys(def_id, tcx).count(),
1372                     }),
1373                 }
1374             }
1375             AggregateKind::Generator(def_id, substs, _) => {
1376                 // Try pre-transform fields first (upvars and current state)
1377                 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1378                     Ok(ty)
1379                 } else {
1380                     // Then try `field_tys` which contains all the fields, but it
1381                     // requires the final optimized MIR.
1382                     match substs.field_tys(def_id, tcx).nth(field_index) {
1383                         Some(ty) => Ok(ty),
1384                         None => Err(FieldAccessError::OutOfRange {
1385                             field_count: substs.field_tys(def_id, tcx).count(),
1386                         }),
1387                     }
1388                 }
1389             }
1390             AggregateKind::Array(ty) => Ok(ty),
1391             AggregateKind::Tuple => {
1392                 unreachable!("This should have been covered in check_rvalues");
1393             }
1394         }
1395     }
1396
1397     fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1398         let tcx = self.tcx();
1399
1400         match rvalue {
1401             Rvalue::Aggregate(ak, ops) => {
1402                 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1403             }
1404
1405             Rvalue::Repeat(operand, len) => if *len > 1 {
1406                 let operand_ty = operand.ty(mir, tcx);
1407
1408                 let trait_ref = ty::TraitRef {
1409                     def_id: tcx.lang_items().copy_trait().unwrap(),
1410                     substs: tcx.mk_substs_trait(operand_ty, &[]),
1411                 };
1412
1413                 self.prove_trait_ref(trait_ref, location.interesting());
1414             },
1415
1416             Rvalue::NullaryOp(_, ty) => {
1417                 let trait_ref = ty::TraitRef {
1418                     def_id: tcx.lang_items().sized_trait().unwrap(),
1419                     substs: tcx.mk_substs_trait(ty, &[]),
1420                 };
1421
1422                 self.prove_trait_ref(trait_ref, location.interesting());
1423             }
1424
1425             Rvalue::Cast(cast_kind, op, ty) => match cast_kind {
1426                 CastKind::ReifyFnPointer => {
1427                     let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1428
1429                     // The type that we see in the fcx is like
1430                     // `foo::<'a, 'b>`, where `foo` is the path to a
1431                     // function definition. When we extract the
1432                     // signature, it comes from the `fn_sig` query,
1433                     // and hence may contain unnormalized results.
1434                     let fn_sig = self.normalize(fn_sig, location);
1435
1436                     let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1437
1438                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1439                         span_mirbug!(
1440                             self,
1441                             rvalue,
1442                             "equating {:?} with {:?} yields {:?}",
1443                             ty_fn_ptr_from,
1444                             ty,
1445                             terr
1446                         );
1447                     }
1448                 }
1449
1450                 CastKind::ClosureFnPointer => {
1451                     let sig = match op.ty(mir, tcx).sty {
1452                         ty::TyClosure(def_id, substs) => {
1453                             substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1454                         }
1455                         _ => bug!(),
1456                     };
1457                     let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1458
1459                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1460                         span_mirbug!(
1461                             self,
1462                             rvalue,
1463                             "equating {:?} with {:?} yields {:?}",
1464                             ty_fn_ptr_from,
1465                             ty,
1466                             terr
1467                         );
1468                     }
1469                 }
1470
1471                 CastKind::UnsafeFnPointer => {
1472                     let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1473
1474                     // The type that we see in the fcx is like
1475                     // `foo::<'a, 'b>`, where `foo` is the path to a
1476                     // function definition. When we extract the
1477                     // signature, it comes from the `fn_sig` query,
1478                     // and hence may contain unnormalized results.
1479                     let fn_sig = self.normalize(fn_sig, location);
1480
1481                     let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1482
1483                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1484                         span_mirbug!(
1485                             self,
1486                             rvalue,
1487                             "equating {:?} with {:?} yields {:?}",
1488                             ty_fn_ptr_from,
1489                             ty,
1490                             terr
1491                         );
1492                     }
1493                 }
1494
1495                 CastKind::Unsize => {
1496                     let &ty = ty;
1497                     let trait_ref = ty::TraitRef {
1498                         def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1499                         substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1500                     };
1501
1502                     self.prove_trait_ref(trait_ref, location.interesting());
1503                 }
1504
1505                 CastKind::Misc => {}
1506             },
1507
1508             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1509                 self.add_reborrow_constraint(location, region, borrowed_place);
1510             }
1511
1512             // FIXME: These other cases have to be implemented in future PRs
1513             Rvalue::Use(..)
1514             | Rvalue::Len(..)
1515             | Rvalue::BinaryOp(..)
1516             | Rvalue::CheckedBinaryOp(..)
1517             | Rvalue::UnaryOp(..)
1518             | Rvalue::Discriminant(..) => {}
1519         }
1520     }
1521
1522     fn check_aggregate_rvalue(
1523         &mut self,
1524         mir: &Mir<'tcx>,
1525         rvalue: &Rvalue<'tcx>,
1526         aggregate_kind: &AggregateKind<'tcx>,
1527         operands: &[Operand<'tcx>],
1528         location: Location,
1529     ) {
1530         let tcx = self.tcx();
1531
1532         self.prove_aggregate_predicates(aggregate_kind, location);
1533
1534         if *aggregate_kind == AggregateKind::Tuple {
1535             // tuple rvalue field type is always the type of the op. Nothing to check here.
1536             return;
1537         }
1538
1539         for (i, operand) in operands.iter().enumerate() {
1540             let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
1541                 Ok(field_ty) => field_ty,
1542                 Err(FieldAccessError::OutOfRange { field_count }) => {
1543                     span_mirbug!(
1544                         self,
1545                         rvalue,
1546                         "accessed field #{} but variant only has {}",
1547                         i,
1548                         field_count
1549                     );
1550                     continue;
1551                 }
1552             };
1553             let operand_ty = operand.ty(mir, tcx);
1554
1555             if let Err(terr) = self.sub_types(operand_ty, field_ty, location.boring()) {
1556                 span_mirbug!(
1557                     self,
1558                     rvalue,
1559                     "{:?} is not a subtype of {:?}: {:?}",
1560                     operand_ty,
1561                     field_ty,
1562                     terr
1563                 );
1564             }
1565         }
1566     }
1567
1568     /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
1569     ///
1570     /// # Parameters
1571     ///
1572     /// - `location`: the location `L` where the borrow expression occurs
1573     /// - `borrow_region`: the region `'a` associated with the borrow
1574     /// - `borrowed_place`: the place `P` being borrowed
1575     fn add_reborrow_constraint(
1576         &mut self,
1577         location: Location,
1578         borrow_region: ty::Region<'tcx>,
1579         borrowed_place: &Place<'tcx>,
1580     ) {
1581         // These constraints are only meaningful during borrowck:
1582         let BorrowCheckContext {
1583             borrow_set,
1584             location_table,
1585             all_facts,
1586             constraints,
1587             ..
1588         } = match self.borrowck_context {
1589             Some(ref mut borrowck_context) => borrowck_context,
1590             None => return,
1591         };
1592
1593         // In Polonius mode, we also push a `borrow_region` fact
1594         // linking the loan to the region (in some cases, though,
1595         // there is no loan associated with this borrow expression --
1596         // that occurs when we are borrowing an unsafe place, for
1597         // example).
1598         if let Some(all_facts) = all_facts {
1599             if let Some(borrow_index) = borrow_set.location_map.get(&location) {
1600                 let region_vid = borrow_region.to_region_vid();
1601                 all_facts.borrow_region.push((
1602                     region_vid,
1603                     *borrow_index,
1604                     location_table.mid_index(location),
1605                 ));
1606             }
1607         }
1608
1609         // If we are reborrowing the referent of another reference, we
1610         // need to add outlives relationships. In a case like `&mut
1611         // *p`, where the `p` has type `&'b mut Foo`, for example, we
1612         // need to ensure that `'b: 'a`.
1613
1614         let mut borrowed_place = borrowed_place;
1615
1616         debug!(
1617             "add_reborrow_constraint({:?}, {:?}, {:?})",
1618             location, borrow_region, borrowed_place
1619         );
1620         while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
1621             debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
1622
1623             match *elem {
1624                 ProjectionElem::Deref => {
1625                     let tcx = self.infcx.tcx;
1626                     let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1627
1628                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
1629                     match base_ty.sty {
1630                         ty::TyRef(ref_region, _, mutbl) => {
1631                             constraints.outlives_constraints.push(OutlivesConstraint {
1632                                 sup: ref_region.to_region_vid(),
1633                                 sub: borrow_region.to_region_vid(),
1634                                 locations: location.boring(),
1635                             });
1636
1637                             if let Some(all_facts) = all_facts {
1638                                 all_facts.outlives.push((
1639                                     ref_region.to_region_vid(),
1640                                     borrow_region.to_region_vid(),
1641                                     location_table.mid_index(location),
1642                                 ));
1643                             }
1644
1645                             match mutbl {
1646                                 hir::Mutability::MutImmutable => {
1647                                     // Immutable reference. We don't need the base
1648                                     // to be valid for the entire lifetime of
1649                                     // the borrow.
1650                                     break;
1651                                 }
1652                                 hir::Mutability::MutMutable => {
1653                                     // Mutable reference. We *do* need the base
1654                                     // to be valid, because after the base becomes
1655                                     // invalid, someone else can use our mutable deref.
1656
1657                                     // This is in order to make the following function
1658                                     // illegal:
1659                                     // ```
1660                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
1661                                     //     &mut *x
1662                                     // }
1663                                     // ```
1664                                     //
1665                                     // As otherwise you could clone `&mut T` using the
1666                                     // following function:
1667                                     // ```
1668                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
1669                                     //     let my_clone = unsafe_deref(&'a x);
1670                                     //     ENDREGION 'a;
1671                                     //     (my_clone, x)
1672                                     // }
1673                                     // ```
1674                                 }
1675                             }
1676                         }
1677                         ty::TyRawPtr(..) => {
1678                             // deref of raw pointer, guaranteed to be valid
1679                             break;
1680                         }
1681                         ty::TyAdt(def, _) if def.is_box() => {
1682                             // deref of `Box`, need the base to be valid - propagate
1683                         }
1684                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
1685                     }
1686                 }
1687                 ProjectionElem::Field(..)
1688                 | ProjectionElem::Downcast(..)
1689                 | ProjectionElem::Index(..)
1690                 | ProjectionElem::ConstantIndex { .. }
1691                 | ProjectionElem::Subslice { .. } => {
1692                     // other field access
1693                 }
1694             }
1695
1696             // The "propagate" case. We need to check that our base is valid
1697             // for the borrow's lifetime.
1698             borrowed_place = base;
1699         }
1700     }
1701
1702     fn prove_aggregate_predicates(
1703         &mut self,
1704         aggregate_kind: &AggregateKind<'tcx>,
1705         location: Location,
1706     ) {
1707         let tcx = self.tcx();
1708
1709         debug!(
1710             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
1711             aggregate_kind, location
1712         );
1713
1714         let instantiated_predicates = match aggregate_kind {
1715             AggregateKind::Adt(def, _, substs, _) => {
1716                 tcx.predicates_of(def.did).instantiate(tcx, substs)
1717             }
1718
1719             // For closures, we have some **extra requirements** we
1720             //
1721             // have to check. In particular, in their upvars and
1722             // signatures, closures often reference various regions
1723             // from the surrounding function -- we call those the
1724             // closure's free regions. When we borrow-check (and hence
1725             // region-check) closures, we may find that the closure
1726             // requires certain relationships between those free
1727             // regions. However, because those free regions refer to
1728             // portions of the CFG of their caller, the closure is not
1729             // in a position to verify those relationships. In that
1730             // case, the requirements get "propagated" to us, and so
1731             // we have to solve them here where we instantiate the
1732             // closure.
1733             //
1734             // Despite the opacity of the previous parapgrah, this is
1735             // actually relatively easy to understand in terms of the
1736             // desugaring. A closure gets desugared to a struct, and
1737             // these extra requirements are basically like where
1738             // clauses on the struct.
1739             AggregateKind::Closure(def_id, substs) => {
1740                 if let Some(closure_region_requirements) =
1741                     tcx.mir_borrowck(*def_id).closure_requirements
1742                 {
1743                     let closure_constraints = closure_region_requirements.apply_requirements(
1744                         self.infcx.tcx,
1745                         location,
1746                         *def_id,
1747                         *substs,
1748                     );
1749
1750                     // Hmm, are these constraints *really* boring?
1751                     self.push_region_constraints(location.boring(), &closure_constraints);
1752                 }
1753
1754                 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1755             }
1756
1757             AggregateKind::Generator(def_id, substs, _) => {
1758                 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1759             }
1760
1761             AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
1762         };
1763
1764         self.normalize_and_prove_instantiated_predicates(
1765             instantiated_predicates,
1766             location.boring(),
1767         );
1768     }
1769
1770     fn prove_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>, locations: Locations) {
1771         self.prove_predicates(
1772             Some(ty::Predicate::Trait(
1773                 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
1774             )),
1775             locations,
1776         );
1777     }
1778
1779     fn normalize_and_prove_instantiated_predicates(
1780         &mut self,
1781         instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
1782         locations: Locations,
1783     ) {
1784         for predicate in instantiated_predicates.predicates {
1785             let predicate = self.normalize(predicate, locations);
1786             self.prove_predicate(predicate, locations);
1787         }
1788     }
1789
1790     fn prove_predicates(
1791         &mut self,
1792         predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
1793         locations: Locations,
1794     ) {
1795         for predicate in predicates {
1796             debug!(
1797                 "prove_predicates(predicate={:?}, locations={:?})",
1798                 predicate, locations,
1799             );
1800
1801             self.prove_predicate(predicate, locations);
1802         }
1803     }
1804
1805     fn prove_predicate(&mut self, predicate: ty::Predicate<'tcx>, locations: Locations) {
1806         debug!(
1807             "prove_predicate(predicate={:?}, location={:?})",
1808             predicate, locations,
1809         );
1810
1811         let param_env = self.param_env;
1812         self.fully_perform_op(
1813             locations,
1814             param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
1815         ).unwrap_or_else(|NoSolution| {
1816             span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
1817         })
1818     }
1819
1820     fn typeck_mir(&mut self, mir: &Mir<'tcx>, mut errors_buffer: Option<&mut Vec<Diagnostic>>) {
1821         self.last_span = mir.span;
1822         debug!("run_on_mir: {:?}", mir.span);
1823
1824         for (local, local_decl) in mir.local_decls.iter_enumerated() {
1825             self.check_local(mir, local, local_decl, &mut errors_buffer);
1826         }
1827
1828         for (block, block_data) in mir.basic_blocks().iter_enumerated() {
1829             let mut location = Location {
1830                 block,
1831                 statement_index: 0,
1832             };
1833             for stmt in &block_data.statements {
1834                 if !stmt.source_info.span.is_dummy() {
1835                     self.last_span = stmt.source_info.span;
1836                 }
1837                 self.check_stmt(mir, stmt, location);
1838                 location.statement_index += 1;
1839             }
1840
1841             self.check_terminator(mir, block_data.terminator(), location);
1842             self.check_iscleanup(mir, block_data);
1843         }
1844     }
1845
1846     fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
1847     where
1848         T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
1849     {
1850         debug!("normalize(value={:?}, location={:?})", value, location);
1851         let param_env = self.param_env;
1852         self.fully_perform_op(
1853             location.to_locations(),
1854             param_env.and(type_op::normalize::Normalize::new(value)),
1855         ).unwrap_or_else(|NoSolution| {
1856             span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
1857             value
1858         })
1859     }
1860 }
1861
1862 pub struct TypeckMir;
1863
1864 impl MirPass for TypeckMir {
1865     fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
1866         let def_id = src.def_id;
1867         debug!("run_pass: {:?}", def_id);
1868
1869         // When NLL is enabled, the borrow checker runs the typeck
1870         // itself, so we don't need this MIR pass anymore.
1871         if tcx.use_mir_borrowck() {
1872             return;
1873         }
1874
1875         if tcx.sess.err_count() > 0 {
1876             // compiling a broken program can obviously result in a
1877             // broken MIR, so try not to report duplicate errors.
1878             return;
1879         }
1880
1881         if tcx.is_struct_constructor(def_id) {
1882             // We just assume that the automatically generated struct constructors are
1883             // correct. See the comment in the `mir_borrowck` implementation for an
1884             // explanation why we need this.
1885             return;
1886         }
1887
1888         let param_env = tcx.param_env(def_id);
1889         tcx.infer_ctxt().enter(|infcx| {
1890             type_check_internal(
1891                 &infcx,
1892                 def_id,
1893                 param_env,
1894                 mir,
1895                 &[],
1896                 None,
1897                 None,
1898                 None,
1899                 |_| (),
1900             );
1901
1902             // For verification purposes, we just ignore the resulting
1903             // region constraint sets. Not our problem. =)
1904         });
1905     }
1906 }
1907
1908 pub trait AtLocation {
1909     /// Indicates a "boring" constraint that the user probably
1910     /// woudln't want to see highlights.
1911     fn boring(self) -> Locations;
1912
1913     /// Indicates an "interesting" edge, which is of significance only
1914     /// for diagnostics.
1915     fn interesting(self) -> Locations;
1916 }
1917
1918 impl AtLocation for Location {
1919     fn boring(self) -> Locations {
1920         Locations::Boring(self)
1921     }
1922
1923     fn interesting(self) -> Locations {
1924         Locations::Interesting(self)
1925     }
1926 }
1927
1928 trait NormalizeLocation: fmt::Debug + Copy {
1929     fn to_locations(self) -> Locations;
1930 }
1931
1932 impl NormalizeLocation for Locations {
1933     fn to_locations(self) -> Locations {
1934         self
1935     }
1936 }
1937
1938 impl NormalizeLocation for Location {
1939     fn to_locations(self) -> Locations {
1940         self.boring()
1941     }
1942 }