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