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