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