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