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