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