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