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