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