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