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