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