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