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