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