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