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