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