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