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