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