]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/type_check/mod.rs
599472958f4fcf12f110f70f22c0eaed84613707
[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, UnpackedKind, 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.sty {
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.sty {
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: sty, def_id }) => {
428                 let sty = self.sanitize_type(place, sty);
429                 let check_err =
430                     |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
431                      place: &Place<'tcx>,
432                      ty,
433                      sty| {
434                         if let Err(terr) = verifier.cx.eq_types(
435                             sty,
436                             ty,
437                             location.to_locations(),
438                             ConstraintCategory::Boring,
439                         ) {
440                             span_mirbug!(
441                             verifier,
442                             place,
443                             "bad promoted type ({:?}: {:?}): {:?}",
444                             ty,
445                             sty,
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, sty);
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, sty);
465                     }
466                 }
467                 PlaceTy::from_ty(sty)
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                     // In order 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.sty {
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.sty {
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.sty {
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.sty {
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.upvar_tys(def_id, tcx).nth(field.index()) {
767                         Some(ty) => Ok(ty),
768                         None => Err(FieldAccessError::OutOfRange {
769                             field_count: substs.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.sty {
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(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.sty {
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(ref place, variance, box ref projection) => {
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.sty {
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         // Do not count the `VaListImpl` argument as a "true" argument to
1730         // a C-variadic function.
1731         let inputs = if sig.c_variadic {
1732             &sig.inputs()[..sig.inputs().len() - 1]
1733         } else {
1734             &sig.inputs()[..]
1735         };
1736         if args.len() < inputs.len() || (args.len() > inputs.len() && !sig.c_variadic) {
1737             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1738         }
1739         for (n, (fn_arg, op_arg)) in inputs.iter().zip(args).enumerate() {
1740             let op_arg_ty = op_arg.ty(body, self.tcx());
1741             let category = if from_hir_call {
1742                 ConstraintCategory::CallArgument
1743             } else {
1744                 ConstraintCategory::Boring
1745             };
1746             if let Err(terr) =
1747                 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1748             {
1749                 span_mirbug!(
1750                     self,
1751                     term,
1752                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1753                     n,
1754                     fn_arg,
1755                     op_arg_ty,
1756                     terr
1757                 );
1758             }
1759         }
1760     }
1761
1762     fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1763         let is_cleanup = block_data.is_cleanup;
1764         self.last_span = block_data.terminator().source_info.span;
1765         match block_data.terminator().kind {
1766             TerminatorKind::Goto { target } => {
1767                 self.assert_iscleanup(body, block_data, target, is_cleanup)
1768             }
1769             TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1770                 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1771             },
1772             TerminatorKind::Resume => if !is_cleanup {
1773                 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1774             },
1775             TerminatorKind::Abort => if !is_cleanup {
1776                 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1777             },
1778             TerminatorKind::Return => if is_cleanup {
1779                 span_mirbug!(self, block_data, "return on cleanup block")
1780             },
1781             TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1782                 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1783             },
1784             TerminatorKind::Yield { resume, drop, .. } => {
1785                 if is_cleanup {
1786                     span_mirbug!(self, block_data, "yield in cleanup block")
1787                 }
1788                 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1789                 if let Some(drop) = drop {
1790                     self.assert_iscleanup(body, block_data, drop, is_cleanup);
1791                 }
1792             }
1793             TerminatorKind::Unreachable => {}
1794             TerminatorKind::Drop { target, unwind, .. }
1795             | TerminatorKind::DropAndReplace { target, unwind, .. }
1796             | TerminatorKind::Assert {
1797                 target,
1798                 cleanup: unwind,
1799                 ..
1800             } => {
1801                 self.assert_iscleanup(body, block_data, target, is_cleanup);
1802                 if let Some(unwind) = unwind {
1803                     if is_cleanup {
1804                         span_mirbug!(self, block_data, "unwind on cleanup block")
1805                     }
1806                     self.assert_iscleanup(body, block_data, unwind, true);
1807                 }
1808             }
1809             TerminatorKind::Call {
1810                 ref destination,
1811                 cleanup,
1812                 ..
1813             } => {
1814                 if let &Some((_, target)) = destination {
1815                     self.assert_iscleanup(body, block_data, target, is_cleanup);
1816                 }
1817                 if let Some(cleanup) = cleanup {
1818                     if is_cleanup {
1819                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1820                     }
1821                     self.assert_iscleanup(body, block_data, cleanup, true);
1822                 }
1823             }
1824             TerminatorKind::FalseEdges {
1825                 real_target,
1826                 imaginary_target,
1827             } => {
1828                 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1829                 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1830             }
1831             TerminatorKind::FalseUnwind {
1832                 real_target,
1833                 unwind,
1834             } => {
1835                 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1836                 if let Some(unwind) = unwind {
1837                     if is_cleanup {
1838                         span_mirbug!(
1839                             self,
1840                             block_data,
1841                             "cleanup in cleanup block via false unwind"
1842                         );
1843                     }
1844                     self.assert_iscleanup(body, block_data, unwind, true);
1845                 }
1846             }
1847         }
1848     }
1849
1850     fn assert_iscleanup(
1851         &mut self,
1852         body: &Body<'tcx>,
1853         ctxt: &dyn fmt::Debug,
1854         bb: BasicBlock,
1855         iscleanuppad: bool,
1856     ) {
1857         if body[bb].is_cleanup != iscleanuppad {
1858             span_mirbug!(
1859                 self,
1860                 ctxt,
1861                 "cleanuppad mismatch: {:?} should be {:?}",
1862                 bb,
1863                 iscleanuppad
1864             );
1865         }
1866     }
1867
1868     fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1869         match body.local_kind(local) {
1870             LocalKind::ReturnPointer | LocalKind::Arg => {
1871                 // return values of normal functions are required to be
1872                 // sized by typeck, but return values of ADT constructors are
1873                 // not because we don't include a `Self: Sized` bounds on them.
1874                 //
1875                 // Unbound parts of arguments were never required to be Sized
1876                 // - maybe we should make that a warning.
1877                 return;
1878             }
1879             LocalKind::Var | LocalKind::Temp => {}
1880         }
1881
1882         // When `#![feature(unsized_locals)]` is enabled, only function calls
1883         // and nullary ops are checked in `check_call_dest`.
1884         if !self.tcx().features().unsized_locals {
1885             let span = local_decl.source_info.span;
1886             let ty = local_decl.ty;
1887             self.ensure_place_sized(ty, span);
1888         }
1889     }
1890
1891     fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1892         let tcx = self.tcx();
1893
1894         // Erase the regions from `ty` to get a global type.  The
1895         // `Sized` bound in no way depends on precise regions, so this
1896         // shouldn't affect `is_sized`.
1897         let gcx = tcx.global_tcx();
1898         let erased_ty = tcx.erase_regions(&ty);
1899         if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1900             // in current MIR construction, all non-control-flow rvalue
1901             // expressions evaluate through `as_temp` or `into` a return
1902             // slot or local, so to find all unsized rvalues it is enough
1903             // to check all temps, return slots and locals.
1904             if let None = self.reported_errors.replace((ty, span)) {
1905                 let mut diag = struct_span_err!(
1906                     self.tcx().sess,
1907                     span,
1908                     E0161,
1909                     "cannot move a value of type {0}: the size of {0} \
1910                      cannot be statically determined",
1911                     ty
1912                 );
1913
1914                 // While this is located in `nll::typeck` this error is not
1915                 // an NLL error, it's a required check to prevent creation
1916                 // of unsized rvalues in certain cases:
1917                 // * operand of a box expression
1918                 // * callee in a call expression
1919                 diag.emit();
1920             }
1921         }
1922     }
1923
1924     fn aggregate_field_ty(
1925         &mut self,
1926         ak: &AggregateKind<'tcx>,
1927         field_index: usize,
1928         location: Location,
1929     ) -> Result<Ty<'tcx>, FieldAccessError> {
1930         let tcx = self.tcx();
1931
1932         match *ak {
1933             AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1934                 let variant = &def.variants[variant_index];
1935                 let adj_field_index = active_field_index.unwrap_or(field_index);
1936                 if let Some(field) = variant.fields.get(adj_field_index) {
1937                     Ok(self.normalize(field.ty(tcx, substs), location))
1938                 } else {
1939                     Err(FieldAccessError::OutOfRange {
1940                         field_count: variant.fields.len(),
1941                     })
1942                 }
1943             }
1944             AggregateKind::Closure(def_id, substs) => {
1945                 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1946                     Some(ty) => Ok(ty),
1947                     None => Err(FieldAccessError::OutOfRange {
1948                         field_count: substs.upvar_tys(def_id, tcx).count(),
1949                     }),
1950                 }
1951             }
1952             AggregateKind::Generator(def_id, substs, _) => {
1953                 // It doesn't make sense to look at a field beyond the prefix;
1954                 // these require a variant index, and are not initialized in
1955                 // aggregate rvalues.
1956                 match substs.prefix_tys(def_id, tcx).nth(field_index) {
1957                     Some(ty) => Ok(ty),
1958                     None => Err(FieldAccessError::OutOfRange {
1959                         field_count: substs.prefix_tys(def_id, tcx).count(),
1960                     }),
1961                 }
1962             }
1963             AggregateKind::Array(ty) => Ok(ty),
1964             AggregateKind::Tuple => {
1965                 unreachable!("This should have been covered in check_rvalues");
1966             }
1967         }
1968     }
1969
1970     fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1971         let tcx = self.tcx();
1972
1973         match rvalue {
1974             Rvalue::Aggregate(ak, ops) => {
1975                 self.check_aggregate_rvalue(body, rvalue, ak, ops, location)
1976             }
1977
1978             Rvalue::Repeat(operand, len) => if *len > 1 {
1979                 if let Operand::Move(_) = operand {
1980                     // While this is located in `nll::typeck` this error is not an NLL error, it's
1981                     // a required check to make sure that repeated elements implement `Copy`.
1982                     let span = body.source_info(location).span;
1983                     let ty = operand.ty(body, tcx);
1984                     if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1985                         self.infcx.report_selection_error(
1986                             &traits::Obligation::new(
1987                                 ObligationCause::new(
1988                                     span,
1989                                     self.tcx().hir().def_index_to_hir_id(self.mir_def_id.index),
1990                                     traits::ObligationCauseCode::RepeatVec,
1991                                 ),
1992                                 self.param_env,
1993                                 ty::Predicate::Trait(ty::Binder::bind(ty::TraitPredicate {
1994                                     trait_ref: ty::TraitRef::new(
1995                                         self.tcx().lang_items().copy_trait().unwrap(),
1996                                         tcx.mk_substs_trait(ty, &[]),
1997                                     ),
1998                                 })),
1999                             ),
2000                             &traits::SelectionError::Unimplemented,
2001                             false,
2002                         );
2003                     }
2004                 }
2005             },
2006
2007             Rvalue::NullaryOp(_, ty) => {
2008                 // Even with unsized locals cannot box an unsized value.
2009                 if self.tcx().features().unsized_locals {
2010                     let span = body.source_info(location).span;
2011                     self.ensure_place_sized(ty, span);
2012                 }
2013
2014                 let trait_ref = ty::TraitRef {
2015                     def_id: tcx.lang_items().sized_trait().unwrap(),
2016                     substs: tcx.mk_substs_trait(ty, &[]),
2017                 };
2018
2019                 self.prove_trait_ref(
2020                     trait_ref,
2021                     location.to_locations(),
2022                     ConstraintCategory::SizedBound,
2023                 );
2024             }
2025
2026             Rvalue::Cast(cast_kind, op, ty) => {
2027                 match cast_kind {
2028                     CastKind::Pointer(PointerCast::ReifyFnPointer) => {
2029                         let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2030
2031                         // The type that we see in the fcx is like
2032                         // `foo::<'a, 'b>`, where `foo` is the path to a
2033                         // function definition. When we extract the
2034                         // signature, it comes from the `fn_sig` query,
2035                         // and hence may contain unnormalized results.
2036                         let fn_sig = self.normalize(fn_sig, location);
2037
2038                         let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
2039
2040                         if let Err(terr) = self.eq_types(
2041                             ty_fn_ptr_from,
2042                             ty,
2043                             location.to_locations(),
2044                             ConstraintCategory::Cast,
2045                         ) {
2046                             span_mirbug!(
2047                                 self,
2048                                 rvalue,
2049                                 "equating {:?} with {:?} yields {:?}",
2050                                 ty_fn_ptr_from,
2051                                 ty,
2052                                 terr
2053                             );
2054                         }
2055                     }
2056
2057                     CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2058                         let sig = match op.ty(body, tcx).sty {
2059                             ty::Closure(def_id, substs) => {
2060                                 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
2061                             }
2062                             _ => bug!(),
2063                         };
2064                         let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2065
2066                         if let Err(terr) = self.eq_types(
2067                             ty_fn_ptr_from,
2068                             ty,
2069                             location.to_locations(),
2070                             ConstraintCategory::Cast,
2071                         ) {
2072                             span_mirbug!(
2073                                 self,
2074                                 rvalue,
2075                                 "equating {:?} with {:?} yields {:?}",
2076                                 ty_fn_ptr_from,
2077                                 ty,
2078                                 terr
2079                             );
2080                         }
2081                     }
2082
2083                     CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2084                         let fn_sig = op.ty(body, tcx).fn_sig(tcx);
2085
2086                         // The type that we see in the fcx is like
2087                         // `foo::<'a, 'b>`, where `foo` is the path to a
2088                         // function definition. When we extract the
2089                         // signature, it comes from the `fn_sig` query,
2090                         // and hence may contain unnormalized results.
2091                         let fn_sig = self.normalize(fn_sig, location);
2092
2093                         let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2094
2095                         if let Err(terr) = self.eq_types(
2096                             ty_fn_ptr_from,
2097                             ty,
2098                             location.to_locations(),
2099                             ConstraintCategory::Cast,
2100                         ) {
2101                             span_mirbug!(
2102                                 self,
2103                                 rvalue,
2104                                 "equating {:?} with {:?} yields {:?}",
2105                                 ty_fn_ptr_from,
2106                                 ty,
2107                                 terr
2108                             );
2109                         }
2110                     }
2111
2112                     CastKind::Pointer(PointerCast::Unsize) => {
2113                         let &ty = ty;
2114                         let trait_ref = ty::TraitRef {
2115                             def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2116                             substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2117                         };
2118
2119                         self.prove_trait_ref(
2120                             trait_ref,
2121                             location.to_locations(),
2122                             ConstraintCategory::Cast,
2123                         );
2124                     }
2125
2126                     CastKind::Pointer(PointerCast::MutToConstPointer) => {
2127                         let ty_from = match op.ty(body, tcx).sty {
2128                             ty::RawPtr(ty::TypeAndMut {
2129                                 ty: ty_from,
2130                                 mutbl: hir::MutMutable,
2131                             }) => ty_from,
2132                             _ => {
2133                                 span_mirbug!(
2134                                     self,
2135                                     rvalue,
2136                                     "unexpected base type for cast {:?}",
2137                                     ty,
2138                                 );
2139                                 return;
2140                             }
2141                         };
2142                         let ty_to = match ty.sty {
2143                             ty::RawPtr(ty::TypeAndMut {
2144                                 ty: ty_to,
2145                                 mutbl: hir::MutImmutable,
2146                             }) => ty_to,
2147                             _ => {
2148                                 span_mirbug!(
2149                                     self,
2150                                     rvalue,
2151                                     "unexpected target type for cast {:?}",
2152                                     ty,
2153                                 );
2154                                 return;
2155                             }
2156                         };
2157                         if let Err(terr) = self.sub_types(
2158                             ty_from,
2159                             ty_to,
2160                             location.to_locations(),
2161                             ConstraintCategory::Cast,
2162                         ) {
2163                             span_mirbug!(
2164                                 self,
2165                                 rvalue,
2166                                 "relating {:?} with {:?} yields {:?}",
2167                                 ty_from,
2168                                 ty_to,
2169                                 terr
2170                             )
2171                         }
2172                     }
2173
2174                     CastKind::Misc => {
2175                         if let ty::Ref(_, mut ty_from, _) = op.ty(body, tcx).sty {
2176                             let (mut ty_to, mutability) = if let ty::RawPtr(ty::TypeAndMut {
2177                                 ty: ty_to,
2178                                 mutbl,
2179                             }) = ty.sty {
2180                                 (ty_to, mutbl)
2181                             } else {
2182                                 span_mirbug!(
2183                                     self,
2184                                     rvalue,
2185                                     "invalid cast types {:?} -> {:?}",
2186                                     op.ty(body, tcx),
2187                                     ty,
2188                                 );
2189                                 return;
2190                             };
2191
2192                             // Handle the direct cast from `&[T; N]` to `*const T` by unwrapping
2193                             // any array we find.
2194                             while let ty::Array(ty_elem_from, _) = ty_from.sty {
2195                                 ty_from = ty_elem_from;
2196                                 if let ty::Array(ty_elem_to, _) = ty_to.sty {
2197                                     ty_to = ty_elem_to;
2198                                 } else {
2199                                     break;
2200                                 }
2201                             }
2202
2203                             if let hir::MutMutable = mutability {
2204                                 if let Err(terr) = self.eq_types(
2205                                     ty_from,
2206                                     ty_to,
2207                                     location.to_locations(),
2208                                     ConstraintCategory::Cast,
2209                                 ) {
2210                                     span_mirbug!(
2211                                         self,
2212                                         rvalue,
2213                                         "equating {:?} with {:?} yields {:?}",
2214                                         ty_from,
2215                                         ty_to,
2216                                         terr
2217                                     )
2218                                 }
2219                             } else {
2220                                 if let Err(terr) = self.sub_types(
2221                                     ty_from,
2222                                     ty_to,
2223                                     location.to_locations(),
2224                                     ConstraintCategory::Cast,
2225                                 ) {
2226                                     span_mirbug!(
2227                                         self,
2228                                         rvalue,
2229                                         "relating {:?} with {:?} yields {:?}",
2230                                         ty_from,
2231                                         ty_to,
2232                                         terr
2233                                     )
2234                                 }
2235                             }
2236                         }
2237                     }
2238                 }
2239             }
2240
2241             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2242                 self.add_reborrow_constraint(body, location, region, borrowed_place);
2243             }
2244
2245             Rvalue::BinaryOp(BinOp::Eq, left, right)
2246             | Rvalue::BinaryOp(BinOp::Ne, left, right)
2247             | Rvalue::BinaryOp(BinOp::Lt, left, right)
2248             | Rvalue::BinaryOp(BinOp::Le, left, right)
2249             | Rvalue::BinaryOp(BinOp::Gt, left, right)
2250             | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2251                 let ty_left = left.ty(body, tcx);
2252                 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.sty {
2253                     let ty_right = right.ty(body, tcx);
2254                     let common_ty = self.infcx.next_ty_var(
2255                         TypeVariableOrigin {
2256                             kind: TypeVariableOriginKind::MiscVariable,
2257                             span: body.source_info(location).span,
2258                         }
2259                     );
2260                     self.sub_types(
2261                         common_ty,
2262                         ty_left,
2263                         location.to_locations(),
2264                         ConstraintCategory::Boring
2265                     ).unwrap_or_else(|err| {
2266                         bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2267                     });
2268                     if let Err(terr) = self.sub_types(
2269                         common_ty,
2270                         ty_right,
2271                         location.to_locations(),
2272                         ConstraintCategory::Boring
2273                     ) {
2274                         span_mirbug!(
2275                             self,
2276                             rvalue,
2277                             "unexpected comparison types {:?} and {:?} yields {:?}",
2278                             ty_left,
2279                             ty_right,
2280                             terr
2281                         )
2282                     }
2283                 }
2284             }
2285
2286             Rvalue::Use(..)
2287             | Rvalue::Len(..)
2288             | Rvalue::BinaryOp(..)
2289             | Rvalue::CheckedBinaryOp(..)
2290             | Rvalue::UnaryOp(..)
2291             | Rvalue::Discriminant(..) => {}
2292         }
2293     }
2294
2295     /// If this rvalue supports a user-given type annotation, then
2296     /// extract and return it. This represents the final type of the
2297     /// rvalue and will be unified with the inferred type.
2298     fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2299         match rvalue {
2300             Rvalue::Use(_)
2301             | Rvalue::Repeat(..)
2302             | Rvalue::Ref(..)
2303             | Rvalue::Len(..)
2304             | Rvalue::Cast(..)
2305             | Rvalue::BinaryOp(..)
2306             | Rvalue::CheckedBinaryOp(..)
2307             | Rvalue::NullaryOp(..)
2308             | Rvalue::UnaryOp(..)
2309             | Rvalue::Discriminant(..) => None,
2310
2311             Rvalue::Aggregate(aggregate, _) => match **aggregate {
2312                 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2313                 AggregateKind::Array(_) => None,
2314                 AggregateKind::Tuple => None,
2315                 AggregateKind::Closure(_, _) => None,
2316                 AggregateKind::Generator(_, _, _) => None,
2317             },
2318         }
2319     }
2320
2321     fn check_aggregate_rvalue(
2322         &mut self,
2323         body: &Body<'tcx>,
2324         rvalue: &Rvalue<'tcx>,
2325         aggregate_kind: &AggregateKind<'tcx>,
2326         operands: &[Operand<'tcx>],
2327         location: Location,
2328     ) {
2329         let tcx = self.tcx();
2330
2331         self.prove_aggregate_predicates(aggregate_kind, location);
2332
2333         if *aggregate_kind == AggregateKind::Tuple {
2334             // tuple rvalue field type is always the type of the op. Nothing to check here.
2335             return;
2336         }
2337
2338         for (i, operand) in operands.iter().enumerate() {
2339             let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2340                 Ok(field_ty) => field_ty,
2341                 Err(FieldAccessError::OutOfRange { field_count }) => {
2342                     span_mirbug!(
2343                         self,
2344                         rvalue,
2345                         "accessed field #{} but variant only has {}",
2346                         i,
2347                         field_count
2348                     );
2349                     continue;
2350                 }
2351             };
2352             let operand_ty = operand.ty(body, tcx);
2353
2354             if let Err(terr) = self.sub_types(
2355                 operand_ty,
2356                 field_ty,
2357                 location.to_locations(),
2358                 ConstraintCategory::Boring,
2359             ) {
2360                 span_mirbug!(
2361                     self,
2362                     rvalue,
2363                     "{:?} is not a subtype of {:?}: {:?}",
2364                     operand_ty,
2365                     field_ty,
2366                     terr
2367                 );
2368             }
2369         }
2370     }
2371
2372     /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2373     ///
2374     /// # Parameters
2375     ///
2376     /// - `location`: the location `L` where the borrow expression occurs
2377     /// - `borrow_region`: the region `'a` associated with the borrow
2378     /// - `borrowed_place`: the place `P` being borrowed
2379     fn add_reborrow_constraint(
2380         &mut self,
2381         body: &Body<'tcx>,
2382         location: Location,
2383         borrow_region: ty::Region<'tcx>,
2384         borrowed_place: &Place<'tcx>,
2385     ) {
2386         // These constraints are only meaningful during borrowck:
2387         let BorrowCheckContext {
2388             borrow_set,
2389             location_table,
2390             all_facts,
2391             constraints,
2392             ..
2393         } = self.borrowck_context;
2394
2395         // In Polonius mode, we also push a `borrow_region` fact
2396         // linking the loan to the region (in some cases, though,
2397         // there is no loan associated with this borrow expression --
2398         // that occurs when we are borrowing an unsafe place, for
2399         // example).
2400         if let Some(all_facts) = all_facts {
2401             if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2402                 let region_vid = borrow_region.to_region_vid();
2403                 all_facts.borrow_region.push((
2404                     region_vid,
2405                     *borrow_index,
2406                     location_table.mid_index(location),
2407                 ));
2408             }
2409         }
2410
2411         // If we are reborrowing the referent of another reference, we
2412         // need to add outlives relationships. In a case like `&mut
2413         // *p`, where the `p` has type `&'b mut Foo`, for example, we
2414         // need to ensure that `'b: 'a`.
2415
2416         debug!(
2417             "add_reborrow_constraint({:?}, {:?}, {:?})",
2418             location, borrow_region, borrowed_place
2419         );
2420         for (i, elem) in borrowed_place.projection.iter().enumerate().rev() {
2421             debug!("add_reborrow_constraint - iteration {:?}", elem);
2422             let proj_base = &borrowed_place.projection[..i];
2423
2424             match elem {
2425                 ProjectionElem::Deref => {
2426                     let tcx = self.infcx.tcx;
2427                     let base_ty = Place::ty_from(&borrowed_place.base, proj_base, body, tcx).ty;
2428
2429                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2430                     match base_ty.sty {
2431                         ty::Ref(ref_region, _, mutbl) => {
2432                             constraints.outlives_constraints.push(OutlivesConstraint {
2433                                 sup: ref_region.to_region_vid(),
2434                                 sub: borrow_region.to_region_vid(),
2435                                 locations: location.to_locations(),
2436                                 category: ConstraintCategory::Boring,
2437                             });
2438
2439                             match mutbl {
2440                                 hir::Mutability::MutImmutable => {
2441                                     // Immutable reference. We don't need the base
2442                                     // to be valid for the entire lifetime of
2443                                     // the borrow.
2444                                     break;
2445                                 }
2446                                 hir::Mutability::MutMutable => {
2447                                     // Mutable reference. We *do* need the base
2448                                     // to be valid, because after the base becomes
2449                                     // invalid, someone else can use our mutable deref.
2450
2451                                     // This is in order to make the following function
2452                                     // illegal:
2453                                     // ```
2454                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2455                                     //     &mut *x
2456                                     // }
2457                                     // ```
2458                                     //
2459                                     // As otherwise you could clone `&mut T` using the
2460                                     // following function:
2461                                     // ```
2462                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
2463                                     //     let my_clone = unsafe_deref(&'a x);
2464                                     //     ENDREGION 'a;
2465                                     //     (my_clone, x)
2466                                     // }
2467                                     // ```
2468                                 }
2469                             }
2470                         }
2471                         ty::RawPtr(..) => {
2472                             // deref of raw pointer, guaranteed to be valid
2473                             break;
2474                         }
2475                         ty::Adt(def, _) if def.is_box() => {
2476                             // deref of `Box`, need the base to be valid - propagate
2477                         }
2478                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2479                     }
2480                 }
2481                 ProjectionElem::Field(..)
2482                 | ProjectionElem::Downcast(..)
2483                 | ProjectionElem::Index(..)
2484                 | ProjectionElem::ConstantIndex { .. }
2485                 | ProjectionElem::Subslice { .. } => {
2486                     // other field access
2487                 }
2488             }
2489         }
2490     }
2491
2492     fn prove_aggregate_predicates(
2493         &mut self,
2494         aggregate_kind: &AggregateKind<'tcx>,
2495         location: Location,
2496     ) {
2497         let tcx = self.tcx();
2498
2499         debug!(
2500             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2501             aggregate_kind, location
2502         );
2503
2504         let instantiated_predicates = match aggregate_kind {
2505             AggregateKind::Adt(def, _, substs, _, _) => {
2506                 tcx.predicates_of(def.did).instantiate(tcx, substs)
2507             }
2508
2509             // For closures, we have some **extra requirements** we
2510             //
2511             // have to check. In particular, in their upvars and
2512             // signatures, closures often reference various regions
2513             // from the surrounding function -- we call those the
2514             // closure's free regions. When we borrow-check (and hence
2515             // region-check) closures, we may find that the closure
2516             // requires certain relationships between those free
2517             // regions. However, because those free regions refer to
2518             // portions of the CFG of their caller, the closure is not
2519             // in a position to verify those relationships. In that
2520             // case, the requirements get "propagated" to us, and so
2521             // we have to solve them here where we instantiate the
2522             // closure.
2523             //
2524             // Despite the opacity of the previous parapgrah, this is
2525             // actually relatively easy to understand in terms of the
2526             // desugaring. A closure gets desugared to a struct, and
2527             // these extra requirements are basically like where
2528             // clauses on the struct.
2529             AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2530             | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2531                 self.prove_closure_bounds(tcx, *def_id, substs, location)
2532             }
2533
2534             AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2535         };
2536
2537         self.normalize_and_prove_instantiated_predicates(
2538             instantiated_predicates,
2539             location.to_locations(),
2540         );
2541     }
2542
2543     fn prove_closure_bounds(
2544         &mut self,
2545         tcx: TyCtxt<'tcx>,
2546         def_id: DefId,
2547         substs: SubstsRef<'tcx>,
2548         location: Location,
2549     ) -> ty::InstantiatedPredicates<'tcx> {
2550         if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2551             let closure_constraints = QueryRegionConstraints {
2552                 outlives: closure_region_requirements.apply_requirements(tcx, def_id, substs),
2553
2554                 // Presently, closures never propagate member
2555                 // constraints to their parents -- they are enforced
2556                 // locally.  This is largely a non-issue as member
2557                 // constraints only come from `-> impl Trait` and
2558                 // friends which don't appear (thus far...) in
2559                 // closures.
2560                 member_constraints: vec![],
2561             };
2562
2563             let bounds_mapping = closure_constraints
2564                 .outlives
2565                 .iter()
2566                 .enumerate()
2567                 .filter_map(|(idx, constraint)| {
2568                     let ty::OutlivesPredicate(k1, r2) =
2569                         constraint.no_bound_vars().unwrap_or_else(|| {
2570                             bug!("query_constraint {:?} contained bound vars", constraint,);
2571                         });
2572
2573                     match k1.unpack() {
2574                         UnpackedKind::Lifetime(r1) => {
2575                             // constraint is r1: r2
2576                             let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2577                             let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2578                             let outlives_requirements =
2579                                 &closure_region_requirements.outlives_requirements[idx];
2580                             Some((
2581                                 (r1_vid, r2_vid),
2582                                 (
2583                                     outlives_requirements.category,
2584                                     outlives_requirements.blame_span,
2585                                 ),
2586                             ))
2587                         }
2588                         UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2589                     }
2590                 })
2591                 .collect();
2592
2593             let existing = self.borrowck_context
2594                 .constraints
2595                 .closure_bounds_mapping
2596                 .insert(location, bounds_mapping);
2597             assert!(
2598                 existing.is_none(),
2599                 "Multiple closures at the same location."
2600             );
2601
2602             self.push_region_constraints(
2603                 location.to_locations(),
2604                 ConstraintCategory::ClosureBounds,
2605                 &closure_constraints,
2606             );
2607         }
2608
2609         tcx.predicates_of(def_id).instantiate(tcx, substs)
2610     }
2611
2612     fn prove_trait_ref(
2613         &mut self,
2614         trait_ref: ty::TraitRef<'tcx>,
2615         locations: Locations,
2616         category: ConstraintCategory,
2617     ) {
2618         self.prove_predicates(
2619             Some(ty::Predicate::Trait(
2620                 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2621             )),
2622             locations,
2623             category,
2624         );
2625     }
2626
2627     fn normalize_and_prove_instantiated_predicates(
2628         &mut self,
2629         instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2630         locations: Locations,
2631     ) {
2632         for predicate in instantiated_predicates.predicates {
2633             let predicate = self.normalize(predicate, locations);
2634             self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2635         }
2636     }
2637
2638     fn prove_predicates(
2639         &mut self,
2640         predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2641         locations: Locations,
2642         category: ConstraintCategory,
2643     ) {
2644         for predicate in predicates {
2645             debug!(
2646                 "prove_predicates(predicate={:?}, locations={:?})",
2647                 predicate, locations,
2648             );
2649
2650             self.prove_predicate(predicate, locations, category);
2651         }
2652     }
2653
2654     fn prove_predicate(
2655         &mut self,
2656         predicate: ty::Predicate<'tcx>,
2657         locations: Locations,
2658         category: ConstraintCategory,
2659     ) {
2660         debug!(
2661             "prove_predicate(predicate={:?}, location={:?})",
2662             predicate, locations,
2663         );
2664
2665         let param_env = self.param_env;
2666         self.fully_perform_op(
2667             locations,
2668             category,
2669             param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2670         ).unwrap_or_else(|NoSolution| {
2671             span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2672         })
2673     }
2674
2675     fn typeck_mir(&mut self, body: &Body<'tcx>) {
2676         self.last_span = body.span;
2677         debug!("run_on_mir: {:?}", body.span);
2678
2679         for (local, local_decl) in body.local_decls.iter_enumerated() {
2680             self.check_local(body, local, local_decl);
2681         }
2682
2683         for (block, block_data) in body.basic_blocks().iter_enumerated() {
2684             let mut location = Location {
2685                 block,
2686                 statement_index: 0,
2687             };
2688             for stmt in &block_data.statements {
2689                 if !stmt.source_info.span.is_dummy() {
2690                     self.last_span = stmt.source_info.span;
2691                 }
2692                 self.check_stmt(body, stmt, location);
2693                 location.statement_index += 1;
2694             }
2695
2696             self.check_terminator(body, block_data.terminator(), location);
2697             self.check_iscleanup(body, block_data);
2698         }
2699     }
2700
2701     fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2702     where
2703         T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
2704     {
2705         debug!("normalize(value={:?}, location={:?})", value, location);
2706         let param_env = self.param_env;
2707         self.fully_perform_op(
2708             location.to_locations(),
2709             ConstraintCategory::Boring,
2710             param_env.and(type_op::normalize::Normalize::new(value)),
2711         ).unwrap_or_else(|NoSolution| {
2712             span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2713             value
2714         })
2715     }
2716 }
2717
2718 trait NormalizeLocation: fmt::Debug + Copy {
2719     fn to_locations(self) -> Locations;
2720 }
2721
2722 impl NormalizeLocation for Locations {
2723     fn to_locations(self) -> Locations {
2724         self
2725     }
2726 }
2727
2728 impl NormalizeLocation for Location {
2729     fn to_locations(self) -> Locations {
2730         Locations::Single(self)
2731     }
2732 }
2733
2734 #[derive(Debug, Default)]
2735 struct ObligationAccumulator<'tcx> {
2736     obligations: PredicateObligations<'tcx>,
2737 }
2738
2739 impl<'tcx> ObligationAccumulator<'tcx> {
2740     fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2741         let InferOk { value, obligations } = value;
2742         self.obligations.extend(obligations);
2743         value
2744     }
2745
2746     fn into_vec(self) -> PredicateObligations<'tcx> {
2747         self.obligations
2748     }
2749 }