]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/type_check/mod.rs
Implement type inference for inline consts
[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 let Some(_) = liveness_constraints.get_elements(region).next() {
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 {
1349                                     defining_ty:
1350                                         DefiningTy::Const(def_id, _)
1351                                         | DefiningTy::InlineConst(def_id, _),
1352                                     ..
1353                                 },
1354                             ..
1355                         } = self.borrowck_context
1356                         {
1357                             if tcx.is_static(*def_id) {
1358                                 ConstraintCategory::UseAsStatic
1359                             } else {
1360                                 ConstraintCategory::UseAsConst
1361                             }
1362                         } else {
1363                             ConstraintCategory::Return(ReturnConstraint::Normal)
1364                         }
1365                     }
1366                     Some(l)
1367                         if matches!(
1368                             body.local_decls[l].local_info,
1369                             Some(box LocalInfo::AggregateTemp)
1370                         ) =>
1371                     {
1372                         ConstraintCategory::Usage
1373                     }
1374                     Some(l) if !body.local_decls[l].is_user_variable() => {
1375                         ConstraintCategory::Boring
1376                     }
1377                     _ => ConstraintCategory::Assignment,
1378                 };
1379                 debug!(
1380                     "assignment category: {:?} {:?}",
1381                     category,
1382                     place.as_local().map(|l| &body.local_decls[l])
1383                 );
1384
1385                 let place_ty = place.ty(body, tcx).ty;
1386                 let place_ty = self.normalize(place_ty, location);
1387                 let rv_ty = rv.ty(body, tcx);
1388                 let rv_ty = self.normalize(rv_ty, location);
1389                 if let Err(terr) =
1390                     self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1391                 {
1392                     span_mirbug!(
1393                         self,
1394                         stmt,
1395                         "bad assignment ({:?} = {:?}): {:?}",
1396                         place_ty,
1397                         rv_ty,
1398                         terr
1399                     );
1400                 }
1401
1402                 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1403                     if let Err(terr) = self.relate_type_and_user_type(
1404                         rv_ty,
1405                         ty::Variance::Invariant,
1406                         &UserTypeProjection { base: annotation_index, projs: vec![] },
1407                         location.to_locations(),
1408                         ConstraintCategory::Boring,
1409                     ) {
1410                         let annotation = &self.user_type_annotations[annotation_index];
1411                         span_mirbug!(
1412                             self,
1413                             stmt,
1414                             "bad user type on rvalue ({:?} = {:?}): {:?}",
1415                             annotation,
1416                             rv_ty,
1417                             terr
1418                         );
1419                     }
1420                 }
1421
1422                 self.check_rvalue(body, rv, location);
1423                 if !self.unsized_feature_enabled() {
1424                     let trait_ref = ty::TraitRef {
1425                         def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1426                         substs: tcx.mk_substs_trait(place_ty, &[]),
1427                     };
1428                     self.prove_trait_ref(
1429                         trait_ref,
1430                         location.to_locations(),
1431                         ConstraintCategory::SizedBound,
1432                     );
1433                 }
1434             }
1435             StatementKind::SetDiscriminant { ref place, variant_index } => {
1436                 let place_type = place.ty(body, tcx).ty;
1437                 let adt = match place_type.kind() {
1438                     ty::Adt(adt, _) if adt.is_enum() => adt,
1439                     _ => {
1440                         span_bug!(
1441                             stmt.source_info.span,
1442                             "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1443                             place,
1444                             variant_index
1445                         );
1446                     }
1447                 };
1448                 if variant_index.as_usize() >= adt.variants.len() {
1449                     span_bug!(
1450                         stmt.source_info.span,
1451                         "bad set discriminant ({:?} = {:?}): value of of range",
1452                         place,
1453                         variant_index
1454                     );
1455                 };
1456             }
1457             StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1458                 let place_ty = place.ty(body, tcx).ty;
1459                 if let Err(terr) = self.relate_type_and_user_type(
1460                     place_ty,
1461                     variance,
1462                     projection,
1463                     Locations::All(stmt.source_info.span),
1464                     ConstraintCategory::TypeAnnotation,
1465                 ) {
1466                     let annotation = &self.user_type_annotations[projection.base];
1467                     span_mirbug!(
1468                         self,
1469                         stmt,
1470                         "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1471                         place_ty,
1472                         annotation,
1473                         projection.projs,
1474                         terr
1475                     );
1476                 }
1477             }
1478             StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
1479                 ..
1480             }) => span_bug!(
1481                 stmt.source_info.span,
1482                 "Unexpected StatementKind::CopyNonOverlapping, should only appear after lowering_intrinsics",
1483             ),
1484             StatementKind::FakeRead(..)
1485             | StatementKind::StorageLive(..)
1486             | StatementKind::StorageDead(..)
1487             | StatementKind::LlvmInlineAsm { .. }
1488             | StatementKind::Retag { .. }
1489             | StatementKind::Coverage(..)
1490             | StatementKind::Nop => {}
1491         }
1492     }
1493
1494     #[instrument(skip(self, body, term_location), level = "debug")]
1495     fn check_terminator(
1496         &mut self,
1497         body: &Body<'tcx>,
1498         term: &Terminator<'tcx>,
1499         term_location: Location,
1500     ) {
1501         let tcx = self.tcx();
1502         match term.kind {
1503             TerminatorKind::Goto { .. }
1504             | TerminatorKind::Resume
1505             | TerminatorKind::Abort
1506             | TerminatorKind::Return
1507             | TerminatorKind::GeneratorDrop
1508             | TerminatorKind::Unreachable
1509             | TerminatorKind::Drop { .. }
1510             | TerminatorKind::FalseEdge { .. }
1511             | TerminatorKind::FalseUnwind { .. }
1512             | TerminatorKind::InlineAsm { .. } => {
1513                 // no checks needed for these
1514             }
1515
1516             TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1517                 let place_ty = place.ty(body, tcx).ty;
1518                 let rv_ty = value.ty(body, tcx);
1519
1520                 let locations = term_location.to_locations();
1521                 if let Err(terr) =
1522                     self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1523                 {
1524                     span_mirbug!(
1525                         self,
1526                         term,
1527                         "bad DropAndReplace ({:?} = {:?}): {:?}",
1528                         place_ty,
1529                         rv_ty,
1530                         terr
1531                     );
1532                 }
1533             }
1534             TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1535                 let discr_ty = discr.ty(body, tcx);
1536                 if let Err(terr) = self.sub_types(
1537                     discr_ty,
1538                     switch_ty,
1539                     term_location.to_locations(),
1540                     ConstraintCategory::Assignment,
1541                 ) {
1542                     span_mirbug!(
1543                         self,
1544                         term,
1545                         "bad SwitchInt ({:?} on {:?}): {:?}",
1546                         switch_ty,
1547                         discr_ty,
1548                         terr
1549                     );
1550                 }
1551                 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1552                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1553                 }
1554                 // FIXME: check the values
1555             }
1556             TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1557                 let func_ty = func.ty(body, tcx);
1558                 debug!("check_terminator: call, func_ty={:?}", func_ty);
1559                 let sig = match func_ty.kind() {
1560                     ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1561                     _ => {
1562                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1563                         return;
1564                     }
1565                 };
1566                 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1567                     term.source_info.span,
1568                     LateBoundRegionConversionTime::FnCall,
1569                     sig,
1570                 );
1571                 let sig = self.normalize(sig, term_location);
1572                 self.check_call_dest(body, term, &sig, destination, term_location);
1573
1574                 self.prove_predicates(
1575                     sig.inputs_and_output
1576                         .iter()
1577                         .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1578                     term_location.to_locations(),
1579                     ConstraintCategory::Boring,
1580                 );
1581
1582                 // The ordinary liveness rules will ensure that all
1583                 // regions in the type of the callee are live here. We
1584                 // then further constrain the late-bound regions that
1585                 // were instantiated at the call site to be live as
1586                 // well. The resulting is that all the input (and
1587                 // output) types in the signature must be live, since
1588                 // all the inputs that fed into it were live.
1589                 for &late_bound_region in map.values() {
1590                     let region_vid =
1591                         self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1592                     self.borrowck_context
1593                         .constraints
1594                         .liveness_constraints
1595                         .add_element(region_vid, term_location);
1596                 }
1597
1598                 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1599             }
1600             TerminatorKind::Assert { ref cond, ref msg, .. } => {
1601                 let cond_ty = cond.ty(body, tcx);
1602                 if cond_ty != tcx.types.bool {
1603                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1604                 }
1605
1606                 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1607                     if len.ty(body, tcx) != tcx.types.usize {
1608                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1609                     }
1610                     if index.ty(body, tcx) != tcx.types.usize {
1611                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1612                     }
1613                 }
1614             }
1615             TerminatorKind::Yield { ref value, .. } => {
1616                 let value_ty = value.ty(body, tcx);
1617                 match body.yield_ty() {
1618                     None => span_mirbug!(self, term, "yield in non-generator"),
1619                     Some(ty) => {
1620                         if let Err(terr) = self.sub_types(
1621                             value_ty,
1622                             ty,
1623                             term_location.to_locations(),
1624                             ConstraintCategory::Yield,
1625                         ) {
1626                             span_mirbug!(
1627                                 self,
1628                                 term,
1629                                 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1630                                 value_ty,
1631                                 ty,
1632                                 terr
1633                             );
1634                         }
1635                     }
1636                 }
1637             }
1638         }
1639     }
1640
1641     fn check_call_dest(
1642         &mut self,
1643         body: &Body<'tcx>,
1644         term: &Terminator<'tcx>,
1645         sig: &ty::FnSig<'tcx>,
1646         destination: &Option<(Place<'tcx>, BasicBlock)>,
1647         term_location: Location,
1648     ) {
1649         let tcx = self.tcx();
1650         match *destination {
1651             Some((ref dest, _target_block)) => {
1652                 let dest_ty = dest.ty(body, tcx).ty;
1653                 let dest_ty = self.normalize(dest_ty, term_location);
1654                 let category = match dest.as_local() {
1655                     Some(RETURN_PLACE) => {
1656                         if let BorrowCheckContext {
1657                             universal_regions:
1658                                 UniversalRegions {
1659                                     defining_ty:
1660                                         DefiningTy::Const(def_id, _)
1661                                         | DefiningTy::InlineConst(def_id, _),
1662                                     ..
1663                                 },
1664                             ..
1665                         } = self.borrowck_context
1666                         {
1667                             if tcx.is_static(*def_id) {
1668                                 ConstraintCategory::UseAsStatic
1669                             } else {
1670                                 ConstraintCategory::UseAsConst
1671                             }
1672                         } else {
1673                             ConstraintCategory::Return(ReturnConstraint::Normal)
1674                         }
1675                     }
1676                     Some(l) if !body.local_decls[l].is_user_variable() => {
1677                         ConstraintCategory::Boring
1678                     }
1679                     _ => ConstraintCategory::Assignment,
1680                 };
1681
1682                 let locations = term_location.to_locations();
1683
1684                 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1685                     span_mirbug!(
1686                         self,
1687                         term,
1688                         "call dest mismatch ({:?} <- {:?}): {:?}",
1689                         dest_ty,
1690                         sig.output(),
1691                         terr
1692                     );
1693                 }
1694
1695                 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1696                 // this check is done at `check_local`.
1697                 if self.unsized_feature_enabled() {
1698                     let span = term.source_info.span;
1699                     self.ensure_place_sized(dest_ty, span);
1700                 }
1701             }
1702             None => {
1703                 if !self
1704                     .tcx()
1705                     .conservative_is_privately_uninhabited(self.param_env.and(sig.output()))
1706                 {
1707                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1708                 }
1709             }
1710         }
1711     }
1712
1713     fn check_call_inputs(
1714         &mut self,
1715         body: &Body<'tcx>,
1716         term: &Terminator<'tcx>,
1717         sig: &ty::FnSig<'tcx>,
1718         args: &[Operand<'tcx>],
1719         term_location: Location,
1720         from_hir_call: bool,
1721     ) {
1722         debug!("check_call_inputs({:?}, {:?})", sig, args);
1723         if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1724             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1725         }
1726         for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1727             let op_arg_ty = op_arg.ty(body, self.tcx());
1728             let op_arg_ty = self.normalize(op_arg_ty, term_location);
1729             let category = if from_hir_call {
1730                 ConstraintCategory::CallArgument
1731             } else {
1732                 ConstraintCategory::Boring
1733             };
1734             if let Err(terr) =
1735                 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1736             {
1737                 span_mirbug!(
1738                     self,
1739                     term,
1740                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1741                     n,
1742                     fn_arg,
1743                     op_arg_ty,
1744                     terr
1745                 );
1746             }
1747         }
1748     }
1749
1750     fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1751         let is_cleanup = block_data.is_cleanup;
1752         self.last_span = block_data.terminator().source_info.span;
1753         match block_data.terminator().kind {
1754             TerminatorKind::Goto { target } => {
1755                 self.assert_iscleanup(body, block_data, target, is_cleanup)
1756             }
1757             TerminatorKind::SwitchInt { ref targets, .. } => {
1758                 for target in targets.all_targets() {
1759                     self.assert_iscleanup(body, block_data, *target, is_cleanup);
1760                 }
1761             }
1762             TerminatorKind::Resume => {
1763                 if !is_cleanup {
1764                     span_mirbug!(self, block_data, "resume on non-cleanup block!")
1765                 }
1766             }
1767             TerminatorKind::Abort => {
1768                 if !is_cleanup {
1769                     span_mirbug!(self, block_data, "abort on non-cleanup block!")
1770                 }
1771             }
1772             TerminatorKind::Return => {
1773                 if is_cleanup {
1774                     span_mirbug!(self, block_data, "return on cleanup block")
1775                 }
1776             }
1777             TerminatorKind::GeneratorDrop { .. } => {
1778                 if is_cleanup {
1779                     span_mirbug!(self, block_data, "generator_drop in cleanup block")
1780                 }
1781             }
1782             TerminatorKind::Yield { resume, drop, .. } => {
1783                 if is_cleanup {
1784                     span_mirbug!(self, block_data, "yield in cleanup block")
1785                 }
1786                 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1787                 if let Some(drop) = drop {
1788                     self.assert_iscleanup(body, block_data, drop, is_cleanup);
1789                 }
1790             }
1791             TerminatorKind::Unreachable => {}
1792             TerminatorKind::Drop { target, unwind, .. }
1793             | TerminatorKind::DropAndReplace { target, unwind, .. }
1794             | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1795                 self.assert_iscleanup(body, block_data, target, is_cleanup);
1796                 if let Some(unwind) = unwind {
1797                     if is_cleanup {
1798                         span_mirbug!(self, block_data, "unwind on cleanup block")
1799                     }
1800                     self.assert_iscleanup(body, block_data, unwind, true);
1801                 }
1802             }
1803             TerminatorKind::Call { ref destination, cleanup, .. } => {
1804                 if let &Some((_, target)) = destination {
1805                     self.assert_iscleanup(body, block_data, target, is_cleanup);
1806                 }
1807                 if let Some(cleanup) = cleanup {
1808                     if is_cleanup {
1809                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1810                     }
1811                     self.assert_iscleanup(body, block_data, cleanup, true);
1812                 }
1813             }
1814             TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1815                 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1816                 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1817             }
1818             TerminatorKind::FalseUnwind { real_target, unwind } => {
1819                 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1820                 if let Some(unwind) = unwind {
1821                     if is_cleanup {
1822                         span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1823                     }
1824                     self.assert_iscleanup(body, block_data, unwind, true);
1825                 }
1826             }
1827             TerminatorKind::InlineAsm { destination, .. } => {
1828                 if let Some(target) = destination {
1829                     self.assert_iscleanup(body, block_data, target, is_cleanup);
1830                 }
1831             }
1832         }
1833     }
1834
1835     fn assert_iscleanup(
1836         &mut self,
1837         body: &Body<'tcx>,
1838         ctxt: &dyn fmt::Debug,
1839         bb: BasicBlock,
1840         iscleanuppad: bool,
1841     ) {
1842         if body[bb].is_cleanup != iscleanuppad {
1843             span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1844         }
1845     }
1846
1847     fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1848         match body.local_kind(local) {
1849             LocalKind::ReturnPointer | LocalKind::Arg => {
1850                 // return values of normal functions are required to be
1851                 // sized by typeck, but return values of ADT constructors are
1852                 // not because we don't include a `Self: Sized` bounds on them.
1853                 //
1854                 // Unbound parts of arguments were never required to be Sized
1855                 // - maybe we should make that a warning.
1856                 return;
1857             }
1858             LocalKind::Var | LocalKind::Temp => {}
1859         }
1860
1861         // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1862         // and nullary ops are checked in `check_call_dest`.
1863         if !self.unsized_feature_enabled() {
1864             let span = local_decl.source_info.span;
1865             let ty = local_decl.ty;
1866             self.ensure_place_sized(ty, span);
1867         }
1868     }
1869
1870     fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1871         let tcx = self.tcx();
1872
1873         // Erase the regions from `ty` to get a global type.  The
1874         // `Sized` bound in no way depends on precise regions, so this
1875         // shouldn't affect `is_sized`.
1876         let erased_ty = tcx.erase_regions(ty);
1877         if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1878             // in current MIR construction, all non-control-flow rvalue
1879             // expressions evaluate through `as_temp` or `into` a return
1880             // slot or local, so to find all unsized rvalues it is enough
1881             // to check all temps, return slots and locals.
1882             if self.reported_errors.replace((ty, span)).is_none() {
1883                 let mut diag = struct_span_err!(
1884                     self.tcx().sess,
1885                     span,
1886                     E0161,
1887                     "cannot move a value of type {0}: the size of {0} \
1888                      cannot be statically determined",
1889                     ty
1890                 );
1891
1892                 // While this is located in `nll::typeck` this error is not
1893                 // an NLL error, it's a required check to prevent creation
1894                 // of unsized rvalues in a call expression.
1895                 diag.emit();
1896             }
1897         }
1898     }
1899
1900     fn aggregate_field_ty(
1901         &mut self,
1902         ak: &AggregateKind<'tcx>,
1903         field_index: usize,
1904         location: Location,
1905     ) -> Result<Ty<'tcx>, FieldAccessError> {
1906         let tcx = self.tcx();
1907
1908         match *ak {
1909             AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1910                 let variant = &def.variants[variant_index];
1911                 let adj_field_index = active_field_index.unwrap_or(field_index);
1912                 if let Some(field) = variant.fields.get(adj_field_index) {
1913                     Ok(self.normalize(field.ty(tcx, substs), location))
1914                 } else {
1915                     Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1916                 }
1917             }
1918             AggregateKind::Closure(_, substs) => {
1919                 match substs.as_closure().upvar_tys().nth(field_index) {
1920                     Some(ty) => Ok(ty),
1921                     None => Err(FieldAccessError::OutOfRange {
1922                         field_count: substs.as_closure().upvar_tys().count(),
1923                     }),
1924                 }
1925             }
1926             AggregateKind::Generator(_, substs, _) => {
1927                 // It doesn't make sense to look at a field beyond the prefix;
1928                 // these require a variant index, and are not initialized in
1929                 // aggregate rvalues.
1930                 match substs.as_generator().prefix_tys().nth(field_index) {
1931                     Some(ty) => Ok(ty),
1932                     None => Err(FieldAccessError::OutOfRange {
1933                         field_count: substs.as_generator().prefix_tys().count(),
1934                     }),
1935                 }
1936             }
1937             AggregateKind::Array(ty) => Ok(ty),
1938             AggregateKind::Tuple => {
1939                 unreachable!("This should have been covered in check_rvalues");
1940             }
1941         }
1942     }
1943
1944     fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1945         let tcx = self.tcx();
1946
1947         match rvalue {
1948             Rvalue::Aggregate(ak, ops) => {
1949                 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1950             }
1951
1952             Rvalue::Repeat(operand, len) => {
1953                 // If the length cannot be evaluated we must assume that the length can be larger
1954                 // than 1.
1955                 // If the length is larger than 1, the repeat expression will need to copy the
1956                 // element, so we require the `Copy` trait.
1957                 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1958                     match operand {
1959                         Operand::Copy(..) | Operand::Constant(..) => {
1960                             // These are always okay: direct use of a const, or a value that can evidently be copied.
1961                         }
1962                         Operand::Move(place) => {
1963                             // Make sure that repeated elements implement `Copy`.
1964                             let span = body.source_info(location).span;
1965                             let ty = operand.ty(body, tcx);
1966                             if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1967                                 let ccx = ConstCx::new_with_param_env(tcx, body, self.param_env);
1968                                 let is_const_fn =
1969                                     is_const_fn_in_array_repeat_expression(&ccx, &place, &body);
1970
1971                                 debug!("check_rvalue: is_const_fn={:?}", is_const_fn);
1972
1973                                 let def_id = body.source.def_id().expect_local();
1974                                 let obligation = traits::Obligation::new(
1975                                     ObligationCause::new(
1976                                         span,
1977                                         self.tcx().hir().local_def_id_to_hir_id(def_id),
1978                                         traits::ObligationCauseCode::RepeatVec(is_const_fn),
1979                                     ),
1980                                     self.param_env,
1981                                     ty::Binder::dummy(ty::TraitRef::new(
1982                                         self.tcx().require_lang_item(
1983                                             LangItem::Copy,
1984                                             Some(self.last_span),
1985                                         ),
1986                                         tcx.mk_substs_trait(ty, &[]),
1987                                     ))
1988                                     .without_const()
1989                                     .to_predicate(self.tcx()),
1990                                 );
1991                                 self.infcx.report_selection_error(
1992                                     obligation.clone(),
1993                                     &obligation,
1994                                     &traits::SelectionError::Unimplemented,
1995                                     false,
1996                                 );
1997                             }
1998                         }
1999                     }
2000                 }
2001             }
2002
2003             Rvalue::NullaryOp(_, ty) | Rvalue::ShallowInitBox(_, ty) => {
2004                 let trait_ref = ty::TraitRef {
2005                     def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
2006                     substs: tcx.mk_substs_trait(ty, &[]),
2007                 };
2008
2009                 self.prove_trait_ref(
2010                     trait_ref,
2011                     location.to_locations(),
2012                     ConstraintCategory::SizedBound,
2013                 );
2014             }
2015
2016             Rvalue::Cast(cast_kind, op, ty) => {
2017                 match cast_kind {
2018                     CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2019                         let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2020
2021                         // The type that we see in the fcx is like
2022                         // `foo::<'a, 'b>`, where `foo` is the path to a
2023                         // function definition. When we extract the
2024                         // signature, it comes from the `fn_sig` query,
2025                         // and hence may contain unnormalized results.
2026                         let fn_sig = self.normalize(fn_sig, location);
2027
2028                         let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2029
2030                         if let Err(terr) = self.eq_types(
2031                             ty,
2032                             ty_fn_ptr_from,
2033                             location.to_locations(),
2034                             ConstraintCategory::Cast,
2035                         ) {
2036                             span_mirbug!(
2037                                 self,
2038                                 rvalue,
2039                                 "equating {:?} with {:?} yields {:?}",
2040                                 ty_fn_ptr_from,
2041                                 ty,
2042                                 terr
2043                             );
2044                         }
2045                     }
2046
2047                     CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2048                         let sig = match op.ty(body, tcx).kind() {
2049                             ty::Closure(_, substs) => substs.as_closure().sig(),
2050                             _ => bug!(),
2051                         };
2052                         let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
2053
2054                         if let Err(terr) = self.eq_types(
2055                             ty,
2056                             ty_fn_ptr_from,
2057                             location.to_locations(),
2058                             ConstraintCategory::Cast,
2059                         ) {
2060                             span_mirbug!(
2061                                 self,
2062                                 rvalue,
2063                                 "equating {:?} with {:?} yields {:?}",
2064                                 ty_fn_ptr_from,
2065                                 ty,
2066                                 terr
2067                             );
2068                         }
2069                     }
2070
2071                     CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2072                         let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2073
2074                         // The type that we see in the fcx is like
2075                         // `foo::<'a, 'b>`, where `foo` is the path to a
2076                         // function definition. When we extract the
2077                         // signature, it comes from the `fn_sig` query,
2078                         // and hence may contain unnormalized results.
2079                         let fn_sig = self.normalize(fn_sig, location);
2080
2081                         let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2082
2083                         if let Err(terr) = self.eq_types(
2084                             ty,
2085                             ty_fn_ptr_from,
2086                             location.to_locations(),
2087                             ConstraintCategory::Cast,
2088                         ) {
2089                             span_mirbug!(
2090                                 self,
2091                                 rvalue,
2092                                 "equating {:?} with {:?} yields {:?}",
2093                                 ty_fn_ptr_from,
2094                                 ty,
2095                                 terr
2096                             );
2097                         }
2098                     }
2099
2100                     CastKind::Pointer(PointerCast::Unsize) => {
2101                         let &ty = ty;
2102                         let trait_ref = ty::TraitRef {
2103                             def_id: tcx
2104                                 .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2105                             substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2106                         };
2107
2108                         self.prove_trait_ref(
2109                             trait_ref,
2110                             location.to_locations(),
2111                             ConstraintCategory::Cast,
2112                         );
2113                     }
2114
2115                     CastKind::Pointer(PointerCast::MutToConstPointer) => {
2116                         let ty_from = match op.ty(body, tcx).kind() {
2117                             ty::RawPtr(ty::TypeAndMut {
2118                                 ty: ty_from,
2119                                 mutbl: hir::Mutability::Mut,
2120                             }) => ty_from,
2121                             _ => {
2122                                 span_mirbug!(
2123                                     self,
2124                                     rvalue,
2125                                     "unexpected base type for cast {:?}",
2126                                     ty,
2127                                 );
2128                                 return;
2129                             }
2130                         };
2131                         let ty_to = match ty.kind() {
2132                             ty::RawPtr(ty::TypeAndMut {
2133                                 ty: ty_to,
2134                                 mutbl: hir::Mutability::Not,
2135                             }) => ty_to,
2136                             _ => {
2137                                 span_mirbug!(
2138                                     self,
2139                                     rvalue,
2140                                     "unexpected target type for cast {:?}",
2141                                     ty,
2142                                 );
2143                                 return;
2144                             }
2145                         };
2146                         if let Err(terr) = self.sub_types(
2147                             ty_from,
2148                             ty_to,
2149                             location.to_locations(),
2150                             ConstraintCategory::Cast,
2151                         ) {
2152                             span_mirbug!(
2153                                 self,
2154                                 rvalue,
2155                                 "relating {:?} with {:?} yields {:?}",
2156                                 ty_from,
2157                                 ty_to,
2158                                 terr
2159                             );
2160                         }
2161                     }
2162
2163                     CastKind::Pointer(PointerCast::ArrayToPointer) => {
2164                         let ty_from = op.ty(body, tcx);
2165
2166                         let opt_ty_elem_mut = match ty_from.kind() {
2167                             ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2168                                 match array_ty.kind() {
2169                                     ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2170                                     _ => None,
2171                                 }
2172                             }
2173                             _ => None,
2174                         };
2175
2176                         let (ty_elem, ty_mut) = match opt_ty_elem_mut {
2177                             Some(ty_elem_mut) => ty_elem_mut,
2178                             None => {
2179                                 span_mirbug!(
2180                                     self,
2181                                     rvalue,
2182                                     "ArrayToPointer cast from unexpected type {:?}",
2183                                     ty_from,
2184                                 );
2185                                 return;
2186                             }
2187                         };
2188
2189                         let (ty_to, ty_to_mut) = match ty.kind() {
2190                             ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2191                                 (ty_to, *ty_to_mut)
2192                             }
2193                             _ => {
2194                                 span_mirbug!(
2195                                     self,
2196                                     rvalue,
2197                                     "ArrayToPointer cast to unexpected type {:?}",
2198                                     ty,
2199                                 );
2200                                 return;
2201                             }
2202                         };
2203
2204                         if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2205                             span_mirbug!(
2206                                 self,
2207                                 rvalue,
2208                                 "ArrayToPointer cast from const {:?} to mut {:?}",
2209                                 ty,
2210                                 ty_to
2211                             );
2212                             return;
2213                         }
2214
2215                         if let Err(terr) = self.sub_types(
2216                             ty_elem,
2217                             ty_to,
2218                             location.to_locations(),
2219                             ConstraintCategory::Cast,
2220                         ) {
2221                             span_mirbug!(
2222                                 self,
2223                                 rvalue,
2224                                 "relating {:?} with {:?} yields {:?}",
2225                                 ty_elem,
2226                                 ty_to,
2227                                 terr
2228                             )
2229                         }
2230                     }
2231
2232                     CastKind::Misc => {
2233                         let ty_from = op.ty(body, tcx);
2234                         let cast_ty_from = CastTy::from_ty(ty_from);
2235                         let cast_ty_to = CastTy::from_ty(ty);
2236                         match (cast_ty_from, cast_ty_to) {
2237                             (None, _)
2238                             | (_, None | Some(CastTy::FnPtr))
2239                             | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2240                             | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => {
2241                                 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2242                             }
2243                             (
2244                                 Some(CastTy::Int(_)),
2245                                 Some(CastTy::Int(_) | CastTy::Float | CastTy::Ptr(_)),
2246                             )
2247                             | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float))
2248                             | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_)))
2249                             | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (),
2250                         }
2251                     }
2252                 }
2253             }
2254
2255             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2256                 self.add_reborrow_constraint(&body, location, region, borrowed_place);
2257             }
2258
2259             Rvalue::BinaryOp(
2260                 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2261                 box (left, right),
2262             ) => {
2263                 let ty_left = left.ty(body, tcx);
2264                 match ty_left.kind() {
2265                     // Types with regions are comparable if they have a common super-type.
2266                     ty::RawPtr(_) | ty::FnPtr(_) => {
2267                         let ty_right = right.ty(body, tcx);
2268                         let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2269                             kind: TypeVariableOriginKind::MiscVariable,
2270                             span: body.source_info(location).span,
2271                         });
2272                         self.sub_types(
2273                             ty_left,
2274                             common_ty,
2275                             location.to_locations(),
2276                             ConstraintCategory::Boring,
2277                         )
2278                         .unwrap_or_else(|err| {
2279                             bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2280                         });
2281                         if let Err(terr) = self.sub_types(
2282                             ty_right,
2283                             common_ty,
2284                             location.to_locations(),
2285                             ConstraintCategory::Boring,
2286                         ) {
2287                             span_mirbug!(
2288                                 self,
2289                                 rvalue,
2290                                 "unexpected comparison types {:?} and {:?} yields {:?}",
2291                                 ty_left,
2292                                 ty_right,
2293                                 terr
2294                             )
2295                         }
2296                     }
2297                     // For types with no regions we can just check that the
2298                     // both operands have the same type.
2299                     ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2300                         if ty_left == right.ty(body, tcx) => {}
2301                     // Other types are compared by trait methods, not by
2302                     // `Rvalue::BinaryOp`.
2303                     _ => span_mirbug!(
2304                         self,
2305                         rvalue,
2306                         "unexpected comparison types {:?} and {:?}",
2307                         ty_left,
2308                         right.ty(body, tcx)
2309                     ),
2310                 }
2311             }
2312
2313             Rvalue::AddressOf(..)
2314             | Rvalue::ThreadLocalRef(..)
2315             | Rvalue::Use(..)
2316             | Rvalue::Len(..)
2317             | Rvalue::BinaryOp(..)
2318             | Rvalue::CheckedBinaryOp(..)
2319             | Rvalue::UnaryOp(..)
2320             | Rvalue::Discriminant(..) => {}
2321         }
2322     }
2323
2324     /// If this rvalue supports a user-given type annotation, then
2325     /// extract and return it. This represents the final type of the
2326     /// rvalue and will be unified with the inferred type.
2327     fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2328         match rvalue {
2329             Rvalue::Use(_)
2330             | Rvalue::ThreadLocalRef(_)
2331             | Rvalue::Repeat(..)
2332             | Rvalue::Ref(..)
2333             | Rvalue::AddressOf(..)
2334             | Rvalue::Len(..)
2335             | Rvalue::Cast(..)
2336             | Rvalue::ShallowInitBox(..)
2337             | Rvalue::BinaryOp(..)
2338             | Rvalue::CheckedBinaryOp(..)
2339             | Rvalue::NullaryOp(..)
2340             | Rvalue::UnaryOp(..)
2341             | Rvalue::Discriminant(..) => None,
2342
2343             Rvalue::Aggregate(aggregate, _) => match **aggregate {
2344                 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2345                 AggregateKind::Array(_) => None,
2346                 AggregateKind::Tuple => None,
2347                 AggregateKind::Closure(_, _) => None,
2348                 AggregateKind::Generator(_, _, _) => None,
2349             },
2350         }
2351     }
2352
2353     fn check_aggregate_rvalue(
2354         &mut self,
2355         body: &Body<'tcx>,
2356         rvalue: &Rvalue<'tcx>,
2357         aggregate_kind: &AggregateKind<'tcx>,
2358         operands: &[Operand<'tcx>],
2359         location: Location,
2360     ) {
2361         let tcx = self.tcx();
2362
2363         self.prove_aggregate_predicates(aggregate_kind, location);
2364
2365         if *aggregate_kind == AggregateKind::Tuple {
2366             // tuple rvalue field type is always the type of the op. Nothing to check here.
2367             return;
2368         }
2369
2370         for (i, operand) in operands.iter().enumerate() {
2371             let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2372                 Ok(field_ty) => field_ty,
2373                 Err(FieldAccessError::OutOfRange { field_count }) => {
2374                     span_mirbug!(
2375                         self,
2376                         rvalue,
2377                         "accessed field #{} but variant only has {}",
2378                         i,
2379                         field_count
2380                     );
2381                     continue;
2382                 }
2383             };
2384             let operand_ty = operand.ty(body, tcx);
2385             let operand_ty = self.normalize(operand_ty, location);
2386
2387             if let Err(terr) = self.sub_types(
2388                 operand_ty,
2389                 field_ty,
2390                 location.to_locations(),
2391                 ConstraintCategory::Boring,
2392             ) {
2393                 span_mirbug!(
2394                     self,
2395                     rvalue,
2396                     "{:?} is not a subtype of {:?}: {:?}",
2397                     operand_ty,
2398                     field_ty,
2399                     terr
2400                 );
2401             }
2402         }
2403     }
2404
2405     /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2406     ///
2407     /// # Parameters
2408     ///
2409     /// - `location`: the location `L` where the borrow expression occurs
2410     /// - `borrow_region`: the region `'a` associated with the borrow
2411     /// - `borrowed_place`: the place `P` being borrowed
2412     fn add_reborrow_constraint(
2413         &mut self,
2414         body: &Body<'tcx>,
2415         location: Location,
2416         borrow_region: ty::Region<'tcx>,
2417         borrowed_place: &Place<'tcx>,
2418     ) {
2419         // These constraints are only meaningful during borrowck:
2420         let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2421             self.borrowck_context;
2422
2423         // In Polonius mode, we also push a `loan_issued_at` fact
2424         // linking the loan to the region (in some cases, though,
2425         // there is no loan associated with this borrow expression --
2426         // that occurs when we are borrowing an unsafe place, for
2427         // example).
2428         if let Some(all_facts) = all_facts {
2429             let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2430             if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2431                 let region_vid = borrow_region.to_region_vid();
2432                 all_facts.loan_issued_at.push((
2433                     region_vid,
2434                     borrow_index,
2435                     location_table.mid_index(location),
2436                 ));
2437             }
2438         }
2439
2440         // If we are reborrowing the referent of another reference, we
2441         // need to add outlives relationships. In a case like `&mut
2442         // *p`, where the `p` has type `&'b mut Foo`, for example, we
2443         // need to ensure that `'b: 'a`.
2444
2445         debug!(
2446             "add_reborrow_constraint({:?}, {:?}, {:?})",
2447             location, borrow_region, borrowed_place
2448         );
2449
2450         let mut cursor = borrowed_place.projection.as_ref();
2451         let tcx = self.infcx.tcx;
2452         let field = path_utils::is_upvar_field_projection(
2453             tcx,
2454             &self.borrowck_context.upvars,
2455             borrowed_place.as_ref(),
2456             body,
2457         );
2458         let category = if let Some(field) = field {
2459             let var_hir_id = self.borrowck_context.upvars[field.index()].place.get_root_variable();
2460             // FIXME(project-rfc-2229#8): Use Place for better diagnostics
2461             ConstraintCategory::ClosureUpvar(var_hir_id)
2462         } else {
2463             ConstraintCategory::Boring
2464         };
2465
2466         while let [proj_base @ .., elem] = cursor {
2467             cursor = proj_base;
2468
2469             debug!("add_reborrow_constraint - iteration {:?}", elem);
2470
2471             match elem {
2472                 ProjectionElem::Deref => {
2473                     let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2474
2475                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2476                     match base_ty.kind() {
2477                         ty::Ref(ref_region, _, mutbl) => {
2478                             constraints.outlives_constraints.push(OutlivesConstraint {
2479                                 sup: ref_region.to_region_vid(),
2480                                 sub: borrow_region.to_region_vid(),
2481                                 locations: location.to_locations(),
2482                                 category,
2483                                 variance_info: ty::VarianceDiagInfo::default(),
2484                             });
2485
2486                             match mutbl {
2487                                 hir::Mutability::Not => {
2488                                     // Immutable reference. We don't need the base
2489                                     // to be valid for the entire lifetime of
2490                                     // the borrow.
2491                                     break;
2492                                 }
2493                                 hir::Mutability::Mut => {
2494                                     // Mutable reference. We *do* need the base
2495                                     // to be valid, because after the base becomes
2496                                     // invalid, someone else can use our mutable deref.
2497
2498                                     // This is in order to make the following function
2499                                     // illegal:
2500                                     // ```
2501                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2502                                     //     &mut *x
2503                                     // }
2504                                     // ```
2505                                     //
2506                                     // As otherwise you could clone `&mut T` using the
2507                                     // following function:
2508                                     // ```
2509                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
2510                                     //     let my_clone = unsafe_deref(&'a x);
2511                                     //     ENDREGION 'a;
2512                                     //     (my_clone, x)
2513                                     // }
2514                                     // ```
2515                                 }
2516                             }
2517                         }
2518                         ty::RawPtr(..) => {
2519                             // deref of raw pointer, guaranteed to be valid
2520                             break;
2521                         }
2522                         ty::Adt(def, _) if def.is_box() => {
2523                             // deref of `Box`, need the base to be valid - propagate
2524                         }
2525                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2526                     }
2527                 }
2528                 ProjectionElem::Field(..)
2529                 | ProjectionElem::Downcast(..)
2530                 | ProjectionElem::Index(..)
2531                 | ProjectionElem::ConstantIndex { .. }
2532                 | ProjectionElem::Subslice { .. } => {
2533                     // other field access
2534                 }
2535             }
2536         }
2537     }
2538
2539     fn prove_aggregate_predicates(
2540         &mut self,
2541         aggregate_kind: &AggregateKind<'tcx>,
2542         location: Location,
2543     ) {
2544         let tcx = self.tcx();
2545
2546         debug!(
2547             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2548             aggregate_kind, location
2549         );
2550
2551         let (def_id, instantiated_predicates) = match aggregate_kind {
2552             AggregateKind::Adt(def, _, substs, _, _) => {
2553                 (def.did, tcx.predicates_of(def.did).instantiate(tcx, substs))
2554             }
2555
2556             // For closures, we have some **extra requirements** we
2557             //
2558             // have to check. In particular, in their upvars and
2559             // signatures, closures often reference various regions
2560             // from the surrounding function -- we call those the
2561             // closure's free regions. When we borrow-check (and hence
2562             // region-check) closures, we may find that the closure
2563             // requires certain relationships between those free
2564             // regions. However, because those free regions refer to
2565             // portions of the CFG of their caller, the closure is not
2566             // in a position to verify those relationships. In that
2567             // case, the requirements get "propagated" to us, and so
2568             // we have to solve them here where we instantiate the
2569             // closure.
2570             //
2571             // Despite the opacity of the previous parapgrah, this is
2572             // actually relatively easy to understand in terms of the
2573             // desugaring. A closure gets desugared to a struct, and
2574             // these extra requirements are basically like where
2575             // clauses on the struct.
2576             AggregateKind::Closure(def_id, substs)
2577             | AggregateKind::Generator(def_id, substs, _) => {
2578                 (*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location))
2579             }
2580
2581             AggregateKind::Array(_) | AggregateKind::Tuple => {
2582                 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2583             }
2584         };
2585
2586         self.normalize_and_prove_instantiated_predicates(
2587             def_id,
2588             instantiated_predicates,
2589             location.to_locations(),
2590         );
2591     }
2592
2593     fn prove_closure_bounds(
2594         &mut self,
2595         tcx: TyCtxt<'tcx>,
2596         def_id: LocalDefId,
2597         substs: SubstsRef<'tcx>,
2598         location: Location,
2599     ) -> ty::InstantiatedPredicates<'tcx> {
2600         if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2601         {
2602             let closure_constraints = QueryRegionConstraints {
2603                 outlives: closure_region_requirements.apply_requirements(
2604                     tcx,
2605                     def_id.to_def_id(),
2606                     substs,
2607                 ),
2608
2609                 // Presently, closures never propagate member
2610                 // constraints to their parents -- they are enforced
2611                 // locally.  This is largely a non-issue as member
2612                 // constraints only come from `-> impl Trait` and
2613                 // friends which don't appear (thus far...) in
2614                 // closures.
2615                 member_constraints: vec![],
2616             };
2617
2618             let bounds_mapping = closure_constraints
2619                 .outlives
2620                 .iter()
2621                 .enumerate()
2622                 .filter_map(|(idx, constraint)| {
2623                     let ty::OutlivesPredicate(k1, r2) =
2624                         constraint.no_bound_vars().unwrap_or_else(|| {
2625                             bug!("query_constraint {:?} contained bound vars", constraint,);
2626                         });
2627
2628                     match k1.unpack() {
2629                         GenericArgKind::Lifetime(r1) => {
2630                             // constraint is r1: r2
2631                             let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2632                             let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2633                             let outlives_requirements =
2634                                 &closure_region_requirements.outlives_requirements[idx];
2635                             Some((
2636                                 (r1_vid, r2_vid),
2637                                 (outlives_requirements.category, outlives_requirements.blame_span),
2638                             ))
2639                         }
2640                         GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2641                     }
2642                 })
2643                 .collect();
2644
2645             let existing = self
2646                 .borrowck_context
2647                 .constraints
2648                 .closure_bounds_mapping
2649                 .insert(location, bounds_mapping);
2650             assert!(existing.is_none(), "Multiple closures at the same location.");
2651
2652             self.push_region_constraints(
2653                 location.to_locations(),
2654                 ConstraintCategory::ClosureBounds,
2655                 &closure_constraints,
2656             );
2657         }
2658
2659         tcx.predicates_of(def_id).instantiate(tcx, substs)
2660     }
2661
2662     #[instrument(skip(self, body), level = "debug")]
2663     fn typeck_mir(&mut self, body: &Body<'tcx>) {
2664         self.last_span = body.span;
2665         debug!(?body.span);
2666
2667         for (local, local_decl) in body.local_decls.iter_enumerated() {
2668             self.check_local(&body, local, local_decl);
2669         }
2670
2671         for (block, block_data) in body.basic_blocks().iter_enumerated() {
2672             let mut location = Location { block, statement_index: 0 };
2673             for stmt in &block_data.statements {
2674                 if !stmt.source_info.span.is_dummy() {
2675                     self.last_span = stmt.source_info.span;
2676                 }
2677                 self.check_stmt(body, stmt, location);
2678                 location.statement_index += 1;
2679             }
2680
2681             self.check_terminator(&body, block_data.terminator(), location);
2682             self.check_iscleanup(&body, block_data);
2683         }
2684     }
2685 }
2686
2687 trait NormalizeLocation: fmt::Debug + Copy {
2688     fn to_locations(self) -> Locations;
2689 }
2690
2691 impl NormalizeLocation for Locations {
2692     fn to_locations(self) -> Locations {
2693         self
2694     }
2695 }
2696
2697 impl NormalizeLocation for Location {
2698     fn to_locations(self) -> Locations {
2699         Locations::Single(self)
2700     }
2701 }
2702
2703 #[derive(Debug, Default)]
2704 struct ObligationAccumulator<'tcx> {
2705     obligations: PredicateObligations<'tcx>,
2706 }
2707
2708 impl<'tcx> ObligationAccumulator<'tcx> {
2709     fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2710         let InferOk { value, obligations } = value;
2711         self.obligations.extend(obligations);
2712         value
2713     }
2714
2715     fn into_vec(self) -> PredicateObligations<'tcx> {
2716         self.obligations
2717     }
2718 }