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