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