]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/type_check/mod.rs
Auto merge of #52911 - Mark-Simulacrum:visibility-hirid, r=oli-obk
[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::universal_regions::UniversalRegions;
22 use borrow_check::nll::LocalWithRegion;
23 use borrow_check::nll::ToRegionVid;
24 use dataflow::move_paths::MoveData;
25 use dataflow::FlowAtLocation;
26 use dataflow::MaybeInitializedPlaces;
27 use rustc::hir;
28 use rustc::hir::def_id::DefId;
29 use rustc::infer::canonical::QueryRegionConstraint;
30 use rustc::infer::region_constraints::GenericKind;
31 use rustc::infer::{InferCtxt, LateBoundRegionConversionTime};
32 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
33 use rustc::mir::tcx::PlaceTy;
34 use rustc::mir::visit::{PlaceContext, Visitor};
35 use rustc::mir::*;
36 use rustc::traits::query::type_op;
37 use rustc::traits::query::{Fallible, NoSolution};
38 use rustc::ty::fold::TypeFoldable;
39 use rustc::ty::{self, CanonicalTy, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TypeVariants};
40 use rustc_errors::Diagnostic;
41 use std::fmt;
42 use std::rc::Rc;
43 use syntax_pos::{Span, DUMMY_SP};
44 use transform::{MirPass, MirSource};
45 use util::liveness::LivenessResults;
46
47 use rustc_data_structures::fx::FxHashSet;
48 use rustc_data_structures::indexed_vec::Idx;
49
50 macro_rules! span_mirbug {
51     ($context:expr, $elem:expr, $($message:tt)*) => ({
52         $crate::borrow_check::nll::type_check::mirbug(
53             $context.tcx(),
54             $context.last_span,
55             &format!(
56                 "broken MIR in {:?} ({:?}): {}",
57                 $context.mir_def_id,
58                 $elem,
59                 format_args!($($message)*),
60             ),
61         )
62     })
63 }
64
65 macro_rules! span_mirbug_and_err {
66     ($context:expr, $elem:expr, $($message:tt)*) => ({
67         {
68             span_mirbug!($context, $elem, $($message)*);
69             $context.error()
70         }
71     })
72 }
73
74 mod constraint_conversion;
75 pub mod free_region_relations;
76 mod input_output;
77 mod liveness;
78 mod relate_tys;
79
80 /// Type checks the given `mir` in the context of the inference
81 /// context `infcx`. Returns any region constraints that have yet to
82 /// be proven. This result is includes liveness constraints that
83 /// ensure that regions appearing in the types of all local variables
84 /// are live at all points where that local variable may later be
85 /// used.
86 ///
87 /// This phase of type-check ought to be infallible -- this is because
88 /// the original, HIR-based type-check succeeded. So if any errors
89 /// occur here, we will get a `bug!` reported.
90 ///
91 /// # Parameters
92 ///
93 /// - `infcx` -- inference context to use
94 /// - `param_env` -- parameter environment to use for trait solving
95 /// - `mir` -- MIR to type-check
96 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
97 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
98 ///   and lifetimes (e.g., `&'a T` implies `T: 'a`)
99 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
100 ///   to outlive; should represent the fn body
101 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
102 ///   the types of the input parameters found in the MIR itself will be equated with these
103 /// - `output_ty` -- fully liberaetd, but **not** normalized, expected return type;
104 ///   the type for the RETURN_PLACE will be equated with this
105 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
106 ///   constraints for the regions in the types of variables
107 /// - `flow_inits` -- results of a maybe-init dataflow analysis
108 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
109 /// - `errors_buffer` -- errors are sent here for future reporting
110 pub(crate) fn type_check<'gcx, 'tcx>(
111     infcx: &InferCtxt<'_, 'gcx, 'tcx>,
112     param_env: ty::ParamEnv<'gcx>,
113     mir: &Mir<'tcx>,
114     mir_def_id: DefId,
115     universal_regions: &Rc<UniversalRegions<'tcx>>,
116     location_table: &LocationTable,
117     borrow_set: &BorrowSet<'tcx>,
118     liveness: &LivenessResults<LocalWithRegion>,
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 ) -> (
125     MirTypeckRegionConstraints<'tcx>,
126     Rc<UniversalRegionRelations<'tcx>>,
127 ) {
128     let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
129     let mut constraints = MirTypeckRegionConstraints {
130         liveness_constraints: LivenessValues::new(elements),
131         outlives_constraints: ConstraintSet::default(),
132         type_tests: Vec::default(),
133     };
134
135     let CreateResult {
136         universal_region_relations,
137         region_bound_pairs,
138         normalized_inputs_and_output,
139     } = free_region_relations::create(
140         infcx,
141         mir_def_id,
142         param_env,
143         location_table,
144         Some(implicit_region_bound),
145         universal_regions,
146         &mut constraints,
147         all_facts,
148     );
149
150     {
151         let mut borrowck_context = BorrowCheckContext {
152             universal_regions,
153             location_table,
154             borrow_set,
155             all_facts,
156             constraints: &mut constraints,
157         };
158
159         type_check_internal(
160             infcx,
161             mir_def_id,
162             param_env,
163             mir,
164             &region_bound_pairs,
165             Some(implicit_region_bound),
166             Some(&mut borrowck_context),
167             Some(errors_buffer),
168             |cx| {
169                 liveness::generate(cx, mir, liveness, flow_inits, move_data);
170                 cx.equate_inputs_and_outputs(
171                     mir,
172                     mir_def_id,
173                     universal_regions,
174                     &universal_region_relations,
175                     &normalized_inputs_and_output,
176                 );
177             },
178         );
179     }
180
181     (constraints, universal_region_relations)
182 }
183
184 fn type_check_internal<'a, 'gcx, 'tcx, F>(
185     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
186     mir_def_id: DefId,
187     param_env: ty::ParamEnv<'gcx>,
188     mir: &'a Mir<'tcx>,
189     region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
190     implicit_region_bound: Option<ty::Region<'tcx>>,
191     borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
192     errors_buffer: Option<&mut Vec<Diagnostic>>,
193     mut extra: F,
194 ) where
195     F: FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>),
196 {
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 /// A collection of region constraints that must be satisfied for the
659 /// program to be considered well-typed.
660 crate struct MirTypeckRegionConstraints<'tcx> {
661     /// In general, the type-checker is not responsible for enforcing
662     /// liveness constraints; this job falls to the region inferencer,
663     /// which performs a liveness analysis. However, in some limited
664     /// cases, the MIR type-checker creates temporary regions that do
665     /// not otherwise appear in the MIR -- in particular, the
666     /// late-bound regions that it instantiates at call-sites -- and
667     /// hence it must report on their liveness constraints.
668     crate liveness_constraints: LivenessValues<RegionVid>,
669
670     crate outlives_constraints: ConstraintSet,
671
672     crate type_tests: Vec<TypeTest<'tcx>>,
673 }
674
675 /// The `Locations` type summarizes *where* region constraints are
676 /// required to hold. Normally, this is at a particular point which
677 /// created the obligation, but for constraints that the user gave, we
678 /// want the constraint to hold at all points.
679 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
680 pub enum Locations {
681     /// Indicates that a type constraint should always be true. This
682     /// is particularly important in the new borrowck analysis for
683     /// things like the type of the return slot. Consider this
684     /// example:
685     ///
686     /// ```
687     /// fn foo<'a>(x: &'a u32) -> &'a u32 {
688     ///     let y = 22;
689     ///     return &y; // error
690     /// }
691     /// ```
692     ///
693     /// Here, we wind up with the signature from the return type being
694     /// something like `&'1 u32` where `'1` is a universal region. But
695     /// the type of the return slot `_0` is something like `&'2 u32`
696     /// where `'2` is an existential region variable. The type checker
697     /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
698     /// older NLL analysis, we required this only at the entry point
699     /// to the function. By the nature of the constraints, this wound
700     /// up propagating to all points reachable from start (because
701     /// `'1` -- as a universal region -- is live everywhere).  In the
702     /// newer analysis, though, this doesn't work: `_0` is considered
703     /// dead at the start (it has no usable value) and hence this type
704     /// equality is basically a no-op. Then, later on, when we do `_0
705     /// = &'3 y`, that region `'3` never winds up related to the
706     /// universal region `'1` and hence no error occurs. Therefore, we
707     /// use Locations::All instead, which ensures that the `'1` and
708     /// `'2` are equal everything. We also use this for other
709     /// user-given type annotations; e.g., if the user wrote `let mut
710     /// x: &'static u32 = ...`, we would ensure that all values
711     /// assigned to `x` are of `'static` lifetime.
712     All,
713
714     /// A "boring" constraint (caused by the given location) is one that
715     /// the user probably doesn't want to see described in diagnostics,
716     /// because it is kind of an artifact of the type system setup.
717     ///
718     /// Example: `x = Foo { field: y }` technically creates
719     /// intermediate regions representing the "type of `Foo { field: y
720     /// }`", and data flows from `y` into those variables, but they
721     /// are not very interesting. The assignment into `x` on the other
722     /// hand might be.
723     Boring(Location),
724
725     /// An *important* outlives constraint (caused by the given
726     /// location) is one that would be useful to highlight in
727     /// diagnostics, because it represents a point where references
728     /// flow from one spot to another (e.g., `x = y`)
729     Interesting(Location),
730 }
731
732 impl Locations {
733     pub fn from_location(&self) -> Option<Location> {
734         match self {
735             Locations::All => None,
736             Locations::Boring(from_location) | Locations::Interesting(from_location) => {
737                 Some(*from_location)
738             }
739         }
740     }
741
742     /// Gets a span representing the location.
743     pub fn span(&self, mir: &Mir<'_>) -> Span {
744         let span_location = match self {
745             Locations::All => Location::START,
746             Locations::Boring(l) | Locations::Interesting(l) => *l,
747         };
748         mir.source_info(span_location).span
749     }
750 }
751
752 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
753     fn new(
754         infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
755         mir: &'a Mir<'tcx>,
756         mir_def_id: DefId,
757         param_env: ty::ParamEnv<'gcx>,
758         region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
759         implicit_region_bound: Option<ty::Region<'tcx>>,
760         borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
761     ) -> Self {
762         TypeChecker {
763             infcx,
764             last_span: DUMMY_SP,
765             mir,
766             mir_def_id,
767             param_env,
768             region_bound_pairs,
769             implicit_region_bound,
770             borrowck_context,
771             reported_errors: FxHashSet(),
772         }
773     }
774
775     /// Given some operation `op` that manipulates types, proves
776     /// predicates, or otherwise uses the inference context, executes
777     /// `op` and then executes all the further obligations that `op`
778     /// returns. This will yield a set of outlives constraints amongst
779     /// regions which are extracted and stored as having occured at
780     /// `locations`.
781     ///
782     /// **Any `rustc::infer` operations that might generate region
783     /// constraints should occur within this method so that those
784     /// constraints can be properly localized!**
785     fn fully_perform_op<R>(
786         &mut self,
787         locations: Locations,
788         op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
789     ) -> Fallible<R> {
790         let (r, opt_data) = op.fully_perform(self.infcx)?;
791
792         if let Some(data) = &opt_data {
793             self.push_region_constraints(locations, data);
794         }
795
796         Ok(r)
797     }
798
799     fn push_region_constraints(
800         &mut self,
801         locations: Locations,
802         data: &[QueryRegionConstraint<'tcx>],
803     ) {
804         debug!(
805             "push_region_constraints: constraints generated at {:?} are {:#?}",
806             locations, data
807         );
808
809         if let Some(ref mut borrowck_context) = self.borrowck_context {
810             constraint_conversion::ConstraintConversion::new(
811                 self.infcx.tcx,
812                 borrowck_context.universal_regions,
813                 borrowck_context.location_table,
814                 self.region_bound_pairs,
815                 self.implicit_region_bound,
816                 self.param_env,
817                 locations,
818                 &mut borrowck_context.constraints.outlives_constraints,
819                 &mut borrowck_context.constraints.type_tests,
820                 &mut borrowck_context.all_facts,
821             ).convert_all(&data);
822         }
823     }
824
825     fn sub_types(&mut self, sub: Ty<'tcx>, sup: Ty<'tcx>, locations: Locations) -> Fallible<()> {
826         relate_tys::sub_types(
827             self.infcx,
828             sub,
829             sup,
830             locations,
831             self.borrowck_context.as_mut().map(|x| &mut **x),
832         )
833     }
834
835     fn eq_types(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, locations: Locations) -> Fallible<()> {
836         relate_tys::eq_types(
837             self.infcx,
838             a,
839             b,
840             locations,
841             self.borrowck_context.as_mut().map(|x| &mut **x),
842         )
843     }
844
845     fn eq_canonical_type_and_type(
846         &mut self,
847         a: CanonicalTy<'tcx>,
848         b: Ty<'tcx>,
849         locations: Locations,
850     ) -> Fallible<()> {
851         relate_tys::eq_canonical_type_and_type(
852             self.infcx,
853             a,
854             b,
855             locations,
856             self.borrowck_context.as_mut().map(|x| &mut **x),
857         )
858     }
859
860     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
861         self.infcx.tcx
862     }
863
864     fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
865         debug!("check_stmt: {:?}", stmt);
866         let tcx = self.tcx();
867         match stmt.kind {
868             StatementKind::Assign(ref place, ref rv) => {
869                 // Assignments to temporaries are not "interesting";
870                 // they are not caused by the user, but rather artifacts
871                 // of lowering. Assignments to other sorts of places *are* interesting
872                 // though.
873                 let is_temp = if let Place::Local(l) = place {
874                     !mir.local_decls[*l].is_user_variable.is_some()
875                 } else {
876                     false
877                 };
878
879                 let locations = if is_temp {
880                     location.boring()
881                 } else {
882                     location.interesting()
883                 };
884
885                 let place_ty = place.ty(mir, tcx).to_ty(tcx);
886                 let rv_ty = rv.ty(mir, tcx);
887                 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
888                     span_mirbug!(
889                         self,
890                         stmt,
891                         "bad assignment ({:?} = {:?}): {:?}",
892                         place_ty,
893                         rv_ty,
894                         terr
895                     );
896                 }
897                 self.check_rvalue(mir, rv, location);
898                 let trait_ref = ty::TraitRef {
899                     def_id: tcx.lang_items().sized_trait().unwrap(),
900                     substs: tcx.mk_substs_trait(place_ty, &[]),
901                 };
902                 self.prove_trait_ref(trait_ref, location.interesting());
903             }
904             StatementKind::SetDiscriminant {
905                 ref place,
906                 variant_index,
907             } => {
908                 let place_type = place.ty(mir, tcx).to_ty(tcx);
909                 let adt = match place_type.sty {
910                     TypeVariants::TyAdt(adt, _) if adt.is_enum() => adt,
911                     _ => {
912                         span_bug!(
913                             stmt.source_info.span,
914                             "bad set discriminant ({:?} = {:?}): lhs is not an enum",
915                             place,
916                             variant_index
917                         );
918                     }
919                 };
920                 if variant_index >= adt.variants.len() {
921                     span_bug!(
922                         stmt.source_info.span,
923                         "bad set discriminant ({:?} = {:?}): value of of range",
924                         place,
925                         variant_index
926                     );
927                 };
928             }
929             StatementKind::UserAssertTy(c_ty, local) => {
930                 let local_ty = mir.local_decls()[local].ty;
931                 if let Err(terr) = self.eq_canonical_type_and_type(c_ty, local_ty, Locations::All) {
932                     span_mirbug!(
933                         self,
934                         stmt,
935                         "bad type assert ({:?} = {:?}): {:?}",
936                         c_ty,
937                         local_ty,
938                         terr
939                     );
940                 }
941             }
942             StatementKind::ReadForMatch(_)
943             | StatementKind::StorageLive(_)
944             | StatementKind::StorageDead(_)
945             | StatementKind::InlineAsm { .. }
946             | StatementKind::EndRegion(_)
947             | StatementKind::Validate(..)
948             | StatementKind::Nop => {}
949         }
950     }
951
952     fn check_terminator(
953         &mut self,
954         mir: &Mir<'tcx>,
955         term: &Terminator<'tcx>,
956         term_location: Location,
957     ) {
958         debug!("check_terminator: {:?}", term);
959         let tcx = self.tcx();
960         match term.kind {
961             TerminatorKind::Goto { .. }
962             | TerminatorKind::Resume
963             | TerminatorKind::Abort
964             | TerminatorKind::Return
965             | TerminatorKind::GeneratorDrop
966             | TerminatorKind::Unreachable
967             | TerminatorKind::Drop { .. }
968             | TerminatorKind::FalseEdges { .. }
969             | TerminatorKind::FalseUnwind { .. } => {
970                 // no checks needed for these
971             }
972
973             TerminatorKind::DropAndReplace {
974                 ref location,
975                 ref value,
976                 target: _,
977                 unwind: _,
978             } => {
979                 let place_ty = location.ty(mir, tcx).to_ty(tcx);
980                 let rv_ty = value.ty(mir, tcx);
981
982                 let locations = term_location.interesting();
983                 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
984                     span_mirbug!(
985                         self,
986                         term,
987                         "bad DropAndReplace ({:?} = {:?}): {:?}",
988                         place_ty,
989                         rv_ty,
990                         terr
991                     );
992                 }
993             }
994             TerminatorKind::SwitchInt {
995                 ref discr,
996                 switch_ty,
997                 ..
998             } => {
999                 let discr_ty = discr.ty(mir, tcx);
1000                 if let Err(terr) = self.sub_types(discr_ty, switch_ty, term_location.boring()) {
1001                     span_mirbug!(
1002                         self,
1003                         term,
1004                         "bad SwitchInt ({:?} on {:?}): {:?}",
1005                         switch_ty,
1006                         discr_ty,
1007                         terr
1008                     );
1009                 }
1010                 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1011                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1012                 }
1013                 // FIXME: check the values
1014             }
1015             TerminatorKind::Call {
1016                 ref func,
1017                 ref args,
1018                 ref destination,
1019                 ..
1020             } => {
1021                 let func_ty = func.ty(mir, tcx);
1022                 debug!("check_terminator: call, func_ty={:?}", func_ty);
1023                 let sig = match func_ty.sty {
1024                     ty::TyFnDef(..) | ty::TyFnPtr(_) => func_ty.fn_sig(tcx),
1025                     _ => {
1026                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1027                         return;
1028                     }
1029                 };
1030                 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
1031                     term.source_info.span,
1032                     LateBoundRegionConversionTime::FnCall,
1033                     &sig,
1034                 );
1035                 let sig = self.normalize(sig, term_location);
1036                 self.check_call_dest(mir, term, &sig, destination, term_location);
1037
1038                 self.prove_predicates(
1039                     sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1040                     term_location.boring(),
1041                 );
1042
1043                 // The ordinary liveness rules will ensure that all
1044                 // regions in the type of the callee are live here. We
1045                 // then further constrain the late-bound regions that
1046                 // were instantiated at the call site to be live as
1047                 // well. The resulting is that all the input (and
1048                 // output) types in the signature must be live, since
1049                 // all the inputs that fed into it were live.
1050                 for &late_bound_region in map.values() {
1051                     if let Some(ref mut borrowck_context) = self.borrowck_context {
1052                         let region_vid = borrowck_context
1053                             .universal_regions
1054                             .to_region_vid(late_bound_region);
1055                         borrowck_context
1056                             .constraints
1057                             .liveness_constraints
1058                             .add_element(region_vid, term_location);
1059                     }
1060                 }
1061
1062                 self.check_call_inputs(mir, term, &sig, args, term_location);
1063             }
1064             TerminatorKind::Assert {
1065                 ref cond, ref msg, ..
1066             } => {
1067                 let cond_ty = cond.ty(mir, tcx);
1068                 if cond_ty != tcx.types.bool {
1069                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1070                 }
1071
1072                 if let BoundsCheck { ref len, ref index } = *msg {
1073                     if len.ty(mir, tcx) != tcx.types.usize {
1074                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1075                     }
1076                     if index.ty(mir, tcx) != tcx.types.usize {
1077                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1078                     }
1079                 }
1080             }
1081             TerminatorKind::Yield { ref value, .. } => {
1082                 let value_ty = value.ty(mir, tcx);
1083                 match mir.yield_ty {
1084                     None => span_mirbug!(self, term, "yield in non-generator"),
1085                     Some(ty) => {
1086                         if let Err(terr) = self.sub_types(value_ty, ty, term_location.interesting())
1087                         {
1088                             span_mirbug!(
1089                                 self,
1090                                 term,
1091                                 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1092                                 value_ty,
1093                                 ty,
1094                                 terr
1095                             );
1096                         }
1097                     }
1098                 }
1099             }
1100         }
1101     }
1102
1103     fn check_call_dest(
1104         &mut self,
1105         mir: &Mir<'tcx>,
1106         term: &Terminator<'tcx>,
1107         sig: &ty::FnSig<'tcx>,
1108         destination: &Option<(Place<'tcx>, BasicBlock)>,
1109         term_location: Location,
1110     ) {
1111         let tcx = self.tcx();
1112         match *destination {
1113             Some((ref dest, _target_block)) => {
1114                 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1115                 let locations = term_location.interesting();
1116                 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations) {
1117                     span_mirbug!(
1118                         self,
1119                         term,
1120                         "call dest mismatch ({:?} <- {:?}): {:?}",
1121                         dest_ty,
1122                         sig.output(),
1123                         terr
1124                     );
1125                 }
1126             }
1127             None => {
1128                 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1129                 if !sig.output().is_never() {
1130                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1131                 }
1132             }
1133         }
1134     }
1135
1136     fn check_call_inputs(
1137         &mut self,
1138         mir: &Mir<'tcx>,
1139         term: &Terminator<'tcx>,
1140         sig: &ty::FnSig<'tcx>,
1141         args: &[Operand<'tcx>],
1142         term_location: Location,
1143     ) {
1144         debug!("check_call_inputs({:?}, {:?})", sig, args);
1145         if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1146             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1147         }
1148         for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1149             let op_arg_ty = op_arg.ty(mir, self.tcx());
1150             if let Err(terr) = self.sub_types(op_arg_ty, fn_arg, term_location.interesting()) {
1151                 span_mirbug!(
1152                     self,
1153                     term,
1154                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1155                     n,
1156                     fn_arg,
1157                     op_arg_ty,
1158                     terr
1159                 );
1160             }
1161         }
1162     }
1163
1164     fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1165         let is_cleanup = block_data.is_cleanup;
1166         self.last_span = block_data.terminator().source_info.span;
1167         match block_data.terminator().kind {
1168             TerminatorKind::Goto { target } => {
1169                 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1170             }
1171             TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1172                 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1173             },
1174             TerminatorKind::Resume => if !is_cleanup {
1175                 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1176             },
1177             TerminatorKind::Abort => if !is_cleanup {
1178                 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1179             },
1180             TerminatorKind::Return => if is_cleanup {
1181                 span_mirbug!(self, block_data, "return on cleanup block")
1182             },
1183             TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1184                 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1185             },
1186             TerminatorKind::Yield { resume, drop, .. } => {
1187                 if is_cleanup {
1188                     span_mirbug!(self, block_data, "yield in cleanup block")
1189                 }
1190                 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1191                 if let Some(drop) = drop {
1192                     self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1193                 }
1194             }
1195             TerminatorKind::Unreachable => {}
1196             TerminatorKind::Drop { target, unwind, .. }
1197             | TerminatorKind::DropAndReplace { target, unwind, .. }
1198             | TerminatorKind::Assert {
1199                 target,
1200                 cleanup: unwind,
1201                 ..
1202             } => {
1203                 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1204                 if let Some(unwind) = unwind {
1205                     if is_cleanup {
1206                         span_mirbug!(self, block_data, "unwind on cleanup block")
1207                     }
1208                     self.assert_iscleanup(mir, block_data, unwind, true);
1209                 }
1210             }
1211             TerminatorKind::Call {
1212                 ref destination,
1213                 cleanup,
1214                 ..
1215             } => {
1216                 if let &Some((_, target)) = destination {
1217                     self.assert_iscleanup(mir, block_data, target, is_cleanup);
1218                 }
1219                 if let Some(cleanup) = cleanup {
1220                     if is_cleanup {
1221                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1222                     }
1223                     self.assert_iscleanup(mir, block_data, cleanup, true);
1224                 }
1225             }
1226             TerminatorKind::FalseEdges {
1227                 real_target,
1228                 ref imaginary_targets,
1229             } => {
1230                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1231                 for target in imaginary_targets {
1232                     self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1233                 }
1234             }
1235             TerminatorKind::FalseUnwind {
1236                 real_target,
1237                 unwind,
1238             } => {
1239                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1240                 if let Some(unwind) = unwind {
1241                     if is_cleanup {
1242                         span_mirbug!(
1243                             self,
1244                             block_data,
1245                             "cleanup in cleanup block via false unwind"
1246                         );
1247                     }
1248                     self.assert_iscleanup(mir, block_data, unwind, true);
1249                 }
1250             }
1251         }
1252     }
1253
1254     fn assert_iscleanup(
1255         &mut self,
1256         mir: &Mir<'tcx>,
1257         ctxt: &dyn fmt::Debug,
1258         bb: BasicBlock,
1259         iscleanuppad: bool,
1260     ) {
1261         if mir[bb].is_cleanup != iscleanuppad {
1262             span_mirbug!(
1263                 self,
1264                 ctxt,
1265                 "cleanuppad mismatch: {:?} should be {:?}",
1266                 bb,
1267                 iscleanuppad
1268             );
1269         }
1270     }
1271
1272     fn check_local(
1273         &mut self,
1274         mir: &Mir<'tcx>,
1275         local: Local,
1276         local_decl: &LocalDecl<'tcx>,
1277         errors_buffer: &mut Option<&mut Vec<Diagnostic>>,
1278     ) {
1279         match mir.local_kind(local) {
1280             LocalKind::ReturnPointer | LocalKind::Arg => {
1281                 // return values of normal functions are required to be
1282                 // sized by typeck, but return values of ADT constructors are
1283                 // not because we don't include a `Self: Sized` bounds on them.
1284                 //
1285                 // Unbound parts of arguments were never required to be Sized
1286                 // - maybe we should make that a warning.
1287                 return;
1288             }
1289             LocalKind::Var | LocalKind::Temp => {}
1290         }
1291
1292         let span = local_decl.source_info.span;
1293         let ty = local_decl.ty;
1294
1295         // Erase the regions from `ty` to get a global type.  The
1296         // `Sized` bound in no way depends on precise regions, so this
1297         // shouldn't affect `is_sized`.
1298         let gcx = self.tcx().global_tcx();
1299         let erased_ty = gcx.lift(&self.tcx().erase_regions(&ty)).unwrap();
1300         if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1301             // in current MIR construction, all non-control-flow rvalue
1302             // expressions evaluate through `as_temp` or `into` a return
1303             // slot or local, so to find all unsized rvalues it is enough
1304             // to check all temps, return slots and locals.
1305             if let None = self.reported_errors.replace((ty, span)) {
1306                 let mut diag = struct_span_err!(
1307                     self.tcx().sess,
1308                     span,
1309                     E0161,
1310                     "cannot move a value of type {0}: the size of {0} \
1311                      cannot be statically determined",
1312                     ty
1313                 );
1314                 if let Some(ref mut errors_buffer) = *errors_buffer {
1315                     diag.buffer(errors_buffer);
1316                 } else {
1317                     // we're allowed to use emit() here because the
1318                     // NLL migration will be turned on (and thus
1319                     // errors will need to be buffered) *only if*
1320                     // errors_buffer is Some.
1321                     diag.emit();
1322                 }
1323             }
1324         }
1325     }
1326
1327     fn aggregate_field_ty(
1328         &mut self,
1329         ak: &AggregateKind<'tcx>,
1330         field_index: usize,
1331         location: Location,
1332     ) -> Result<Ty<'tcx>, FieldAccessError> {
1333         let tcx = self.tcx();
1334
1335         match *ak {
1336             AggregateKind::Adt(def, variant_index, substs, active_field_index) => {
1337                 let variant = &def.variants[variant_index];
1338                 let adj_field_index = active_field_index.unwrap_or(field_index);
1339                 if let Some(field) = variant.fields.get(adj_field_index) {
1340                     Ok(self.normalize(field.ty(tcx, substs), location))
1341                 } else {
1342                     Err(FieldAccessError::OutOfRange {
1343                         field_count: variant.fields.len(),
1344                     })
1345                 }
1346             }
1347             AggregateKind::Closure(def_id, substs) => {
1348                 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1349                     Some(ty) => Ok(ty),
1350                     None => Err(FieldAccessError::OutOfRange {
1351                         field_count: substs.upvar_tys(def_id, tcx).count(),
1352                     }),
1353                 }
1354             }
1355             AggregateKind::Generator(def_id, substs, _) => {
1356                 // Try pre-transform fields first (upvars and current state)
1357                 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1358                     Ok(ty)
1359                 } else {
1360                     // Then try `field_tys` which contains all the fields, but it
1361                     // requires the final optimized MIR.
1362                     match substs.field_tys(def_id, tcx).nth(field_index) {
1363                         Some(ty) => Ok(ty),
1364                         None => Err(FieldAccessError::OutOfRange {
1365                             field_count: substs.field_tys(def_id, tcx).count(),
1366                         }),
1367                     }
1368                 }
1369             }
1370             AggregateKind::Array(ty) => Ok(ty),
1371             AggregateKind::Tuple => {
1372                 unreachable!("This should have been covered in check_rvalues");
1373             }
1374         }
1375     }
1376
1377     fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1378         let tcx = self.tcx();
1379
1380         match rvalue {
1381             Rvalue::Aggregate(ak, ops) => {
1382                 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1383             }
1384
1385             Rvalue::Repeat(operand, len) => if *len > 1 {
1386                 let operand_ty = operand.ty(mir, tcx);
1387
1388                 let trait_ref = ty::TraitRef {
1389                     def_id: tcx.lang_items().copy_trait().unwrap(),
1390                     substs: tcx.mk_substs_trait(operand_ty, &[]),
1391                 };
1392
1393                 self.prove_trait_ref(trait_ref, location.interesting());
1394             },
1395
1396             Rvalue::NullaryOp(_, ty) => {
1397                 let trait_ref = ty::TraitRef {
1398                     def_id: tcx.lang_items().sized_trait().unwrap(),
1399                     substs: tcx.mk_substs_trait(ty, &[]),
1400                 };
1401
1402                 self.prove_trait_ref(trait_ref, location.interesting());
1403             }
1404
1405             Rvalue::Cast(cast_kind, op, ty) => match cast_kind {
1406                 CastKind::ReifyFnPointer => {
1407                     let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1408
1409                     // The type that we see in the fcx is like
1410                     // `foo::<'a, 'b>`, where `foo` is the path to a
1411                     // function definition. When we extract the
1412                     // signature, it comes from the `fn_sig` query,
1413                     // and hence may contain unnormalized results.
1414                     let fn_sig = self.normalize(fn_sig, location);
1415
1416                     let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1417
1418                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1419                         span_mirbug!(
1420                             self,
1421                             rvalue,
1422                             "equating {:?} with {:?} yields {:?}",
1423                             ty_fn_ptr_from,
1424                             ty,
1425                             terr
1426                         );
1427                     }
1428                 }
1429
1430                 CastKind::ClosureFnPointer => {
1431                     let sig = match op.ty(mir, tcx).sty {
1432                         ty::TyClosure(def_id, substs) => {
1433                             substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1434                         }
1435                         _ => bug!(),
1436                     };
1437                     let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1438
1439                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1440                         span_mirbug!(
1441                             self,
1442                             rvalue,
1443                             "equating {:?} with {:?} yields {:?}",
1444                             ty_fn_ptr_from,
1445                             ty,
1446                             terr
1447                         );
1448                     }
1449                 }
1450
1451                 CastKind::UnsafeFnPointer => {
1452                     let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1453
1454                     // The type that we see in the fcx is like
1455                     // `foo::<'a, 'b>`, where `foo` is the path to a
1456                     // function definition. When we extract the
1457                     // signature, it comes from the `fn_sig` query,
1458                     // and hence may contain unnormalized results.
1459                     let fn_sig = self.normalize(fn_sig, location);
1460
1461                     let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1462
1463                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1464                         span_mirbug!(
1465                             self,
1466                             rvalue,
1467                             "equating {:?} with {:?} yields {:?}",
1468                             ty_fn_ptr_from,
1469                             ty,
1470                             terr
1471                         );
1472                     }
1473                 }
1474
1475                 CastKind::Unsize => {
1476                     let &ty = ty;
1477                     let trait_ref = ty::TraitRef {
1478                         def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1479                         substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1480                     };
1481
1482                     self.prove_trait_ref(trait_ref, location.interesting());
1483                 }
1484
1485                 CastKind::Misc => {}
1486             },
1487
1488             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1489                 self.add_reborrow_constraint(location, region, borrowed_place);
1490             }
1491
1492             // FIXME: These other cases have to be implemented in future PRs
1493             Rvalue::Use(..)
1494             | Rvalue::Len(..)
1495             | Rvalue::BinaryOp(..)
1496             | Rvalue::CheckedBinaryOp(..)
1497             | Rvalue::UnaryOp(..)
1498             | Rvalue::Discriminant(..) => {}
1499         }
1500     }
1501
1502     fn check_aggregate_rvalue(
1503         &mut self,
1504         mir: &Mir<'tcx>,
1505         rvalue: &Rvalue<'tcx>,
1506         aggregate_kind: &AggregateKind<'tcx>,
1507         operands: &[Operand<'tcx>],
1508         location: Location,
1509     ) {
1510         let tcx = self.tcx();
1511
1512         self.prove_aggregate_predicates(aggregate_kind, location);
1513
1514         if *aggregate_kind == AggregateKind::Tuple {
1515             // tuple rvalue field type is always the type of the op. Nothing to check here.
1516             return;
1517         }
1518
1519         for (i, operand) in operands.iter().enumerate() {
1520             let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
1521                 Ok(field_ty) => field_ty,
1522                 Err(FieldAccessError::OutOfRange { field_count }) => {
1523                     span_mirbug!(
1524                         self,
1525                         rvalue,
1526                         "accessed field #{} but variant only has {}",
1527                         i,
1528                         field_count
1529                     );
1530                     continue;
1531                 }
1532             };
1533             let operand_ty = operand.ty(mir, tcx);
1534
1535             if let Err(terr) = self.sub_types(operand_ty, field_ty, location.boring()) {
1536                 span_mirbug!(
1537                     self,
1538                     rvalue,
1539                     "{:?} is not a subtype of {:?}: {:?}",
1540                     operand_ty,
1541                     field_ty,
1542                     terr
1543                 );
1544             }
1545         }
1546     }
1547
1548     /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
1549     ///
1550     /// # Parameters
1551     ///
1552     /// - `location`: the location `L` where the borrow expression occurs
1553     /// - `borrow_region`: the region `'a` associated with the borrow
1554     /// - `borrowed_place`: the place `P` being borrowed
1555     fn add_reborrow_constraint(
1556         &mut self,
1557         location: Location,
1558         borrow_region: ty::Region<'tcx>,
1559         borrowed_place: &Place<'tcx>,
1560     ) {
1561         // These constraints are only meaningful during borrowck:
1562         let BorrowCheckContext {
1563             borrow_set,
1564             location_table,
1565             all_facts,
1566             constraints,
1567             ..
1568         } = match self.borrowck_context {
1569             Some(ref mut borrowck_context) => borrowck_context,
1570             None => return,
1571         };
1572
1573         // In Polonius mode, we also push a `borrow_region` fact
1574         // linking the loan to the region (in some cases, though,
1575         // there is no loan associated with this borrow expression --
1576         // that occurs when we are borrowing an unsafe place, for
1577         // example).
1578         if let Some(all_facts) = all_facts {
1579             if let Some(borrow_index) = borrow_set.location_map.get(&location) {
1580                 let region_vid = borrow_region.to_region_vid();
1581                 all_facts.borrow_region.push((
1582                     region_vid,
1583                     *borrow_index,
1584                     location_table.mid_index(location),
1585                 ));
1586             }
1587         }
1588
1589         // If we are reborrowing the referent of another reference, we
1590         // need to add outlives relationships. In a case like `&mut
1591         // *p`, where the `p` has type `&'b mut Foo`, for example, we
1592         // need to ensure that `'b: 'a`.
1593
1594         let mut borrowed_place = borrowed_place;
1595
1596         debug!(
1597             "add_reborrow_constraint({:?}, {:?}, {:?})",
1598             location, borrow_region, borrowed_place
1599         );
1600         while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
1601             debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
1602
1603             match *elem {
1604                 ProjectionElem::Deref => {
1605                     let tcx = self.infcx.tcx;
1606                     let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1607
1608                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
1609                     match base_ty.sty {
1610                         ty::TyRef(ref_region, _, mutbl) => {
1611                             constraints.outlives_constraints.push(OutlivesConstraint {
1612                                 sup: ref_region.to_region_vid(),
1613                                 sub: borrow_region.to_region_vid(),
1614                                 locations: location.boring(),
1615                             });
1616
1617                             if let Some(all_facts) = all_facts {
1618                                 all_facts.outlives.push((
1619                                     ref_region.to_region_vid(),
1620                                     borrow_region.to_region_vid(),
1621                                     location_table.mid_index(location),
1622                                 ));
1623                             }
1624
1625                             match mutbl {
1626                                 hir::Mutability::MutImmutable => {
1627                                     // Immutable reference. We don't need the base
1628                                     // to be valid for the entire lifetime of
1629                                     // the borrow.
1630                                     break;
1631                                 }
1632                                 hir::Mutability::MutMutable => {
1633                                     // Mutable reference. We *do* need the base
1634                                     // to be valid, because after the base becomes
1635                                     // invalid, someone else can use our mutable deref.
1636
1637                                     // This is in order to make the following function
1638                                     // illegal:
1639                                     // ```
1640                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
1641                                     //     &mut *x
1642                                     // }
1643                                     // ```
1644                                     //
1645                                     // As otherwise you could clone `&mut T` using the
1646                                     // following function:
1647                                     // ```
1648                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
1649                                     //     let my_clone = unsafe_deref(&'a x);
1650                                     //     ENDREGION 'a;
1651                                     //     (my_clone, x)
1652                                     // }
1653                                     // ```
1654                                 }
1655                             }
1656                         }
1657                         ty::TyRawPtr(..) => {
1658                             // deref of raw pointer, guaranteed to be valid
1659                             break;
1660                         }
1661                         ty::TyAdt(def, _) if def.is_box() => {
1662                             // deref of `Box`, need the base to be valid - propagate
1663                         }
1664                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
1665                     }
1666                 }
1667                 ProjectionElem::Field(..)
1668                 | ProjectionElem::Downcast(..)
1669                 | ProjectionElem::Index(..)
1670                 | ProjectionElem::ConstantIndex { .. }
1671                 | ProjectionElem::Subslice { .. } => {
1672                     // other field access
1673                 }
1674             }
1675
1676             // The "propagate" case. We need to check that our base is valid
1677             // for the borrow's lifetime.
1678             borrowed_place = base;
1679         }
1680     }
1681
1682     fn prove_aggregate_predicates(
1683         &mut self,
1684         aggregate_kind: &AggregateKind<'tcx>,
1685         location: Location,
1686     ) {
1687         let tcx = self.tcx();
1688
1689         debug!(
1690             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
1691             aggregate_kind, location
1692         );
1693
1694         let instantiated_predicates = match aggregate_kind {
1695             AggregateKind::Adt(def, _, substs, _) => {
1696                 tcx.predicates_of(def.did).instantiate(tcx, substs)
1697             }
1698
1699             // For closures, we have some **extra requirements** we
1700             //
1701             // have to check. In particular, in their upvars and
1702             // signatures, closures often reference various regions
1703             // from the surrounding function -- we call those the
1704             // closure's free regions. When we borrow-check (and hence
1705             // region-check) closures, we may find that the closure
1706             // requires certain relationships between those free
1707             // regions. However, because those free regions refer to
1708             // portions of the CFG of their caller, the closure is not
1709             // in a position to verify those relationships. In that
1710             // case, the requirements get "propagated" to us, and so
1711             // we have to solve them here where we instantiate the
1712             // closure.
1713             //
1714             // Despite the opacity of the previous parapgrah, this is
1715             // actually relatively easy to understand in terms of the
1716             // desugaring. A closure gets desugared to a struct, and
1717             // these extra requirements are basically like where
1718             // clauses on the struct.
1719             AggregateKind::Closure(def_id, substs) => {
1720                 if let Some(closure_region_requirements) =
1721                     tcx.mir_borrowck(*def_id).closure_requirements
1722                 {
1723                     let closure_constraints = closure_region_requirements.apply_requirements(
1724                         self.infcx.tcx,
1725                         location,
1726                         *def_id,
1727                         *substs,
1728                     );
1729
1730                     // Hmm, are these constraints *really* boring?
1731                     self.push_region_constraints(location.boring(), &closure_constraints);
1732                 }
1733
1734                 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1735             }
1736
1737             AggregateKind::Generator(def_id, substs, _) => {
1738                 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1739             }
1740
1741             AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
1742         };
1743
1744         self.normalize_and_prove_instantiated_predicates(
1745             instantiated_predicates,
1746             location.boring(),
1747         );
1748     }
1749
1750     fn prove_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>, locations: Locations) {
1751         self.prove_predicates(
1752             Some(ty::Predicate::Trait(
1753                 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
1754             )),
1755             locations,
1756         );
1757     }
1758
1759     fn normalize_and_prove_instantiated_predicates(
1760         &mut self,
1761         instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
1762         locations: Locations,
1763     ) {
1764         for predicate in instantiated_predicates.predicates {
1765             let predicate = self.normalize(predicate, locations);
1766             self.prove_predicate(predicate, locations);
1767         }
1768     }
1769
1770     fn prove_predicates(
1771         &mut self,
1772         predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
1773         locations: Locations,
1774     ) {
1775         for predicate in predicates {
1776             debug!(
1777                 "prove_predicates(predicate={:?}, locations={:?})",
1778                 predicate, locations,
1779             );
1780
1781             self.prove_predicate(predicate, locations);
1782         }
1783     }
1784
1785     fn prove_predicate(&mut self, predicate: ty::Predicate<'tcx>, locations: Locations) {
1786         debug!(
1787             "prove_predicate(predicate={:?}, location={:?})",
1788             predicate, locations,
1789         );
1790
1791         let param_env = self.param_env;
1792         self.fully_perform_op(
1793             locations,
1794             param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
1795         ).unwrap_or_else(|NoSolution| {
1796             span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
1797         })
1798     }
1799
1800     fn typeck_mir(&mut self, mir: &Mir<'tcx>, mut errors_buffer: Option<&mut Vec<Diagnostic>>) {
1801         self.last_span = mir.span;
1802         debug!("run_on_mir: {:?}", mir.span);
1803
1804         for (local, local_decl) in mir.local_decls.iter_enumerated() {
1805             self.check_local(mir, local, local_decl, &mut errors_buffer);
1806         }
1807
1808         for (block, block_data) in mir.basic_blocks().iter_enumerated() {
1809             let mut location = Location {
1810                 block,
1811                 statement_index: 0,
1812             };
1813             for stmt in &block_data.statements {
1814                 if !stmt.source_info.span.is_dummy() {
1815                     self.last_span = stmt.source_info.span;
1816                 }
1817                 self.check_stmt(mir, stmt, location);
1818                 location.statement_index += 1;
1819             }
1820
1821             self.check_terminator(mir, block_data.terminator(), location);
1822             self.check_iscleanup(mir, block_data);
1823         }
1824     }
1825
1826     fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
1827     where
1828         T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
1829     {
1830         debug!("normalize(value={:?}, location={:?})", value, location);
1831         let param_env = self.param_env;
1832         self.fully_perform_op(
1833             location.to_locations(),
1834             param_env.and(type_op::normalize::Normalize::new(value)),
1835         ).unwrap_or_else(|NoSolution| {
1836             span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
1837             value
1838         })
1839     }
1840 }
1841
1842 pub struct TypeckMir;
1843
1844 impl MirPass for TypeckMir {
1845     fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
1846         let def_id = src.def_id;
1847         debug!("run_pass: {:?}", def_id);
1848
1849         // When NLL is enabled, the borrow checker runs the typeck
1850         // itself, so we don't need this MIR pass anymore.
1851         if tcx.use_mir_borrowck() {
1852             return;
1853         }
1854
1855         if tcx.sess.err_count() > 0 {
1856             // compiling a broken program can obviously result in a
1857             // broken MIR, so try not to report duplicate errors.
1858             return;
1859         }
1860
1861         if tcx.is_struct_constructor(def_id) {
1862             // We just assume that the automatically generated struct constructors are
1863             // correct. See the comment in the `mir_borrowck` implementation for an
1864             // explanation why we need this.
1865             return;
1866         }
1867
1868         let param_env = tcx.param_env(def_id);
1869         tcx.infer_ctxt().enter(|infcx| {
1870             type_check_internal(
1871                 &infcx,
1872                 def_id,
1873                 param_env,
1874                 mir,
1875                 &[],
1876                 None,
1877                 None,
1878                 None,
1879                 |_| (),
1880             );
1881
1882             // For verification purposes, we just ignore the resulting
1883             // region constraint sets. Not our problem. =)
1884         });
1885     }
1886 }
1887
1888 pub trait AtLocation {
1889     /// Indicates a "boring" constraint that the user probably
1890     /// woudln't want to see highlights.
1891     fn boring(self) -> Locations;
1892
1893     /// Indicates an "interesting" edge, which is of significance only
1894     /// for diagnostics.
1895     fn interesting(self) -> Locations;
1896 }
1897
1898 impl AtLocation for Location {
1899     fn boring(self) -> Locations {
1900         Locations::Boring(self)
1901     }
1902
1903     fn interesting(self) -> Locations {
1904         Locations::Interesting(self)
1905     }
1906 }
1907
1908 trait NormalizeLocation: fmt::Debug + Copy {
1909     fn to_locations(self) -> Locations;
1910 }
1911
1912 impl NormalizeLocation for Locations {
1913     fn to_locations(self) -> Locations {
1914         self
1915     }
1916 }
1917
1918 impl NormalizeLocation for Location {
1919     fn to_locations(self) -> Locations {
1920         self.boring()
1921     }
1922 }