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