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