]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/type_check/mod.rs
Various minor/cosmetic improvements to code
[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
13 #![allow(unreachable_code)]
14
15 use borrow_check::borrow_set::BorrowSet;
16 use borrow_check::location::LocationTable;
17 use borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
18 use borrow_check::nll::facts::AllFacts;
19 use borrow_check::nll::region_infer::values::LivenessValues;
20 use borrow_check::nll::region_infer::values::PlaceholderIndex;
21 use borrow_check::nll::region_infer::values::PlaceholderIndices;
22 use borrow_check::nll::region_infer::values::RegionValueElements;
23 use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
24 use borrow_check::nll::renumber;
25 use borrow_check::nll::type_check::free_region_relations::{
26     CreateResult, UniversalRegionRelations,
27 };
28 use borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
29 use borrow_check::nll::ToRegionVid;
30 use dataflow::move_paths::MoveData;
31 use dataflow::FlowAtLocation;
32 use dataflow::MaybeInitializedPlaces;
33 use either::Either;
34 use rustc::hir;
35 use rustc::hir::def_id::DefId;
36 use rustc::infer::canonical::QueryRegionConstraint;
37 use rustc::infer::outlives::env::RegionBoundPairs;
38 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
39 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
40 use rustc::mir::tcx::PlaceTy;
41 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
42 use rustc::mir::*;
43 use rustc::traits::query::type_op;
44 use rustc::traits::query::type_op::custom::CustomTypeOp;
45 use rustc::traits::query::{Fallible, NoSolution};
46 use rustc::traits::{ObligationCause, PredicateObligations};
47 use rustc::ty::fold::TypeFoldable;
48 use rustc::ty::subst::{Subst, Substs, UnpackedKind};
49 use rustc::ty::{self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TyKind};
50 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
51 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
52 use rustc::ty::layout::VariantIdx;
53 use std::rc::Rc;
54 use std::{fmt, iter};
55 use syntax_pos::{Span, DUMMY_SP};
56 use transform::{MirPass, MirSource};
57
58 macro_rules! span_mirbug {
59     ($context:expr, $elem:expr, $($message:tt)*) => ({
60         $crate::borrow_check::nll::type_check::mirbug(
61             $context.tcx(),
62             $context.last_span,
63             &format!(
64                 "broken MIR in {:?} ({:?}): {}",
65                 $context.mir_def_id,
66                 $elem,
67                 format_args!($($message)*),
68             ),
69         )
70     })
71 }
72
73 macro_rules! span_mirbug_and_err {
74     ($context:expr, $elem:expr, $($message:tt)*) => ({
75         {
76             span_mirbug!($context, $elem, $($message)*);
77             $context.error()
78         }
79     })
80 }
81
82 mod constraint_conversion;
83 pub mod free_region_relations;
84 mod input_output;
85 crate mod liveness;
86 mod relate_tys;
87
88 /// Type checks the given `mir` in the context of the inference
89 /// context `infcx`. Returns any region constraints that have yet to
90 /// be proven. This result is includes liveness constraints that
91 /// ensure that regions appearing in the types of all local variables
92 /// are live at all points where that local variable may later be
93 /// used.
94 ///
95 /// This phase of type-check ought to be infallible -- this is because
96 /// the original, HIR-based type-check succeeded. So if any errors
97 /// occur here, we will get a `bug!` reported.
98 ///
99 /// # Parameters
100 ///
101 /// - `infcx` -- inference context to use
102 /// - `param_env` -- parameter environment to use for trait solving
103 /// - `mir` -- MIR to type-check
104 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
105 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
106 ///   and lifetimes (e.g., `&'a T` implies `T: 'a`)
107 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
108 ///   to outlive; should represent the fn body
109 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
110 ///   the types of the input parameters found in the MIR itself will be equated with these
111 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
112 ///   the type for the RETURN_PLACE will be equated with this
113 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
114 ///   constraints for the regions in the types of variables
115 /// - `flow_inits` -- results of a maybe-init dataflow analysis
116 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
117 pub(crate) fn type_check<'gcx, 'tcx>(
118     infcx: &InferCtxt<'_, 'gcx, 'tcx>,
119     param_env: ty::ParamEnv<'gcx>,
120     mir: &Mir<'tcx>,
121     mir_def_id: DefId,
122     universal_regions: &Rc<UniversalRegions<'tcx>>,
123     location_table: &LocationTable,
124     borrow_set: &BorrowSet<'tcx>,
125     all_facts: &mut Option<AllFacts>,
126     flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
127     move_data: &MoveData<'tcx>,
128     elements: &Rc<RegionValueElements>,
129 ) -> MirTypeckResults<'tcx> {
130     let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
131     let mut constraints = MirTypeckRegionConstraints {
132         placeholder_indices: PlaceholderIndices::default(),
133         placeholder_index_to_region: IndexVec::default(),
134         liveness_constraints: LivenessValues::new(elements),
135         outlives_constraints: ConstraintSet::default(),
136         closure_bounds_mapping: Default::default(),
137         type_tests: Vec::default(),
138     };
139
140     let CreateResult {
141         universal_region_relations,
142         region_bound_pairs,
143         normalized_inputs_and_output,
144     } = free_region_relations::create(
145         infcx,
146         param_env,
147         Some(implicit_region_bound),
148         universal_regions,
149         &mut constraints,
150     );
151
152     let mut borrowck_context = BorrowCheckContext {
153         universal_regions,
154         location_table,
155         borrow_set,
156         all_facts,
157         constraints: &mut constraints,
158     };
159
160     type_check_internal(
161         infcx,
162         mir_def_id,
163         param_env,
164         mir,
165         &region_bound_pairs,
166         Some(implicit_region_bound),
167         Some(&mut borrowck_context),
168         Some(&universal_region_relations),
169         |cx| {
170             cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
171             liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
172
173             cx.borrowck_context
174                 .as_mut()
175                 .map(|bcx| translate_outlives_facts(bcx));
176         },
177     );
178
179     MirTypeckResults {
180         constraints,
181         universal_region_relations,
182     }
183 }
184
185 fn type_check_internal<'a, 'gcx, 'tcx, R>(
186     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
187     mir_def_id: DefId,
188     param_env: ty::ParamEnv<'gcx>,
189     mir: &'a Mir<'tcx>,
190     region_bound_pairs: &'a RegionBoundPairs<'tcx>,
191     implicit_region_bound: Option<ty::Region<'tcx>>,
192     borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
193     universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
194     mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
195 ) -> R where {
196     let mut checker = TypeChecker::new(
197         infcx,
198         mir,
199         mir_def_id,
200         param_env,
201         region_bound_pairs,
202         implicit_region_bound,
203         borrowck_context,
204         universal_region_relations,
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);
215     }
216
217     extra(&mut checker)
218 }
219
220 fn translate_outlives_facts(cx: &mut BorrowCheckContext) {
221     if let Some(facts) = cx.all_facts {
222         let location_table = cx.location_table;
223         facts
224             .outlives
225             .extend(cx.constraints.outlives_constraints.iter().flat_map(
226                 |constraint: &OutlivesConstraint| {
227                     if let Some(from_location) = constraint.locations.from_location() {
228                         Either::Left(iter::once((
229                             constraint.sup,
230                             constraint.sub,
231                             location_table.mid_index(from_location),
232                         )))
233                     } else {
234                         Either::Right(
235                             location_table
236                                 .all_points()
237                                 .map(move |location| (constraint.sup, constraint.sub, location)),
238                         )
239                     }
240                 },
241             ));
242     }
243 }
244
245 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
246     // We sometimes see MIR failures (notably predicate failures) due to
247     // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
248     // to avoid reporting bugs in those cases.
249     tcx.sess.diagnostic().delay_span_bug(span, msg);
250 }
251
252 enum FieldAccessError {
253     OutOfRange { field_count: usize },
254 }
255
256 /// Verifies that MIR types are sane to not crash further checks.
257 ///
258 /// The sanitize_XYZ methods here take an MIR object and compute its
259 /// type, calling `span_mirbug` and returning an error type if there
260 /// is a problem.
261 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
262     cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
263     mir: &'a Mir<'tcx>,
264     last_span: Span,
265     mir_def_id: DefId,
266     errors_reported: bool,
267 }
268
269 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
270     fn visit_span(&mut self, span: &Span) {
271         if !span.is_dummy() {
272             self.last_span = *span;
273         }
274     }
275
276     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
277         self.sanitize_place(place, location, context);
278     }
279
280     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
281         self.super_constant(constant, location);
282         self.sanitize_constant(constant, location);
283         self.sanitize_type(constant, constant.ty);
284
285         if let Some(user_ty) = constant.user_ty {
286             if let Err(terr) = self.cx.relate_type_and_user_type(
287                 constant.ty,
288                 ty::Variance::Invariant,
289                 &UserTypeProjection { base: user_ty, projs: vec![], },
290                 location.to_locations(),
291                 ConstraintCategory::Boring,
292             ) {
293                 span_mirbug!(
294                     self,
295                     constant,
296                     "bad constant user type {:?} vs {:?}: {:?}",
297                     user_ty,
298                     constant.ty,
299                     terr,
300                 );
301             }
302         }
303     }
304
305     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
306         self.super_rvalue(rvalue, location);
307         let rval_ty = rvalue.ty(self.mir, self.tcx());
308         self.sanitize_type(rvalue, rval_ty);
309     }
310
311     fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
312         self.super_local_decl(local, local_decl);
313         self.sanitize_type(local_decl, local_decl.ty);
314
315         for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
316             if let Err(terr) = self.cx.relate_type_and_user_type(
317                 local_decl.ty,
318                 ty::Variance::Invariant,
319                 user_ty,
320                 Locations::All(*span),
321                 ConstraintCategory::TypeAnnotation,
322             ) {
323                 span_mirbug!(
324                     self,
325                     local,
326                     "bad user type on variable {:?}: {:?} != {:?} ({:?})",
327                     local,
328                     local_decl.ty,
329                     local_decl.user_ty,
330                     terr,
331                 );
332             }
333         }
334     }
335
336     fn visit_mir(&mut self, mir: &Mir<'tcx>) {
337         self.sanitize_type(&"return type", mir.return_ty());
338         for local_decl in &mir.local_decls {
339             self.sanitize_type(local_decl, local_decl.ty);
340         }
341         if self.errors_reported {
342             return;
343         }
344         self.super_mir(mir);
345     }
346 }
347
348 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
349     fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
350         TypeVerifier {
351             mir,
352             mir_def_id: cx.mir_def_id,
353             cx,
354             last_span: mir.span,
355             errors_reported: false,
356         }
357     }
358
359     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
360         self.cx.infcx.tcx
361     }
362
363     fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
364         if ty.has_escaping_bound_vars() || ty.references_error() {
365             span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
366         } else {
367             ty
368         }
369     }
370
371     /// Checks that the constant's `ty` field matches up with what
372     /// would be expected from its literal.
373     fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
374         debug!(
375             "sanitize_constant(constant={:?}, location={:?})",
376             constant, location
377         );
378
379         // FIXME(#46702) -- We need some way to get the predicates
380         // associated with the "pre-evaluated" form of the
381         // constant. For example, consider that the constant
382         // may have associated constant projections (`<Foo as
383         // Trait<'a, 'b>>::SOME_CONST`) that impose
384         // constraints on `'a` and `'b`. These constraints
385         // would be lost if we just look at the normalized
386         // value.
387         if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
388             let tcx = self.tcx();
389             let type_checker = &mut self.cx;
390
391             // FIXME -- For now, use the substitutions from
392             // `value.ty` rather than `value.val`. The
393             // renumberer will rewrite them to independent
394             // sets of regions; in principle, we ought to
395             // derive the type of the `value.val` from "first
396             // principles" and equate with value.ty, but as we
397             // are transitioning to the miri-based system, we
398             // don't have a handy function for that, so for
399             // now we just ignore `value.val` regions.
400
401             let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
402             type_checker.normalize_and_prove_instantiated_predicates(
403                 instantiated_predicates,
404                 location.to_locations(),
405             );
406         }
407
408         debug!("sanitize_constant: expected_ty={:?}", constant.literal.ty);
409
410         if let Err(terr) = self.cx.eq_types(
411             constant.literal.ty,
412             constant.ty,
413             location.to_locations(),
414             ConstraintCategory::Boring,
415         ) {
416             span_mirbug!(
417                 self,
418                 constant,
419                 "constant {:?} should have type {:?} but has {:?} ({:?})",
420                 constant,
421                 constant.literal.ty,
422                 constant.ty,
423                 terr,
424             );
425         }
426     }
427
428     /// Checks that the types internal to the `place` match up with
429     /// what would be expected.
430     fn sanitize_place(
431         &mut self,
432         place: &Place<'tcx>,
433         location: Location,
434         context: PlaceContext,
435     ) -> PlaceTy<'tcx> {
436         debug!("sanitize_place: {:?}", place);
437         let place_ty = match *place {
438             Place::Local(index) => PlaceTy::Ty {
439                 ty: self.mir.local_decls[index].ty,
440             },
441             Place::Promoted(box (_index, sty)) => {
442                 let sty = self.sanitize_type(place, sty);
443                 // FIXME -- promoted MIR return types reference
444                 // various "free regions" (e.g., scopes and things)
445                 // that they ought not to do. We have to figure out
446                 // how best to handle that -- probably we want treat
447                 // promoted MIR much like closures, renumbering all
448                 // their free regions and propagating constraints
449                 // upwards. We have the same acyclic guarantees, so
450                 // that should be possible. But for now, ignore them.
451                 //
452                 // let promoted_mir = &self.mir.promoted[index];
453                 // promoted_mir.return_ty()
454                 PlaceTy::Ty { ty: sty }
455             }
456             Place::Static(box Static { def_id, ty: sty }) => {
457                 let sty = self.sanitize_type(place, sty);
458                 let ty = self.tcx().type_of(def_id);
459                 let ty = self.cx.normalize(ty, location);
460                 if let Err(terr) =
461                     self.cx
462                         .eq_types(ty, sty, location.to_locations(), ConstraintCategory::Boring)
463                 {
464                     span_mirbug!(
465                         self,
466                         place,
467                         "bad static type ({:?}: {:?}): {:?}",
468                         ty,
469                         sty,
470                         terr
471                     );
472                 }
473                 PlaceTy::Ty { ty: sty }
474             }
475             Place::Projection(ref proj) => {
476                 let base_context = if context.is_mutating_use() {
477                     PlaceContext::MutatingUse(MutatingUseContext::Projection)
478                 } else {
479                     PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
480                 };
481                 let base_ty = self.sanitize_place(&proj.base, location, base_context);
482                 if let PlaceTy::Ty { ty } = base_ty {
483                     if ty.references_error() {
484                         assert!(self.errors_reported);
485                         return PlaceTy::Ty {
486                             ty: self.tcx().types.err,
487                         };
488                     }
489                 }
490                 self.sanitize_projection(base_ty, &proj.elem, place, location)
491             }
492         };
493         if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
494             let tcx = self.tcx();
495             let trait_ref = ty::TraitRef {
496                 def_id: tcx.lang_items().copy_trait().unwrap(),
497                 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
498             };
499
500             // In order to have a Copy operand, the type T of the value must be Copy. Note that we
501             // prove that T: Copy, rather than using the type_moves_by_default test. This is
502             // important because type_moves_by_default ignores the resulting region obligations and
503             // assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
504             // (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
505             // fully apply: in effect, the rule is that if a value of some type could implement
506             // Copy, then it must.
507             self.cx.prove_trait_ref(
508                 trait_ref,
509                 location.to_locations(),
510                 ConstraintCategory::CopyBound,
511             );
512         }
513         place_ty
514     }
515
516     fn sanitize_projection(
517         &mut self,
518         base: PlaceTy<'tcx>,
519         pi: &PlaceElem<'tcx>,
520         place: &Place<'tcx>,
521         location: Location,
522     ) -> PlaceTy<'tcx> {
523         debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
524         let tcx = self.tcx();
525         let base_ty = base.to_ty(tcx);
526         match *pi {
527             ProjectionElem::Deref => {
528                 let deref_ty = base_ty.builtin_deref(true);
529                 PlaceTy::Ty {
530                     ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
531                         span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
532                     }),
533                 }
534             }
535             ProjectionElem::Index(i) => {
536                 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
537                 if index_ty != tcx.types.usize {
538                     PlaceTy::Ty {
539                         ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
540                     }
541                 } else {
542                     PlaceTy::Ty {
543                         ty: base_ty.builtin_index().unwrap_or_else(|| {
544                             span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
545                         }),
546                     }
547                 }
548             }
549             ProjectionElem::ConstantIndex { .. } => {
550                 // consider verifying in-bounds
551                 PlaceTy::Ty {
552                     ty: base_ty.builtin_index().unwrap_or_else(|| {
553                         span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
554                     }),
555                 }
556             }
557             ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
558                 ty: match base_ty.sty {
559                     ty::Array(inner, size) => {
560                         let size = size.unwrap_usize(tcx);
561                         let min_size = (from as u64) + (to as u64);
562                         if let Some(rest_size) = size.checked_sub(min_size) {
563                             tcx.mk_array(inner, rest_size)
564                         } else {
565                             span_mirbug_and_err!(
566                                 self,
567                                 place,
568                                 "taking too-small slice of {:?}",
569                                 base_ty
570                             )
571                         }
572                     }
573                     ty::Slice(..) => base_ty,
574                     _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
575                 },
576             },
577             ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
578                 ty::Adt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
579                     if index.as_usize() >= adt_def.variants.len() {
580                         PlaceTy::Ty {
581                             ty: span_mirbug_and_err!(
582                                 self,
583                                 place,
584                                 "cast to variant #{:?} but enum only has {:?}",
585                                 index,
586                                 adt_def.variants.len()
587                             ),
588                         }
589                     } else {
590                         PlaceTy::Downcast {
591                             adt_def,
592                             substs,
593                             variant_index: index,
594                         }
595                     }
596                 }
597                 _ => PlaceTy::Ty {
598                     ty: span_mirbug_and_err!(
599                         self,
600                         place,
601                         "can't downcast {:?} as {:?}",
602                         base_ty,
603                         adt_def1
604                     ),
605                 },
606             },
607             ProjectionElem::Field(field, fty) => {
608                 let fty = self.sanitize_type(place, fty);
609                 match self.field_ty(place, base, field, location) {
610                     Ok(ty) => if let Err(terr) = self.cx.eq_types(
611                         ty,
612                         fty,
613                         location.to_locations(),
614                         ConstraintCategory::Boring,
615                     ) {
616                         span_mirbug!(
617                             self,
618                             place,
619                             "bad field access ({:?}: {:?}): {:?}",
620                             ty,
621                             fty,
622                             terr
623                         );
624                     },
625                     Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
626                         self,
627                         place,
628                         "accessed field #{} but variant only has {}",
629                         field.index(),
630                         field_count
631                     ),
632                 }
633                 PlaceTy::Ty { ty: fty }
634             }
635         }
636     }
637
638     fn error(&mut self) -> Ty<'tcx> {
639         self.errors_reported = true;
640         self.tcx().types.err
641     }
642
643     fn field_ty(
644         &mut self,
645         parent: &dyn fmt::Debug,
646         base_ty: PlaceTy<'tcx>,
647         field: Field,
648         location: Location,
649     ) -> Result<Ty<'tcx>, FieldAccessError> {
650         let tcx = self.tcx();
651
652         let (variant, substs) = match base_ty {
653             PlaceTy::Downcast {
654                 adt_def,
655                 substs,
656                 variant_index,
657             } => (&adt_def.variants[variant_index], substs),
658             PlaceTy::Ty { ty } => match ty.sty {
659                 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
660                     (&adt_def.variants[VariantIdx::new(0)], substs),
661                 ty::Closure(def_id, substs) => {
662                     return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
663                         Some(ty) => Ok(ty),
664                         None => Err(FieldAccessError::OutOfRange {
665                             field_count: substs.upvar_tys(def_id, tcx).count(),
666                         }),
667                     }
668                 }
669                 ty::Generator(def_id, substs, _) => {
670                     // Try pre-transform fields first (upvars and current state)
671                     if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
672                         return Ok(ty);
673                     }
674
675                     // Then try `field_tys` which contains all the fields, but it
676                     // requires the final optimized MIR.
677                     return match substs.field_tys(def_id, tcx).nth(field.index()) {
678                         Some(ty) => Ok(ty),
679                         None => Err(FieldAccessError::OutOfRange {
680                             field_count: substs.field_tys(def_id, tcx).count(),
681                         }),
682                     };
683                 }
684                 ty::Tuple(tys) => {
685                     return match tys.get(field.index()) {
686                         Some(&ty) => Ok(ty),
687                         None => Err(FieldAccessError::OutOfRange {
688                             field_count: tys.len(),
689                         }),
690                     }
691                 }
692                 _ => {
693                     return Ok(span_mirbug_and_err!(
694                         self,
695                         parent,
696                         "can't project out of {:?}",
697                         base_ty
698                     ))
699                 }
700             },
701         };
702
703         if let Some(field) = variant.fields.get(field.index()) {
704             Ok(self.cx.normalize(&field.ty(tcx, substs), location))
705         } else {
706             Err(FieldAccessError::OutOfRange {
707                 field_count: variant.fields.len(),
708             })
709         }
710     }
711 }
712
713 /// The MIR type checker. Visits the MIR and enforces all the
714 /// constraints needed for it to be valid and well-typed. Along the
715 /// way, it accrues region constraints -- these can later be used by
716 /// NLL region checking.
717 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
718     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
719     param_env: ty::ParamEnv<'gcx>,
720     last_span: Span,
721     mir: &'a Mir<'tcx>,
722     mir_def_id: DefId,
723     region_bound_pairs: &'a RegionBoundPairs<'tcx>,
724     implicit_region_bound: Option<ty::Region<'tcx>>,
725     reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
726     borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
727     universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
728 }
729
730 struct BorrowCheckContext<'a, 'tcx: 'a> {
731     universal_regions: &'a UniversalRegions<'tcx>,
732     location_table: &'a LocationTable,
733     all_facts: &'a mut Option<AllFacts>,
734     borrow_set: &'a BorrowSet<'tcx>,
735     constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
736 }
737
738 crate struct MirTypeckResults<'tcx> {
739     crate constraints: MirTypeckRegionConstraints<'tcx>,
740     crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
741 }
742
743 /// A collection of region constraints that must be satisfied for the
744 /// program to be considered well-typed.
745 crate struct MirTypeckRegionConstraints<'tcx> {
746     /// Maps from a `ty::Placeholder` to the corresponding
747     /// `PlaceholderIndex` bit that we will use for it.
748     ///
749     /// To keep everything in sync, do not insert this set
750     /// directly. Instead, use the `placeholder_region` helper.
751     crate placeholder_indices: PlaceholderIndices,
752
753     /// Each time we add a placeholder to `placeholder_indices`, we
754     /// also create a corresponding "representative" region vid for
755     /// that wraps it. This vector tracks those. This way, when we
756     /// convert the same `ty::RePlaceholder(p)` twice, we can map to
757     /// the same underlying `RegionVid`.
758     crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
759
760     /// In general, the type-checker is not responsible for enforcing
761     /// liveness constraints; this job falls to the region inferencer,
762     /// which performs a liveness analysis. However, in some limited
763     /// cases, the MIR type-checker creates temporary regions that do
764     /// not otherwise appear in the MIR -- in particular, the
765     /// late-bound regions that it instantiates at call-sites -- and
766     /// hence it must report on their liveness constraints.
767     crate liveness_constraints: LivenessValues<RegionVid>,
768
769     crate outlives_constraints: ConstraintSet,
770
771     crate closure_bounds_mapping:
772         FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
773
774     crate type_tests: Vec<TypeTest<'tcx>>,
775 }
776
777 impl MirTypeckRegionConstraints<'tcx> {
778     fn placeholder_region(
779         &mut self,
780         infcx: &InferCtxt<'_, '_, 'tcx>,
781         placeholder: ty::PlaceholderRegion,
782     ) -> ty::Region<'tcx> {
783         let placeholder_index = self.placeholder_indices.insert(placeholder);
784         match self.placeholder_index_to_region.get(placeholder_index) {
785             Some(&v) => v,
786             None => {
787                 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
788                 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
789                 self.placeholder_index_to_region.push(region);
790                 region
791             }
792         }
793     }
794 }
795
796 /// The `Locations` type summarizes *where* region constraints are
797 /// required to hold. Normally, this is at a particular point which
798 /// created the obligation, but for constraints that the user gave, we
799 /// want the constraint to hold at all points.
800 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
801 pub enum Locations {
802     /// Indicates that a type constraint should always be true. This
803     /// is particularly important in the new borrowck analysis for
804     /// things like the type of the return slot. Consider this
805     /// example:
806     ///
807     /// ```
808     /// fn foo<'a>(x: &'a u32) -> &'a u32 {
809     ///     let y = 22;
810     ///     return &y; // error
811     /// }
812     /// ```
813     ///
814     /// Here, we wind up with the signature from the return type being
815     /// something like `&'1 u32` where `'1` is a universal region. But
816     /// the type of the return slot `_0` is something like `&'2 u32`
817     /// where `'2` is an existential region variable. The type checker
818     /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
819     /// older NLL analysis, we required this only at the entry point
820     /// to the function. By the nature of the constraints, this wound
821     /// up propagating to all points reachable from start (because
822     /// `'1` -- as a universal region -- is live everywhere).  In the
823     /// newer analysis, though, this doesn't work: `_0` is considered
824     /// dead at the start (it has no usable value) and hence this type
825     /// equality is basically a no-op. Then, later on, when we do `_0
826     /// = &'3 y`, that region `'3` never winds up related to the
827     /// universal region `'1` and hence no error occurs. Therefore, we
828     /// use Locations::All instead, which ensures that the `'1` and
829     /// `'2` are equal everything. We also use this for other
830     /// user-given type annotations; e.g., if the user wrote `let mut
831     /// x: &'static u32 = ...`, we would ensure that all values
832     /// assigned to `x` are of `'static` lifetime.
833     ///
834     /// The span points to the place the constraint arose. For example,
835     /// it points to the type in a user-given type annotation. If
836     /// there's no sensible span then it's DUMMY_SP.
837     All(Span),
838
839     /// An outlives constraint that only has to hold at a single location,
840     /// usually it represents a point where references flow from one spot to
841     /// another (e.g., `x = y`)
842     Single(Location),
843 }
844
845 impl Locations {
846     pub fn from_location(&self) -> Option<Location> {
847         match self {
848             Locations::All(_) => None,
849             Locations::Single(from_location) => Some(*from_location),
850         }
851     }
852
853     /// Gets a span representing the location.
854     pub fn span(&self, mir: &Mir<'_>) -> Span {
855         match self {
856             Locations::All(span) => *span,
857             Locations::Single(l) => mir.source_info(*l).span,
858         }
859     }
860 }
861
862 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
863     fn new(
864         infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
865         mir: &'a Mir<'tcx>,
866         mir_def_id: DefId,
867         param_env: ty::ParamEnv<'gcx>,
868         region_bound_pairs: &'a RegionBoundPairs<'tcx>,
869         implicit_region_bound: Option<ty::Region<'tcx>>,
870         borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
871         universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
872     ) -> Self {
873         TypeChecker {
874             infcx,
875             last_span: DUMMY_SP,
876             mir,
877             mir_def_id,
878             param_env,
879             region_bound_pairs,
880             implicit_region_bound,
881             borrowck_context,
882             reported_errors: Default::default(),
883             universal_region_relations,
884         }
885     }
886
887     /// Given some operation `op` that manipulates types, proves
888     /// predicates, or otherwise uses the inference context, executes
889     /// `op` and then executes all the further obligations that `op`
890     /// returns. This will yield a set of outlives constraints amongst
891     /// regions which are extracted and stored as having occurred at
892     /// `locations`.
893     ///
894     /// **Any `rustc::infer` operations that might generate region
895     /// constraints should occur within this method so that those
896     /// constraints can be properly localized!**
897     fn fully_perform_op<R>(
898         &mut self,
899         locations: Locations,
900         category: ConstraintCategory,
901         op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
902     ) -> Fallible<R> {
903         let (r, opt_data) = op.fully_perform(self.infcx)?;
904
905         if let Some(data) = &opt_data {
906             self.push_region_constraints(locations, category, data);
907         }
908
909         Ok(r)
910     }
911
912     fn push_region_constraints(
913         &mut self,
914         locations: Locations,
915         category: ConstraintCategory,
916         data: &[QueryRegionConstraint<'tcx>],
917     ) {
918         debug!(
919             "push_region_constraints: constraints generated at {:?} are {:#?}",
920             locations, data
921         );
922
923         if let Some(ref mut borrowck_context) = self.borrowck_context {
924             constraint_conversion::ConstraintConversion::new(
925                 self.infcx,
926                 borrowck_context.universal_regions,
927                 self.region_bound_pairs,
928                 self.implicit_region_bound,
929                 self.param_env,
930                 locations,
931                 category,
932                 &mut borrowck_context.constraints,
933             ).convert_all(&data);
934         }
935     }
936
937     /// Convenient wrapper around `relate_tys::relate_types` -- see
938     /// that fn for docs.
939     fn relate_types(
940         &mut self,
941         a: Ty<'tcx>,
942         v: ty::Variance,
943         b: Ty<'tcx>,
944         locations: Locations,
945         category: ConstraintCategory,
946     ) -> Fallible<()> {
947         relate_tys::relate_types(
948             self.infcx,
949             a,
950             v,
951             b,
952             locations,
953             category,
954             self.borrowck_context.as_mut().map(|x| &mut **x),
955         )
956     }
957
958     fn sub_types(
959         &mut self,
960         sub: Ty<'tcx>,
961         sup: Ty<'tcx>,
962         locations: Locations,
963         category: ConstraintCategory,
964     ) -> Fallible<()> {
965         self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
966     }
967
968     /// Try to relate `sub <: sup`; if this fails, instantiate opaque
969     /// variables in `sub` with their inferred definitions and try
970     /// again. This is used for opaque types in places (e.g., `let x:
971     /// impl Foo = ..`).
972     fn sub_types_or_anon(
973         &mut self,
974         sub: Ty<'tcx>,
975         sup: Ty<'tcx>,
976         locations: Locations,
977         category: ConstraintCategory,
978     ) -> Fallible<()> {
979         if let Err(terr) = self.sub_types(sub, sup, locations, category) {
980             if let TyKind::Opaque(..) = sup.sty {
981                 // When you have `let x: impl Foo = ...` in a closure,
982                 // the resulting inferend values are stored with the
983                 // def-id of the base function.
984                 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
985                 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
986             } else {
987                 return Err(terr);
988             }
989         }
990         Ok(())
991     }
992
993     fn eq_types(
994         &mut self,
995         a: Ty<'tcx>,
996         b: Ty<'tcx>,
997         locations: Locations,
998         category: ConstraintCategory,
999     ) -> Fallible<()> {
1000         self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1001     }
1002
1003     fn relate_type_and_user_type(
1004         &mut self,
1005         a: Ty<'tcx>,
1006         v: ty::Variance,
1007         user_ty: &UserTypeProjection<'tcx>,
1008         locations: Locations,
1009         category: ConstraintCategory,
1010     ) -> Fallible<()> {
1011         debug!(
1012             "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1013             a, v, user_ty, locations,
1014         );
1015
1016         match user_ty.base {
1017             UserTypeAnnotation::Ty(canonical_ty) => {
1018                 let (ty, _) = self.infcx
1019                     .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_ty);
1020
1021                 // The `TypeRelating` code assumes that "unresolved inference
1022                 // variables" appear in the "a" side, so flip `Contravariant`
1023                 // ambient variance to get the right relationship.
1024                 let v1 = ty::Contravariant.xform(v);
1025
1026                 let tcx = self.infcx.tcx;
1027                 let ty = self.normalize(ty, locations);
1028
1029                 // We need to follow any provided projetions into the type.
1030                 //
1031                 // if we hit a ty var as we descend, then just skip the
1032                 // attempt to relate the mir local with any type.
1033                 #[derive(Debug)] struct HitTyVar;
1034                 let mut curr_projected_ty: Result<PlaceTy, HitTyVar>;
1035
1036                 curr_projected_ty = Ok(PlaceTy::from_ty(ty));
1037                 for proj in &user_ty.projs {
1038                     let projected_ty = if let Ok(projected_ty) = curr_projected_ty {
1039                         projected_ty
1040                     } else {
1041                         break;
1042                     };
1043                     curr_projected_ty = projected_ty.projection_ty_core(
1044                         tcx, proj, |this, field, &()| {
1045                             if this.to_ty(tcx).is_ty_var() {
1046                                 Err(HitTyVar)
1047                             } else {
1048                                 let ty = this.field_ty(tcx, field);
1049                                 Ok(self.normalize(ty, locations))
1050                             }
1051                         });
1052                 }
1053                 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1054                        user_ty.base, ty, user_ty.projs, curr_projected_ty);
1055
1056                 if let Ok(projected_ty) = curr_projected_ty {
1057                     let ty = projected_ty.to_ty(tcx);
1058                     self.relate_types(ty, v1, a, locations, category)?;
1059                 }
1060             }
1061             UserTypeAnnotation::TypeOf(def_id, canonical_substs) => {
1062                 let (
1063                     user_substs,
1064                     _,
1065                 ) = self.infcx
1066                     .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
1067
1068                 let projs = self.infcx.tcx.intern_projs(&user_ty.projs);
1069                 self.fully_perform_op(
1070                     locations,
1071                     category,
1072                     self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1073                         a, v, def_id, user_substs, projs,
1074                     )),
1075                 )?;
1076             }
1077         }
1078
1079         Ok(())
1080     }
1081
1082     fn eq_opaque_type_and_type(
1083         &mut self,
1084         revealed_ty: Ty<'tcx>,
1085         anon_ty: Ty<'tcx>,
1086         anon_owner_def_id: DefId,
1087         locations: Locations,
1088         category: ConstraintCategory,
1089     ) -> Fallible<()> {
1090         debug!(
1091             "eq_opaque_type_and_type( \
1092              revealed_ty={:?}, \
1093              anon_ty={:?})",
1094             revealed_ty, anon_ty
1095         );
1096         let infcx = self.infcx;
1097         let tcx = infcx.tcx;
1098         let param_env = self.param_env;
1099         debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1100         let opaque_type_map = self.fully_perform_op(
1101             locations,
1102             category,
1103             CustomTypeOp::new(
1104                 |infcx| {
1105                     let mut obligations = ObligationAccumulator::default();
1106
1107                     let dummy_body_id = ObligationCause::dummy().body_id;
1108                     let (output_ty, opaque_type_map) =
1109                         obligations.add(infcx.instantiate_opaque_types(
1110                             anon_owner_def_id,
1111                             dummy_body_id,
1112                             param_env,
1113                             &anon_ty,
1114                         ));
1115                     debug!(
1116                         "eq_opaque_type_and_type: \
1117                          instantiated output_ty={:?} \
1118                          opaque_type_map={:#?} \
1119                          revealed_ty={:?}",
1120                         output_ty, opaque_type_map, revealed_ty
1121                     );
1122                     obligations.add(infcx
1123                         .at(&ObligationCause::dummy(), param_env)
1124                         .eq(output_ty, revealed_ty)?);
1125
1126                     for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1127                         let opaque_defn_ty = tcx.type_of(opaque_def_id);
1128                         let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1129                         let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1130                         debug!(
1131                             "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1132                             opaque_decl.concrete_ty,
1133                             infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1134                             opaque_defn_ty
1135                         );
1136                         obligations.add(infcx
1137                             .at(&ObligationCause::dummy(), param_env)
1138                             .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1139                     }
1140
1141                     debug!("eq_opaque_type_and_type: equated");
1142
1143                     Ok(InferOk {
1144                         value: Some(opaque_type_map),
1145                         obligations: obligations.into_vec(),
1146                     })
1147                 },
1148                 || "input_output".to_string(),
1149             ),
1150         )?;
1151
1152         let universal_region_relations = match self.universal_region_relations {
1153             Some(rel) => rel,
1154             None => return Ok(()),
1155         };
1156
1157         // Finally, if we instantiated the anon types successfully, we
1158         // have to solve any bounds (e.g., `-> impl Iterator` needs to
1159         // prove that `T: Iterator` where `T` is the type we
1160         // instantiated it with).
1161         if let Some(opaque_type_map) = opaque_type_map {
1162             for (opaque_def_id, opaque_decl) in opaque_type_map {
1163                 self.fully_perform_op(
1164                     locations,
1165                     ConstraintCategory::OpaqueType,
1166                     CustomTypeOp::new(
1167                         |_cx| {
1168                             infcx.constrain_opaque_type(
1169                                 opaque_def_id,
1170                                 &opaque_decl,
1171                                 universal_region_relations,
1172                             );
1173                             Ok(InferOk {
1174                                 value: (),
1175                                 obligations: vec![],
1176                             })
1177                         },
1178                         || "opaque_type_map".to_string(),
1179                     ),
1180                 )?;
1181             }
1182         }
1183         Ok(())
1184     }
1185
1186     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1187         self.infcx.tcx
1188     }
1189
1190     fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1191         debug!("check_stmt: {:?}", stmt);
1192         let tcx = self.tcx();
1193         match stmt.kind {
1194             StatementKind::Assign(ref place, ref rv) => {
1195                 // Assignments to temporaries are not "interesting";
1196                 // they are not caused by the user, but rather artifacts
1197                 // of lowering. Assignments to other sorts of places *are* interesting
1198                 // though.
1199                 let category = match *place {
1200                     Place::Local(RETURN_PLACE) => if let Some(BorrowCheckContext {
1201                         universal_regions:
1202                             UniversalRegions {
1203                                 defining_ty: DefiningTy::Const(def_id, _),
1204                                 ..
1205                             },
1206                         ..
1207                     }) = self.borrowck_context
1208                     {
1209                         if tcx.is_static(*def_id).is_some() {
1210                             ConstraintCategory::UseAsStatic
1211                         } else {
1212                             ConstraintCategory::UseAsConst
1213                         }
1214                     } else {
1215                         ConstraintCategory::Return
1216                     },
1217                     Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1218                         ConstraintCategory::Boring
1219                     }
1220                     _ => ConstraintCategory::Assignment,
1221                 };
1222
1223                 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1224                 let rv_ty = rv.ty(mir, tcx);
1225                 if let Err(terr) =
1226                     self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1227                 {
1228                     span_mirbug!(
1229                         self,
1230                         stmt,
1231                         "bad assignment ({:?} = {:?}): {:?}",
1232                         place_ty,
1233                         rv_ty,
1234                         terr
1235                     );
1236                 }
1237
1238                 if let Some(user_ty) = self.rvalue_user_ty(rv) {
1239                     if let Err(terr) = self.relate_type_and_user_type(
1240                         rv_ty,
1241                         ty::Variance::Invariant,
1242                         &UserTypeProjection { base: user_ty, projs: vec![], },
1243                         location.to_locations(),
1244                         ConstraintCategory::Boring,
1245                     ) {
1246                         span_mirbug!(
1247                             self,
1248                             stmt,
1249                             "bad user type on rvalue ({:?} = {:?}): {:?}",
1250                             user_ty,
1251                             rv_ty,
1252                             terr
1253                         );
1254                     }
1255                 }
1256
1257                 self.check_rvalue(mir, rv, location);
1258                 if !self.tcx().features().unsized_locals {
1259                     let trait_ref = ty::TraitRef {
1260                         def_id: tcx.lang_items().sized_trait().unwrap(),
1261                         substs: tcx.mk_substs_trait(place_ty, &[]),
1262                     };
1263                     self.prove_trait_ref(
1264                         trait_ref,
1265                         location.to_locations(),
1266                         ConstraintCategory::SizedBound,
1267                     );
1268                 }
1269             }
1270             StatementKind::SetDiscriminant {
1271                 ref place,
1272                 variant_index,
1273             } => {
1274                 let place_type = place.ty(mir, tcx).to_ty(tcx);
1275                 let adt = match place_type.sty {
1276                     TyKind::Adt(adt, _) if adt.is_enum() => adt,
1277                     _ => {
1278                         span_bug!(
1279                             stmt.source_info.span,
1280                             "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1281                             place,
1282                             variant_index
1283                         );
1284                     }
1285                 };
1286                 if variant_index.as_usize() >= adt.variants.len() {
1287                     span_bug!(
1288                         stmt.source_info.span,
1289                         "bad set discriminant ({:?} = {:?}): value of of range",
1290                         place,
1291                         variant_index
1292                     );
1293                 };
1294             }
1295             StatementKind::AscribeUserType(ref place, variance, box ref c_ty) => {
1296                 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1297                 if let Err(terr) = self.relate_type_and_user_type(
1298                     place_ty,
1299                     variance,
1300                     c_ty,
1301                     Locations::All(stmt.source_info.span),
1302                     ConstraintCategory::TypeAnnotation,
1303                 ) {
1304                     span_mirbug!(
1305                         self,
1306                         stmt,
1307                         "bad type assert ({:?} <: {:?}): {:?}",
1308                         place_ty,
1309                         c_ty,
1310                         terr
1311                     );
1312                 }
1313             }
1314             StatementKind::FakeRead(..)
1315             | StatementKind::StorageLive(..)
1316             | StatementKind::StorageDead(..)
1317             | StatementKind::InlineAsm { .. }
1318             | StatementKind::Retag { .. }
1319             | StatementKind::EscapeToRaw { .. }
1320             | StatementKind::Nop => {}
1321         }
1322     }
1323
1324     fn check_terminator(
1325         &mut self,
1326         mir: &Mir<'tcx>,
1327         term: &Terminator<'tcx>,
1328         term_location: Location,
1329     ) {
1330         debug!("check_terminator: {:?}", term);
1331         let tcx = self.tcx();
1332         match term.kind {
1333             TerminatorKind::Goto { .. }
1334             | TerminatorKind::Resume
1335             | TerminatorKind::Abort
1336             | TerminatorKind::Return
1337             | TerminatorKind::GeneratorDrop
1338             | TerminatorKind::Unreachable
1339             | TerminatorKind::Drop { .. }
1340             | TerminatorKind::FalseEdges { .. }
1341             | TerminatorKind::FalseUnwind { .. } => {
1342                 // no checks needed for these
1343             }
1344
1345             TerminatorKind::DropAndReplace {
1346                 ref location,
1347                 ref value,
1348                 target: _,
1349                 unwind: _,
1350             } => {
1351                 let place_ty = location.ty(mir, tcx).to_ty(tcx);
1352                 let rv_ty = value.ty(mir, tcx);
1353
1354                 let locations = term_location.to_locations();
1355                 if let Err(terr) =
1356                     self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1357                 {
1358                     span_mirbug!(
1359                         self,
1360                         term,
1361                         "bad DropAndReplace ({:?} = {:?}): {:?}",
1362                         place_ty,
1363                         rv_ty,
1364                         terr
1365                     );
1366                 }
1367             }
1368             TerminatorKind::SwitchInt {
1369                 ref discr,
1370                 switch_ty,
1371                 ..
1372             } => {
1373                 let discr_ty = discr.ty(mir, tcx);
1374                 if let Err(terr) = self.sub_types(
1375                     discr_ty,
1376                     switch_ty,
1377                     term_location.to_locations(),
1378                     ConstraintCategory::Assignment,
1379                 ) {
1380                     span_mirbug!(
1381                         self,
1382                         term,
1383                         "bad SwitchInt ({:?} on {:?}): {:?}",
1384                         switch_ty,
1385                         discr_ty,
1386                         terr
1387                     );
1388                 }
1389                 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1390                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1391                 }
1392                 // FIXME: check the values
1393             }
1394             TerminatorKind::Call {
1395                 ref func,
1396                 ref args,
1397                 ref destination,
1398                 from_hir_call,
1399                 ..
1400             } => {
1401                 let func_ty = func.ty(mir, tcx);
1402                 debug!("check_terminator: call, func_ty={:?}", func_ty);
1403                 let sig = match func_ty.sty {
1404                     ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1405                     _ => {
1406                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1407                         return;
1408                     }
1409                 };
1410                 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1411                     term.source_info.span,
1412                     LateBoundRegionConversionTime::FnCall,
1413                     &sig,
1414                 );
1415                 let sig = self.normalize(sig, term_location);
1416                 self.check_call_dest(mir, term, &sig, destination, term_location);
1417
1418                 self.prove_predicates(
1419                     sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1420                     term_location.to_locations(),
1421                     ConstraintCategory::Boring,
1422                 );
1423
1424                 // The ordinary liveness rules will ensure that all
1425                 // regions in the type of the callee are live here. We
1426                 // then further constrain the late-bound regions that
1427                 // were instantiated at the call site to be live as
1428                 // well. The resulting is that all the input (and
1429                 // output) types in the signature must be live, since
1430                 // all the inputs that fed into it were live.
1431                 for &late_bound_region in map.values() {
1432                     if let Some(ref mut borrowck_context) = self.borrowck_context {
1433                         let region_vid = borrowck_context
1434                             .universal_regions
1435                             .to_region_vid(late_bound_region);
1436                         borrowck_context
1437                             .constraints
1438                             .liveness_constraints
1439                             .add_element(region_vid, term_location);
1440                     }
1441                 }
1442
1443                 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1444             }
1445             TerminatorKind::Assert {
1446                 ref cond, ref msg, ..
1447             } => {
1448                 let cond_ty = cond.ty(mir, tcx);
1449                 if cond_ty != tcx.types.bool {
1450                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1451                 }
1452
1453                 if let BoundsCheck { ref len, ref index } = *msg {
1454                     if len.ty(mir, tcx) != tcx.types.usize {
1455                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1456                     }
1457                     if index.ty(mir, tcx) != tcx.types.usize {
1458                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1459                     }
1460                 }
1461             }
1462             TerminatorKind::Yield { ref value, .. } => {
1463                 let value_ty = value.ty(mir, tcx);
1464                 match mir.yield_ty {
1465                     None => span_mirbug!(self, term, "yield in non-generator"),
1466                     Some(ty) => {
1467                         if let Err(terr) = self.sub_types(
1468                             value_ty,
1469                             ty,
1470                             term_location.to_locations(),
1471                             ConstraintCategory::Yield,
1472                         ) {
1473                             span_mirbug!(
1474                                 self,
1475                                 term,
1476                                 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1477                                 value_ty,
1478                                 ty,
1479                                 terr
1480                             );
1481                         }
1482                     }
1483                 }
1484             }
1485         }
1486     }
1487
1488     fn check_call_dest(
1489         &mut self,
1490         mir: &Mir<'tcx>,
1491         term: &Terminator<'tcx>,
1492         sig: &ty::FnSig<'tcx>,
1493         destination: &Option<(Place<'tcx>, BasicBlock)>,
1494         term_location: Location,
1495     ) {
1496         let tcx = self.tcx();
1497         match *destination {
1498             Some((ref dest, _target_block)) => {
1499                 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1500                 let category = match *dest {
1501                     Place::Local(RETURN_PLACE) => {
1502                         if let Some(BorrowCheckContext {
1503                             universal_regions:
1504                                 UniversalRegions {
1505                                     defining_ty: DefiningTy::Const(def_id, _),
1506                                     ..
1507                                 },
1508                             ..
1509                         }) = self.borrowck_context
1510                         {
1511                             if tcx.is_static(*def_id).is_some() {
1512                                 ConstraintCategory::UseAsStatic
1513                             } else {
1514                                 ConstraintCategory::UseAsConst
1515                             }
1516                         } else {
1517                             ConstraintCategory::Return
1518                         }
1519                     }
1520                     Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1521                         ConstraintCategory::Boring
1522                     }
1523                     _ => ConstraintCategory::Assignment,
1524                 };
1525
1526                 let locations = term_location.to_locations();
1527
1528                 if let Err(terr) =
1529                     self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1530                 {
1531                     span_mirbug!(
1532                         self,
1533                         term,
1534                         "call dest mismatch ({:?} <- {:?}): {:?}",
1535                         dest_ty,
1536                         sig.output(),
1537                         terr
1538                     );
1539                 }
1540
1541                 // When `#![feature(unsized_locals)]` is not enabled,
1542                 // this check is done at `check_local`.
1543                 if self.tcx().features().unsized_locals {
1544                     let span = term.source_info.span;
1545                     self.ensure_place_sized(dest_ty, span);
1546                 }
1547             }
1548             None => {
1549                 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1550                 if !sig.output().is_never() {
1551                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1552                 }
1553             }
1554         }
1555     }
1556
1557     fn check_call_inputs(
1558         &mut self,
1559         mir: &Mir<'tcx>,
1560         term: &Terminator<'tcx>,
1561         sig: &ty::FnSig<'tcx>,
1562         args: &[Operand<'tcx>],
1563         term_location: Location,
1564         from_hir_call: bool,
1565     ) {
1566         debug!("check_call_inputs({:?}, {:?})", sig, args);
1567         if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1568             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1569         }
1570         for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1571             let op_arg_ty = op_arg.ty(mir, self.tcx());
1572             let category = if from_hir_call {
1573                 ConstraintCategory::CallArgument
1574             } else {
1575                 ConstraintCategory::Boring
1576             };
1577             if let Err(terr) =
1578                 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1579             {
1580                 span_mirbug!(
1581                     self,
1582                     term,
1583                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1584                     n,
1585                     fn_arg,
1586                     op_arg_ty,
1587                     terr
1588                 );
1589             }
1590         }
1591     }
1592
1593     fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1594         let is_cleanup = block_data.is_cleanup;
1595         self.last_span = block_data.terminator().source_info.span;
1596         match block_data.terminator().kind {
1597             TerminatorKind::Goto { target } => {
1598                 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1599             }
1600             TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1601                 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1602             },
1603             TerminatorKind::Resume => if !is_cleanup {
1604                 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1605             },
1606             TerminatorKind::Abort => if !is_cleanup {
1607                 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1608             },
1609             TerminatorKind::Return => if is_cleanup {
1610                 span_mirbug!(self, block_data, "return on cleanup block")
1611             },
1612             TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1613                 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1614             },
1615             TerminatorKind::Yield { resume, drop, .. } => {
1616                 if is_cleanup {
1617                     span_mirbug!(self, block_data, "yield in cleanup block")
1618                 }
1619                 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1620                 if let Some(drop) = drop {
1621                     self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1622                 }
1623             }
1624             TerminatorKind::Unreachable => {}
1625             TerminatorKind::Drop { target, unwind, .. }
1626             | TerminatorKind::DropAndReplace { target, unwind, .. }
1627             | TerminatorKind::Assert {
1628                 target,
1629                 cleanup: unwind,
1630                 ..
1631             } => {
1632                 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1633                 if let Some(unwind) = unwind {
1634                     if is_cleanup {
1635                         span_mirbug!(self, block_data, "unwind on cleanup block")
1636                     }
1637                     self.assert_iscleanup(mir, block_data, unwind, true);
1638                 }
1639             }
1640             TerminatorKind::Call {
1641                 ref destination,
1642                 cleanup,
1643                 ..
1644             } => {
1645                 if let &Some((_, target)) = destination {
1646                     self.assert_iscleanup(mir, block_data, target, is_cleanup);
1647                 }
1648                 if let Some(cleanup) = cleanup {
1649                     if is_cleanup {
1650                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1651                     }
1652                     self.assert_iscleanup(mir, block_data, cleanup, true);
1653                 }
1654             }
1655             TerminatorKind::FalseEdges {
1656                 real_target,
1657                 ref imaginary_targets,
1658             } => {
1659                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1660                 for target in imaginary_targets {
1661                     self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1662                 }
1663             }
1664             TerminatorKind::FalseUnwind {
1665                 real_target,
1666                 unwind,
1667             } => {
1668                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1669                 if let Some(unwind) = unwind {
1670                     if is_cleanup {
1671                         span_mirbug!(
1672                             self,
1673                             block_data,
1674                             "cleanup in cleanup block via false unwind"
1675                         );
1676                     }
1677                     self.assert_iscleanup(mir, block_data, unwind, true);
1678                 }
1679             }
1680         }
1681     }
1682
1683     fn assert_iscleanup(
1684         &mut self,
1685         mir: &Mir<'tcx>,
1686         ctxt: &dyn fmt::Debug,
1687         bb: BasicBlock,
1688         iscleanuppad: bool,
1689     ) {
1690         if mir[bb].is_cleanup != iscleanuppad {
1691             span_mirbug!(
1692                 self,
1693                 ctxt,
1694                 "cleanuppad mismatch: {:?} should be {:?}",
1695                 bb,
1696                 iscleanuppad
1697             );
1698         }
1699     }
1700
1701     fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1702         match mir.local_kind(local) {
1703             LocalKind::ReturnPointer | LocalKind::Arg => {
1704                 // return values of normal functions are required to be
1705                 // sized by typeck, but return values of ADT constructors are
1706                 // not because we don't include a `Self: Sized` bounds on them.
1707                 //
1708                 // Unbound parts of arguments were never required to be Sized
1709                 // - maybe we should make that a warning.
1710                 return;
1711             }
1712             LocalKind::Var | LocalKind::Temp => {}
1713         }
1714
1715         // When `#![feature(unsized_locals)]` is enabled, only function calls
1716         // and nullary ops are checked in `check_call_dest`.
1717         if !self.tcx().features().unsized_locals {
1718             let span = local_decl.source_info.span;
1719             let ty = local_decl.ty;
1720             self.ensure_place_sized(ty, span);
1721         }
1722     }
1723
1724     fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1725         let tcx = self.tcx();
1726
1727         // Erase the regions from `ty` to get a global type.  The
1728         // `Sized` bound in no way depends on precise regions, so this
1729         // shouldn't affect `is_sized`.
1730         let gcx = tcx.global_tcx();
1731         let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1732         if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1733             // in current MIR construction, all non-control-flow rvalue
1734             // expressions evaluate through `as_temp` or `into` a return
1735             // slot or local, so to find all unsized rvalues it is enough
1736             // to check all temps, return slots and locals.
1737             if let None = self.reported_errors.replace((ty, span)) {
1738                 let mut diag = struct_span_err!(
1739                     self.tcx().sess,
1740                     span,
1741                     E0161,
1742                     "cannot move a value of type {0}: the size of {0} \
1743                      cannot be statically determined",
1744                     ty
1745                 );
1746
1747                 // While this is located in `nll::typeck` this error is not
1748                 // an NLL error, it's a required check to prevent creation
1749                 // of unsized rvalues in certain cases:
1750                 // * operand of a box expression
1751                 // * callee in a call expression
1752                 diag.emit();
1753             }
1754         }
1755     }
1756
1757     fn aggregate_field_ty(
1758         &mut self,
1759         ak: &AggregateKind<'tcx>,
1760         field_index: usize,
1761         location: Location,
1762     ) -> Result<Ty<'tcx>, FieldAccessError> {
1763         let tcx = self.tcx();
1764
1765         match *ak {
1766             AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1767                 let variant = &def.variants[variant_index];
1768                 let adj_field_index = active_field_index.unwrap_or(field_index);
1769                 if let Some(field) = variant.fields.get(adj_field_index) {
1770                     Ok(self.normalize(field.ty(tcx, substs), location))
1771                 } else {
1772                     Err(FieldAccessError::OutOfRange {
1773                         field_count: variant.fields.len(),
1774                     })
1775                 }
1776             }
1777             AggregateKind::Closure(def_id, substs) => {
1778                 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1779                     Some(ty) => Ok(ty),
1780                     None => Err(FieldAccessError::OutOfRange {
1781                         field_count: substs.upvar_tys(def_id, tcx).count(),
1782                     }),
1783                 }
1784             }
1785             AggregateKind::Generator(def_id, substs, _) => {
1786                 // Try pre-transform fields first (upvars and current state)
1787                 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1788                     Ok(ty)
1789                 } else {
1790                     // Then try `field_tys` which contains all the fields, but it
1791                     // requires the final optimized MIR.
1792                     match substs.field_tys(def_id, tcx).nth(field_index) {
1793                         Some(ty) => Ok(ty),
1794                         None => Err(FieldAccessError::OutOfRange {
1795                             field_count: substs.field_tys(def_id, tcx).count(),
1796                         }),
1797                     }
1798                 }
1799             }
1800             AggregateKind::Array(ty) => Ok(ty),
1801             AggregateKind::Tuple => {
1802                 unreachable!("This should have been covered in check_rvalues");
1803             }
1804         }
1805     }
1806
1807     fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1808         let tcx = self.tcx();
1809
1810         match rvalue {
1811             Rvalue::Aggregate(ak, ops) => {
1812                 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1813             }
1814
1815             Rvalue::Repeat(operand, len) => if *len > 1 {
1816                 let operand_ty = operand.ty(mir, tcx);
1817
1818                 let trait_ref = ty::TraitRef {
1819                     def_id: tcx.lang_items().copy_trait().unwrap(),
1820                     substs: tcx.mk_substs_trait(operand_ty, &[]),
1821                 };
1822
1823                 self.prove_trait_ref(
1824                     trait_ref,
1825                     location.to_locations(),
1826                     ConstraintCategory::CopyBound,
1827                 );
1828             },
1829
1830             Rvalue::NullaryOp(_, ty) => {
1831                 // Even with unsized locals cannot box an unsized value.
1832                 if self.tcx().features().unsized_locals {
1833                     let span = mir.source_info(location).span;
1834                     self.ensure_place_sized(ty, span);
1835                 }
1836
1837                 let trait_ref = ty::TraitRef {
1838                     def_id: tcx.lang_items().sized_trait().unwrap(),
1839                     substs: tcx.mk_substs_trait(ty, &[]),
1840                 };
1841
1842                 self.prove_trait_ref(
1843                     trait_ref,
1844                     location.to_locations(),
1845                     ConstraintCategory::SizedBound,
1846                 );
1847             }
1848
1849             Rvalue::Cast(cast_kind, op, ty) => {
1850                 match cast_kind {
1851                     CastKind::ReifyFnPointer => {
1852                         let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1853
1854                         // The type that we see in the fcx is like
1855                         // `foo::<'a, 'b>`, where `foo` is the path to a
1856                         // function definition. When we extract the
1857                         // signature, it comes from the `fn_sig` query,
1858                         // and hence may contain unnormalized results.
1859                         let fn_sig = self.normalize(fn_sig, location);
1860
1861                         let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1862
1863                         if let Err(terr) = self.eq_types(
1864                             ty_fn_ptr_from,
1865                             ty,
1866                             location.to_locations(),
1867                             ConstraintCategory::Cast,
1868                         ) {
1869                             span_mirbug!(
1870                                 self,
1871                                 rvalue,
1872                                 "equating {:?} with {:?} yields {:?}",
1873                                 ty_fn_ptr_from,
1874                                 ty,
1875                                 terr
1876                             );
1877                         }
1878                     }
1879
1880                     CastKind::ClosureFnPointer => {
1881                         let sig = match op.ty(mir, tcx).sty {
1882                             ty::Closure(def_id, substs) => {
1883                                 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1884                             }
1885                             _ => bug!(),
1886                         };
1887                         let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1888
1889                         if let Err(terr) = self.eq_types(
1890                             ty_fn_ptr_from,
1891                             ty,
1892                             location.to_locations(),
1893                             ConstraintCategory::Cast,
1894                         ) {
1895                             span_mirbug!(
1896                                 self,
1897                                 rvalue,
1898                                 "equating {:?} with {:?} yields {:?}",
1899                                 ty_fn_ptr_from,
1900                                 ty,
1901                                 terr
1902                             );
1903                         }
1904                     }
1905
1906                     CastKind::UnsafeFnPointer => {
1907                         let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1908
1909                         // The type that we see in the fcx is like
1910                         // `foo::<'a, 'b>`, where `foo` is the path to a
1911                         // function definition. When we extract the
1912                         // signature, it comes from the `fn_sig` query,
1913                         // and hence may contain unnormalized results.
1914                         let fn_sig = self.normalize(fn_sig, location);
1915
1916                         let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1917
1918                         if let Err(terr) = self.eq_types(
1919                             ty_fn_ptr_from,
1920                             ty,
1921                             location.to_locations(),
1922                             ConstraintCategory::Cast,
1923                         ) {
1924                             span_mirbug!(
1925                                 self,
1926                                 rvalue,
1927                                 "equating {:?} with {:?} yields {:?}",
1928                                 ty_fn_ptr_from,
1929                                 ty,
1930                                 terr
1931                             );
1932                         }
1933                     }
1934
1935                     CastKind::Unsize => {
1936                         let &ty = ty;
1937                         let trait_ref = ty::TraitRef {
1938                             def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1939                             substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1940                         };
1941
1942                         self.prove_trait_ref(
1943                             trait_ref,
1944                             location.to_locations(),
1945                             ConstraintCategory::Cast,
1946                         );
1947                     }
1948
1949                     CastKind::Misc => {}
1950                 }
1951             }
1952
1953             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1954                 self.add_reborrow_constraint(location, region, borrowed_place);
1955             }
1956
1957             // FIXME: These other cases have to be implemented in future PRs
1958             Rvalue::Use(..)
1959             | Rvalue::Len(..)
1960             | Rvalue::BinaryOp(..)
1961             | Rvalue::CheckedBinaryOp(..)
1962             | Rvalue::UnaryOp(..)
1963             | Rvalue::Discriminant(..) => {}
1964         }
1965     }
1966
1967     /// If this rvalue supports a user-given type annotation, then
1968     /// extract and return it. This represents the final type of the
1969     /// rvalue and will be unified with the inferred type.
1970     fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotation<'tcx>> {
1971         match rvalue {
1972             Rvalue::Use(_)
1973             | Rvalue::Repeat(..)
1974             | Rvalue::Ref(..)
1975             | Rvalue::Len(..)
1976             | Rvalue::Cast(..)
1977             | Rvalue::BinaryOp(..)
1978             | Rvalue::CheckedBinaryOp(..)
1979             | Rvalue::NullaryOp(..)
1980             | Rvalue::UnaryOp(..)
1981             | Rvalue::Discriminant(..) => None,
1982
1983             Rvalue::Aggregate(aggregate, _) => match **aggregate {
1984                 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
1985                 AggregateKind::Array(_) => None,
1986                 AggregateKind::Tuple => None,
1987                 AggregateKind::Closure(_, _) => None,
1988                 AggregateKind::Generator(_, _, _) => None,
1989             },
1990         }
1991     }
1992
1993     fn check_aggregate_rvalue(
1994         &mut self,
1995         mir: &Mir<'tcx>,
1996         rvalue: &Rvalue<'tcx>,
1997         aggregate_kind: &AggregateKind<'tcx>,
1998         operands: &[Operand<'tcx>],
1999         location: Location,
2000     ) {
2001         let tcx = self.tcx();
2002
2003         self.prove_aggregate_predicates(aggregate_kind, location);
2004
2005         if *aggregate_kind == AggregateKind::Tuple {
2006             // tuple rvalue field type is always the type of the op. Nothing to check here.
2007             return;
2008         }
2009
2010         for (i, operand) in operands.iter().enumerate() {
2011             let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2012                 Ok(field_ty) => field_ty,
2013                 Err(FieldAccessError::OutOfRange { field_count }) => {
2014                     span_mirbug!(
2015                         self,
2016                         rvalue,
2017                         "accessed field #{} but variant only has {}",
2018                         i,
2019                         field_count
2020                     );
2021                     continue;
2022                 }
2023             };
2024             let operand_ty = operand.ty(mir, tcx);
2025
2026             if let Err(terr) = self.sub_types(
2027                 operand_ty,
2028                 field_ty,
2029                 location.to_locations(),
2030                 ConstraintCategory::Boring,
2031             ) {
2032                 span_mirbug!(
2033                     self,
2034                     rvalue,
2035                     "{:?} is not a subtype of {:?}: {:?}",
2036                     operand_ty,
2037                     field_ty,
2038                     terr
2039                 );
2040             }
2041         }
2042     }
2043
2044     /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
2045     ///
2046     /// # Parameters
2047     ///
2048     /// - `location`: the location `L` where the borrow expression occurs
2049     /// - `borrow_region`: the region `'a` associated with the borrow
2050     /// - `borrowed_place`: the place `P` being borrowed
2051     fn add_reborrow_constraint(
2052         &mut self,
2053         location: Location,
2054         borrow_region: ty::Region<'tcx>,
2055         borrowed_place: &Place<'tcx>,
2056     ) {
2057         // These constraints are only meaningful during borrowck:
2058         let BorrowCheckContext {
2059             borrow_set,
2060             location_table,
2061             all_facts,
2062             constraints,
2063             ..
2064         } = match self.borrowck_context {
2065             Some(ref mut borrowck_context) => borrowck_context,
2066             None => return,
2067         };
2068
2069         // In Polonius mode, we also push a `borrow_region` fact
2070         // linking the loan to the region (in some cases, though,
2071         // there is no loan associated with this borrow expression --
2072         // that occurs when we are borrowing an unsafe place, for
2073         // example).
2074         if let Some(all_facts) = all_facts {
2075             if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2076                 let region_vid = borrow_region.to_region_vid();
2077                 all_facts.borrow_region.push((
2078                     region_vid,
2079                     *borrow_index,
2080                     location_table.mid_index(location),
2081                 ));
2082             }
2083         }
2084
2085         // If we are reborrowing the referent of another reference, we
2086         // need to add outlives relationships. In a case like `&mut
2087         // *p`, where the `p` has type `&'b mut Foo`, for example, we
2088         // need to ensure that `'b: 'a`.
2089
2090         let mut borrowed_place = borrowed_place;
2091
2092         debug!(
2093             "add_reborrow_constraint({:?}, {:?}, {:?})",
2094             location, borrow_region, borrowed_place
2095         );
2096         while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2097             debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2098
2099             match *elem {
2100                 ProjectionElem::Deref => {
2101                     let tcx = self.infcx.tcx;
2102                     let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
2103
2104                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2105                     match base_ty.sty {
2106                         ty::Ref(ref_region, _, mutbl) => {
2107                             constraints.outlives_constraints.push(OutlivesConstraint {
2108                                 sup: ref_region.to_region_vid(),
2109                                 sub: borrow_region.to_region_vid(),
2110                                 locations: location.to_locations(),
2111                                 category: ConstraintCategory::Boring,
2112                             });
2113
2114                             match mutbl {
2115                                 hir::Mutability::MutImmutable => {
2116                                     // Immutable reference. We don't need the base
2117                                     // to be valid for the entire lifetime of
2118                                     // the borrow.
2119                                     break;
2120                                 }
2121                                 hir::Mutability::MutMutable => {
2122                                     // Mutable reference. We *do* need the base
2123                                     // to be valid, because after the base becomes
2124                                     // invalid, someone else can use our mutable deref.
2125
2126                                     // This is in order to make the following function
2127                                     // illegal:
2128                                     // ```
2129                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2130                                     //     &mut *x
2131                                     // }
2132                                     // ```
2133                                     //
2134                                     // As otherwise you could clone `&mut T` using the
2135                                     // following function:
2136                                     // ```
2137                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
2138                                     //     let my_clone = unsafe_deref(&'a x);
2139                                     //     ENDREGION 'a;
2140                                     //     (my_clone, x)
2141                                     // }
2142                                     // ```
2143                                 }
2144                             }
2145                         }
2146                         ty::RawPtr(..) => {
2147                             // deref of raw pointer, guaranteed to be valid
2148                             break;
2149                         }
2150                         ty::Adt(def, _) if def.is_box() => {
2151                             // deref of `Box`, need the base to be valid - propagate
2152                         }
2153                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2154                     }
2155                 }
2156                 ProjectionElem::Field(..)
2157                 | ProjectionElem::Downcast(..)
2158                 | ProjectionElem::Index(..)
2159                 | ProjectionElem::ConstantIndex { .. }
2160                 | ProjectionElem::Subslice { .. } => {
2161                     // other field access
2162                 }
2163             }
2164
2165             // The "propagate" case. We need to check that our base is valid
2166             // for the borrow's lifetime.
2167             borrowed_place = base;
2168         }
2169     }
2170
2171     fn prove_aggregate_predicates(
2172         &mut self,
2173         aggregate_kind: &AggregateKind<'tcx>,
2174         location: Location,
2175     ) {
2176         let tcx = self.tcx();
2177
2178         debug!(
2179             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2180             aggregate_kind, location
2181         );
2182
2183         let instantiated_predicates = match aggregate_kind {
2184             AggregateKind::Adt(def, _, substs, _, _) => {
2185                 tcx.predicates_of(def.did).instantiate(tcx, substs)
2186             }
2187
2188             // For closures, we have some **extra requirements** we
2189             //
2190             // have to check. In particular, in their upvars and
2191             // signatures, closures often reference various regions
2192             // from the surrounding function -- we call those the
2193             // closure's free regions. When we borrow-check (and hence
2194             // region-check) closures, we may find that the closure
2195             // requires certain relationships between those free
2196             // regions. However, because those free regions refer to
2197             // portions of the CFG of their caller, the closure is not
2198             // in a position to verify those relationships. In that
2199             // case, the requirements get "propagated" to us, and so
2200             // we have to solve them here where we instantiate the
2201             // closure.
2202             //
2203             // Despite the opacity of the previous parapgrah, this is
2204             // actually relatively easy to understand in terms of the
2205             // desugaring. A closure gets desugared to a struct, and
2206             // these extra requirements are basically like where
2207             // clauses on the struct.
2208             AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2209             | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2210                 self.prove_closure_bounds(tcx, *def_id, substs, location)
2211             }
2212
2213             AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2214         };
2215
2216         self.normalize_and_prove_instantiated_predicates(
2217             instantiated_predicates,
2218             location.to_locations(),
2219         );
2220     }
2221
2222     fn prove_closure_bounds(
2223         &mut self,
2224         tcx: TyCtxt<'a, 'gcx, 'tcx>,
2225         def_id: DefId,
2226         substs: &'tcx Substs<'tcx>,
2227         location: Location,
2228     ) -> ty::InstantiatedPredicates<'tcx> {
2229         if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2230             let closure_constraints =
2231                 closure_region_requirements.apply_requirements(tcx, location, def_id, substs);
2232
2233             if let Some(ref mut borrowck_context) = self.borrowck_context {
2234                 let bounds_mapping = closure_constraints
2235                     .iter()
2236                     .enumerate()
2237                     .filter_map(|(idx, constraint)| {
2238                         let ty::OutlivesPredicate(k1, r2) =
2239                             constraint.no_bound_vars().unwrap_or_else(|| {
2240                                 bug!("query_constraint {:?} contained bound vars", constraint,);
2241                             });
2242
2243                         match k1.unpack() {
2244                             UnpackedKind::Lifetime(r1) => {
2245                                 // constraint is r1: r2
2246                                 let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
2247                                 let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
2248                                 let outlives_requirements =
2249                                     &closure_region_requirements.outlives_requirements[idx];
2250                                 Some((
2251                                     (r1_vid, r2_vid),
2252                                     (
2253                                         outlives_requirements.category,
2254                                         outlives_requirements.blame_span,
2255                                     ),
2256                                 ))
2257                             }
2258                             UnpackedKind::Type(_) => None,
2259                         }
2260                     })
2261                     .collect();
2262
2263                 let existing = borrowck_context
2264                     .constraints
2265                     .closure_bounds_mapping
2266                     .insert(location, bounds_mapping);
2267                 assert!(
2268                     existing.is_none(),
2269                     "Multiple closures at the same location."
2270                 );
2271             }
2272
2273             self.push_region_constraints(
2274                 location.to_locations(),
2275                 ConstraintCategory::ClosureBounds,
2276                 &closure_constraints,
2277             );
2278         }
2279
2280         tcx.predicates_of(def_id).instantiate(tcx, substs)
2281     }
2282
2283     fn prove_trait_ref(
2284         &mut self,
2285         trait_ref: ty::TraitRef<'tcx>,
2286         locations: Locations,
2287         category: ConstraintCategory,
2288     ) {
2289         self.prove_predicates(
2290             Some(ty::Predicate::Trait(
2291                 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2292             )),
2293             locations,
2294             category,
2295         );
2296     }
2297
2298     fn normalize_and_prove_instantiated_predicates(
2299         &mut self,
2300         instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2301         locations: Locations,
2302     ) {
2303         for predicate in instantiated_predicates.predicates {
2304             let predicate = self.normalize(predicate, locations);
2305             self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2306         }
2307     }
2308
2309     fn prove_predicates(
2310         &mut self,
2311         predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2312         locations: Locations,
2313         category: ConstraintCategory,
2314     ) {
2315         for predicate in predicates {
2316             debug!(
2317                 "prove_predicates(predicate={:?}, locations={:?})",
2318                 predicate, locations,
2319             );
2320
2321             self.prove_predicate(predicate, locations, category);
2322         }
2323     }
2324
2325     fn prove_predicate(
2326         &mut self,
2327         predicate: ty::Predicate<'tcx>,
2328         locations: Locations,
2329         category: ConstraintCategory,
2330     ) {
2331         debug!(
2332             "prove_predicate(predicate={:?}, location={:?})",
2333             predicate, locations,
2334         );
2335
2336         let param_env = self.param_env;
2337         self.fully_perform_op(
2338             locations,
2339             category,
2340             param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2341         ).unwrap_or_else(|NoSolution| {
2342             span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2343         })
2344     }
2345
2346     fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2347         self.last_span = mir.span;
2348         debug!("run_on_mir: {:?}", mir.span);
2349
2350         for (local, local_decl) in mir.local_decls.iter_enumerated() {
2351             self.check_local(mir, local, local_decl);
2352         }
2353
2354         for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2355             let mut location = Location {
2356                 block,
2357                 statement_index: 0,
2358             };
2359             for stmt in &block_data.statements {
2360                 if !stmt.source_info.span.is_dummy() {
2361                     self.last_span = stmt.source_info.span;
2362                 }
2363                 self.check_stmt(mir, stmt, location);
2364                 location.statement_index += 1;
2365             }
2366
2367             self.check_terminator(mir, block_data.terminator(), location);
2368             self.check_iscleanup(mir, block_data);
2369         }
2370     }
2371
2372     fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2373     where
2374         T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2375     {
2376         debug!("normalize(value={:?}, location={:?})", value, location);
2377         let param_env = self.param_env;
2378         self.fully_perform_op(
2379             location.to_locations(),
2380             ConstraintCategory::Boring,
2381             param_env.and(type_op::normalize::Normalize::new(value)),
2382         ).unwrap_or_else(|NoSolution| {
2383             span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2384             value
2385         })
2386     }
2387 }
2388
2389 pub struct TypeckMir;
2390
2391 impl MirPass for TypeckMir {
2392     fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
2393         let def_id = src.def_id;
2394         debug!("run_pass: {:?}", def_id);
2395
2396         // When NLL is enabled, the borrow checker runs the typeck
2397         // itself, so we don't need this MIR pass anymore.
2398         if tcx.use_mir_borrowck() {
2399             return;
2400         }
2401
2402         if tcx.sess.err_count() > 0 {
2403             // compiling a broken program can obviously result in a
2404             // broken MIR, so try not to report duplicate errors.
2405             return;
2406         }
2407
2408         if tcx.is_struct_constructor(def_id) {
2409             // We just assume that the automatically generated struct constructors are
2410             // correct. See the comment in the `mir_borrowck` implementation for an
2411             // explanation why we need this.
2412             return;
2413         }
2414
2415         let param_env = tcx.param_env(def_id);
2416         tcx.infer_ctxt().enter(|infcx| {
2417             type_check_internal(
2418                 &infcx,
2419                 def_id,
2420                 param_env,
2421                 mir,
2422                 &vec![],
2423                 None,
2424                 None,
2425                 None,
2426                 |_| (),
2427             );
2428
2429             // For verification purposes, we just ignore the resulting
2430             // region constraint sets. Not our problem. =)
2431         });
2432     }
2433 }
2434
2435 trait NormalizeLocation: fmt::Debug + Copy {
2436     fn to_locations(self) -> Locations;
2437 }
2438
2439 impl NormalizeLocation for Locations {
2440     fn to_locations(self) -> Locations {
2441         self
2442     }
2443 }
2444
2445 impl NormalizeLocation for Location {
2446     fn to_locations(self) -> Locations {
2447         Locations::Single(self)
2448     }
2449 }
2450
2451 #[derive(Debug, Default)]
2452 struct ObligationAccumulator<'tcx> {
2453     obligations: PredicateObligations<'tcx>,
2454 }
2455
2456 impl<'tcx> ObligationAccumulator<'tcx> {
2457     fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2458         let InferOk { value, obligations } = value;
2459         self.obligations.extend(obligations);
2460         value
2461     }
2462
2463     fn into_vec(self) -> PredicateObligations<'tcx> {
2464         self.obligations
2465     }
2466 }