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