]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/type_check/mod.rs
97a74e0d3365bbc701e823985ce4ae2980f7500c
[rust.git] / src / librustc_mir / borrow_check / nll / type_check / mod.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! This pass type-checks the MIR to ensure it is not broken.
12 #![allow(unreachable_code)]
13
14 use borrow_check::borrow_set::BorrowSet;
15 use borrow_check::location::LocationTable;
16 use borrow_check::nll::constraint_set::{ConstraintSet, OutlivesConstraint};
17 use borrow_check::nll::facts::AllFacts;
18 use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
19 use borrow_check::nll::universal_regions::UniversalRegions;
20 use borrow_check::nll::ToRegionVid;
21 use dataflow::move_paths::MoveData;
22 use dataflow::FlowAtLocation;
23 use dataflow::MaybeInitializedPlaces;
24 use rustc::hir;
25 use rustc::hir::def_id::DefId;
26 use rustc::infer::canonical::QueryRegionConstraint;
27 use rustc::infer::region_constraints::GenericKind;
28 use rustc::infer::{InferCtxt, LateBoundRegionConversionTime};
29 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
30 use rustc::mir::tcx::PlaceTy;
31 use rustc::mir::visit::{PlaceContext, Visitor};
32 use rustc::mir::*;
33 use rustc::traits::query::type_op;
34 use rustc::traits::query::{Fallible, NoSolution};
35 use rustc::ty::fold::TypeFoldable;
36 use rustc::ty::{self, ToPolyTraitRef, Ty, TyCtxt, TypeVariants};
37 use std::fmt;
38 use syntax_pos::{Span, DUMMY_SP};
39 use transform::{MirPass, MirSource};
40 use util::liveness::LivenessResults;
41
42 use rustc_data_structures::fx::FxHashSet;
43 use rustc_data_structures::indexed_vec::Idx;
44
45 macro_rules! span_mirbug {
46     ($context:expr, $elem:expr, $($message:tt)*) => ({
47         $crate::borrow_check::nll::type_check::mirbug(
48             $context.tcx(),
49             $context.last_span,
50             &format!(
51                 "broken MIR in {:?} ({:?}): {}",
52                 $context.mir_def_id,
53                 $elem,
54                 format_args!($($message)*),
55             ),
56         )
57     })
58 }
59
60 macro_rules! span_mirbug_and_err {
61     ($context:expr, $elem:expr, $($message:tt)*) => ({
62         {
63             span_mirbug!($context, $elem, $($message)*);
64             $context.error()
65         }
66     })
67 }
68
69 mod constraint_conversion;
70 mod input_output;
71 mod liveness;
72
73 /// Type checks the given `mir` in the context of the inference
74 /// context `infcx`. Returns any region constraints that have yet to
75 /// be proven. This result is includes liveness constraints that
76 /// ensure that regions appearing in the types of all local variables
77 /// are live at all points where that local variable may later be
78 /// used.
79 ///
80 /// This phase of type-check ought to be infallible -- this is because
81 /// the original, HIR-based type-check succeeded. So if any errors
82 /// occur here, we will get a `bug!` reported.
83 ///
84 /// # Parameters
85 ///
86 /// - `infcx` -- inference context to use
87 /// - `param_env` -- parameter environment to use for trait solving
88 /// - `mir` -- MIR to type-check
89 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
90 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
91 ///   and lifetimes (e.g., `&'a T` implies `T: 'a`)
92 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
93 ///   to outlive; should represent the fn body
94 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
95 ///   the types of the input parameters found in the MIR itself will be equated with these
96 /// - `output_ty` -- fully liberaetd, but **not** normalized, expected return type;
97 ///   the type for the RETURN_PLACE will be equated with this
98 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
99 ///   constraints for the regions in the types of variables
100 /// - `flow_inits` -- results of a maybe-init dataflow analysis
101 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
102 pub(crate) fn type_check<'gcx, 'tcx>(
103     infcx: &InferCtxt<'_, 'gcx, 'tcx>,
104     param_env: ty::ParamEnv<'gcx>,
105     mir: &Mir<'tcx>,
106     mir_def_id: DefId,
107     universal_regions: &UniversalRegions<'tcx>,
108     location_table: &LocationTable,
109     borrow_set: &BorrowSet<'tcx>,
110     liveness: &LivenessResults,
111     all_facts: &mut Option<AllFacts>,
112     flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
113     move_data: &MoveData<'tcx>,
114 ) -> MirTypeckRegionConstraints<'tcx> {
115     let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
116     type_check_internal(
117         infcx,
118         mir_def_id,
119         param_env,
120         mir,
121         &universal_regions.region_bound_pairs,
122         Some(implicit_region_bound),
123         Some(BorrowCheckContext {
124             universal_regions,
125             location_table,
126             borrow_set,
127             all_facts,
128         }),
129         &mut |cx| {
130             liveness::generate(cx, mir, liveness, flow_inits, move_data);
131
132             cx.equate_inputs_and_outputs(mir, mir_def_id, universal_regions);
133         },
134     )
135 }
136
137 fn type_check_internal<'gcx, 'tcx>(
138     infcx: &InferCtxt<'_, 'gcx, 'tcx>,
139     mir_def_id: DefId,
140     param_env: ty::ParamEnv<'gcx>,
141     mir: &Mir<'tcx>,
142     region_bound_pairs: &[(ty::Region<'tcx>, GenericKind<'tcx>)],
143     implicit_region_bound: Option<ty::Region<'tcx>>,
144     borrowck_context: Option<BorrowCheckContext<'_, 'tcx>>,
145     extra: &mut dyn FnMut(&mut TypeChecker<'_, 'gcx, 'tcx>),
146 ) -> MirTypeckRegionConstraints<'tcx> {
147     let mut checker = TypeChecker::new(
148         infcx,
149         mir,
150         mir_def_id,
151         param_env,
152         region_bound_pairs,
153         implicit_region_bound,
154         borrowck_context,
155     );
156     let errors_reported = {
157         let mut verifier = TypeVerifier::new(&mut checker, mir);
158         verifier.visit_mir(mir);
159         verifier.errors_reported
160     };
161
162     if !errors_reported {
163         // if verifier failed, don't do further checks to avoid ICEs
164         checker.typeck_mir(mir);
165     }
166
167     extra(&mut checker);
168
169     checker.constraints
170 }
171
172 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
173     // We sometimes see MIR failures (notably predicate failures) due to
174     // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
175     // to avoid reporting bugs in those cases.
176     tcx.sess.diagnostic().delay_span_bug(span, msg);
177 }
178
179 enum FieldAccessError {
180     OutOfRange { field_count: usize },
181 }
182
183 /// Verifies that MIR types are sane to not crash further checks.
184 ///
185 /// The sanitize_XYZ methods here take an MIR object and compute its
186 /// type, calling `span_mirbug` and returning an error type if there
187 /// is a problem.
188 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'b + 'tcx, 'tcx: 'b> {
189     cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
190     mir: &'a Mir<'tcx>,
191     last_span: Span,
192     mir_def_id: DefId,
193     errors_reported: bool,
194 }
195
196 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
197     fn visit_span(&mut self, span: &Span) {
198         if !span.is_dummy() {
199             self.last_span = *span;
200         }
201     }
202
203     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
204         self.sanitize_place(place, location, context);
205     }
206
207     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
208         self.super_constant(constant, location);
209         self.sanitize_constant(constant, location);
210         self.sanitize_type(constant, constant.ty);
211     }
212
213     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
214         self.super_rvalue(rvalue, location);
215         let rval_ty = rvalue.ty(self.mir, self.tcx());
216         self.sanitize_type(rvalue, rval_ty);
217     }
218
219     fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
220         self.super_local_decl(local, local_decl);
221         self.sanitize_type(local_decl, local_decl.ty);
222     }
223
224     fn visit_mir(&mut self, mir: &Mir<'tcx>) {
225         self.sanitize_type(&"return type", mir.return_ty());
226         for local_decl in &mir.local_decls {
227             self.sanitize_type(local_decl, local_decl.ty);
228         }
229         if self.errors_reported {
230             return;
231         }
232         self.super_mir(mir);
233     }
234 }
235
236 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
237     fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
238         TypeVerifier {
239             mir,
240             mir_def_id: cx.mir_def_id,
241             cx,
242             last_span: mir.span,
243             errors_reported: false,
244         }
245     }
246
247     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
248         self.cx.infcx.tcx
249     }
250
251     fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
252         if ty.has_escaping_regions() || ty.references_error() {
253             span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
254         } else {
255             ty
256         }
257     }
258
259     /// Checks that the constant's `ty` field matches up with what
260     /// would be expected from its literal.
261     fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
262         debug!(
263             "sanitize_constant(constant={:?}, location={:?})",
264             constant, location
265         );
266
267         let expected_ty = match constant.literal {
268             Literal::Value { value } => {
269                 // FIXME(#46702) -- We need some way to get the predicates
270                 // associated with the "pre-evaluated" form of the
271                 // constant. For example, consider that the constant
272                 // may have associated constant projections (`<Foo as
273                 // Trait<'a, 'b>>::SOME_CONST`) that impose
274                 // constraints on `'a` and `'b`. These constraints
275                 // would be lost if we just look at the normalized
276                 // value.
277                 if let ty::TyFnDef(def_id, substs) = value.ty.sty {
278                     let tcx = self.tcx();
279                     let type_checker = &mut self.cx;
280
281                     // FIXME -- For now, use the substitutions from
282                     // `value.ty` rather than `value.val`. The
283                     // renumberer will rewrite them to independent
284                     // sets of regions; in principle, we ought to
285                     // derive the type of the `value.val` from "first
286                     // principles" and equate with value.ty, but as we
287                     // are transitioning to the miri-based system, we
288                     // don't have a handy function for that, so for
289                     // now we just ignore `value.val` regions.
290
291                     let instantiated_predicates =
292                         tcx.predicates_of(def_id).instantiate(tcx, substs);
293                     type_checker.normalize_and_prove_instantiated_predicates(
294                         instantiated_predicates,
295                         location.boring(),
296                     );
297                 }
298
299                 value.ty
300             }
301
302             Literal::Promoted { .. } => {
303                 // FIXME -- promoted MIR return types reference
304                 // various "free regions" (e.g., scopes and things)
305                 // that they ought not to do. We have to figure out
306                 // how best to handle that -- probably we want treat
307                 // promoted MIR much like closures, renumbering all
308                 // their free regions and propagating constraints
309                 // upwards. We have the same acyclic guarantees, so
310                 // that should be possible. But for now, ignore them.
311                 //
312                 // let promoted_mir = &self.mir.promoted[index];
313                 // promoted_mir.return_ty()
314                 return;
315             }
316         };
317
318         debug!("sanitize_constant: expected_ty={:?}", expected_ty);
319
320         if let Err(terr) = self
321             .cx
322             .eq_types(expected_ty, constant.ty, location.boring())
323         {
324             span_mirbug!(
325                 self,
326                 constant,
327                 "constant {:?} should have type {:?} but has {:?} ({:?})",
328                 constant,
329                 expected_ty,
330                 constant.ty,
331                 terr,
332             );
333         }
334     }
335
336     /// Checks that the types internal to the `place` match up with
337     /// what would be expected.
338     fn sanitize_place(
339         &mut self,
340         place: &Place<'tcx>,
341         location: Location,
342         context: PlaceContext,
343     ) -> PlaceTy<'tcx> {
344         debug!("sanitize_place: {:?}", place);
345         let place_ty = match *place {
346             Place::Local(index) => PlaceTy::Ty {
347                 ty: self.mir.local_decls[index].ty,
348             },
349             Place::Static(box Static { def_id, ty: sty }) => {
350                 let sty = self.sanitize_type(place, sty);
351                 let ty = self.tcx().type_of(def_id);
352                 let ty = self.cx.normalize(ty, location);
353                 if let Err(terr) = self.cx.eq_types(ty, sty, location.boring()) {
354                     span_mirbug!(
355                         self,
356                         place,
357                         "bad static type ({:?}: {:?}): {:?}",
358                         ty,
359                         sty,
360                         terr
361                     );
362                 }
363                 PlaceTy::Ty { ty: sty }
364             }
365             Place::Projection(ref proj) => {
366                 let base_context = if context.is_mutating_use() {
367                     PlaceContext::Projection(Mutability::Mut)
368                 } else {
369                     PlaceContext::Projection(Mutability::Not)
370                 };
371                 let base_ty = self.sanitize_place(&proj.base, location, base_context);
372                 if let PlaceTy::Ty { ty } = base_ty {
373                     if ty.references_error() {
374                         assert!(self.errors_reported);
375                         return PlaceTy::Ty {
376                             ty: self.tcx().types.err,
377                         };
378                     }
379                 }
380                 self.sanitize_projection(base_ty, &proj.elem, place, location)
381             }
382         };
383         if let PlaceContext::Copy = context {
384             let tcx = self.tcx();
385             let trait_ref = ty::TraitRef {
386                 def_id: tcx.lang_items().copy_trait().unwrap(),
387                 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
388             };
389
390             // In order to have a Copy operand, the type T of the value must be Copy. Note that we
391             // prove that T: Copy, rather than using the type_moves_by_default test. This is
392             // important because type_moves_by_default ignores the resulting region obligations and
393             // assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
394             // (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
395             // fully apply: in effect, the rule is that if a value of some type could implement
396             // Copy, then it must.
397             self.cx.prove_trait_ref(trait_ref, location.interesting());
398         }
399         place_ty
400     }
401
402     fn sanitize_projection(
403         &mut self,
404         base: PlaceTy<'tcx>,
405         pi: &PlaceElem<'tcx>,
406         place: &Place<'tcx>,
407         location: Location,
408     ) -> PlaceTy<'tcx> {
409         debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
410         let tcx = self.tcx();
411         let base_ty = base.to_ty(tcx);
412         match *pi {
413             ProjectionElem::Deref => {
414                 let deref_ty = base_ty.builtin_deref(true);
415                 PlaceTy::Ty {
416                     ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
417                         span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
418                     }),
419                 }
420             }
421             ProjectionElem::Index(i) => {
422                 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
423                 if index_ty != tcx.types.usize {
424                     PlaceTy::Ty {
425                         ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
426                     }
427                 } else {
428                     PlaceTy::Ty {
429                         ty: base_ty.builtin_index().unwrap_or_else(|| {
430                             span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
431                         }),
432                     }
433                 }
434             }
435             ProjectionElem::ConstantIndex { .. } => {
436                 // consider verifying in-bounds
437                 PlaceTy::Ty {
438                     ty: base_ty.builtin_index().unwrap_or_else(|| {
439                         span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
440                     }),
441                 }
442             }
443             ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
444                 ty: match base_ty.sty {
445                     ty::TyArray(inner, size) => {
446                         let size = size.unwrap_usize(tcx);
447                         let min_size = (from as u64) + (to as u64);
448                         if let Some(rest_size) = size.checked_sub(min_size) {
449                             tcx.mk_array(inner, rest_size)
450                         } else {
451                             span_mirbug_and_err!(
452                                 self,
453                                 place,
454                                 "taking too-small slice of {:?}",
455                                 base_ty
456                             )
457                         }
458                     }
459                     ty::TySlice(..) => base_ty,
460                     _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
461                 },
462             },
463             ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
464                 ty::TyAdt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
465                     if index >= adt_def.variants.len() {
466                         PlaceTy::Ty {
467                             ty: span_mirbug_and_err!(
468                                 self,
469                                 place,
470                                 "cast to variant #{:?} but enum only has {:?}",
471                                 index,
472                                 adt_def.variants.len()
473                             ),
474                         }
475                     } else {
476                         PlaceTy::Downcast {
477                             adt_def,
478                             substs,
479                             variant_index: index,
480                         }
481                     }
482                 }
483                 _ => PlaceTy::Ty {
484                     ty: span_mirbug_and_err!(
485                         self,
486                         place,
487                         "can't downcast {:?} as {:?}",
488                         base_ty,
489                         adt_def1
490                     ),
491                 },
492             },
493             ProjectionElem::Field(field, fty) => {
494                 let fty = self.sanitize_type(place, fty);
495                 match self.field_ty(place, base, field, location) {
496                     Ok(ty) => if let Err(terr) = self.cx.eq_types(ty, fty, location.boring()) {
497                         span_mirbug!(
498                             self,
499                             place,
500                             "bad field access ({:?}: {:?}): {:?}",
501                             ty,
502                             fty,
503                             terr
504                         );
505                     },
506                     Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
507                         self,
508                         place,
509                         "accessed field #{} but variant only has {}",
510                         field.index(),
511                         field_count
512                     ),
513                 }
514                 PlaceTy::Ty { ty: fty }
515             }
516         }
517     }
518
519     fn error(&mut self) -> Ty<'tcx> {
520         self.errors_reported = true;
521         self.tcx().types.err
522     }
523
524     fn field_ty(
525         &mut self,
526         parent: &dyn fmt::Debug,
527         base_ty: PlaceTy<'tcx>,
528         field: Field,
529         location: Location,
530     ) -> Result<Ty<'tcx>, FieldAccessError> {
531         let tcx = self.tcx();
532
533         let (variant, substs) = match base_ty {
534             PlaceTy::Downcast {
535                 adt_def,
536                 substs,
537                 variant_index,
538             } => (&adt_def.variants[variant_index], substs),
539             PlaceTy::Ty { ty } => match ty.sty {
540                 ty::TyAdt(adt_def, substs) if !adt_def.is_enum() => (&adt_def.variants[0], substs),
541                 ty::TyClosure(def_id, substs) => {
542                     return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
543                         Some(ty) => Ok(ty),
544                         None => Err(FieldAccessError::OutOfRange {
545                             field_count: substs.upvar_tys(def_id, tcx).count(),
546                         }),
547                     }
548                 }
549                 ty::TyGenerator(def_id, substs, _) => {
550                     // Try pre-transform fields first (upvars and current state)
551                     if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
552                         return Ok(ty);
553                     }
554
555                     // Then try `field_tys` which contains all the fields, but it
556                     // requires the final optimized MIR.
557                     return match substs.field_tys(def_id, tcx).nth(field.index()) {
558                         Some(ty) => Ok(ty),
559                         None => Err(FieldAccessError::OutOfRange {
560                             field_count: substs.field_tys(def_id, tcx).count(),
561                         }),
562                     };
563                 }
564                 ty::TyTuple(tys) => {
565                     return match tys.get(field.index()) {
566                         Some(&ty) => Ok(ty),
567                         None => Err(FieldAccessError::OutOfRange {
568                             field_count: tys.len(),
569                         }),
570                     }
571                 }
572                 _ => {
573                     return Ok(span_mirbug_and_err!(
574                         self,
575                         parent,
576                         "can't project out of {:?}",
577                         base_ty
578                     ))
579                 }
580             },
581         };
582
583         if let Some(field) = variant.fields.get(field.index()) {
584             Ok(self.cx.normalize(&field.ty(tcx, substs), location))
585         } else {
586             Err(FieldAccessError::OutOfRange {
587                 field_count: variant.fields.len(),
588             })
589         }
590     }
591 }
592
593 /// The MIR type checker. Visits the MIR and enforces all the
594 /// constraints needed for it to be valid and well-typed. Along the
595 /// way, it accrues region constraints -- these can later be used by
596 /// NLL region checking.
597 struct TypeChecker<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
598     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
599     param_env: ty::ParamEnv<'gcx>,
600     last_span: Span,
601     mir: &'a Mir<'tcx>,
602     mir_def_id: DefId,
603     region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
604     implicit_region_bound: Option<ty::Region<'tcx>>,
605     reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
606     constraints: MirTypeckRegionConstraints<'tcx>,
607     borrowck_context: Option<BorrowCheckContext<'a, 'tcx>>,
608 }
609
610 struct BorrowCheckContext<'a, 'tcx: 'a> {
611     universal_regions: &'a UniversalRegions<'tcx>,
612     location_table: &'a LocationTable,
613     all_facts: &'a mut Option<AllFacts>,
614     borrow_set: &'a BorrowSet<'tcx>,
615 }
616
617 /// A collection of region constraints that must be satisfied for the
618 /// program to be considered well-typed.
619 #[derive(Default)]
620 crate struct MirTypeckRegionConstraints<'tcx> {
621     /// In general, the type-checker is not responsible for enforcing
622     /// liveness constraints; this job falls to the region inferencer,
623     /// which performs a liveness analysis. However, in some limited
624     /// cases, the MIR type-checker creates temporary regions that do
625     /// not otherwise appear in the MIR -- in particular, the
626     /// late-bound regions that it instantiates at call-sites -- and
627     /// hence it must report on their liveness constraints.
628     crate liveness_set: Vec<(ty::Region<'tcx>, Location)>,
629
630     crate outlives_constraints: ConstraintSet,
631
632     crate type_tests: Vec<TypeTest<'tcx>>,
633 }
634
635 /// The `Locations` type summarizes *where* region constraints are
636 /// required to hold. Normally, this is at a particular point which
637 /// created the obligation, but for constraints that the user gave, we
638 /// want the constraint to hold at all points.
639 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
640 pub enum Locations {
641     /// Indicates that a type constraint should always be true. This
642     /// is particularly important in the new borrowck analysis for
643     /// things like the type of the return slot. Consider this
644     /// example:
645     ///
646     /// ```
647     /// fn foo<'a>(x: &'a u32) -> &'a u32 {
648     ///     let y = 22;
649     ///     return &y; // error
650     /// }
651     /// ```
652     ///
653     /// Here, we wind up with the signature from the return type being
654     /// something like `&'1 u32` where `'1` is a universal region. But
655     /// the type of the return slot `_0` is something like `&'2 u32`
656     /// where `'2` is an existential region variable. The type checker
657     /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
658     /// older NLL analysis, we required this only at the entry point
659     /// to the function. By the nature of the constraints, this wound
660     /// up propagating to all points reachable from start (because
661     /// `'1` -- as a universal region -- is live everywhere).  In the
662     /// newer analysis, though, this doesn't work: `_0` is considered
663     /// dead at the start (it has no usable value) and hence this type
664     /// equality is basically a no-op. Then, later on, when we do `_0
665     /// = &'3 y`, that region `'3` never winds up related to the
666     /// universal region `'1` and hence no error occurs. Therefore, we
667     /// use Locations::All instead, which ensures that the `'1` and
668     /// `'2` are equal everything. We also use this for other
669     /// user-given type annotations; e.g., if the user wrote `let mut
670     /// x: &'static u32 = ...`, we would ensure that all values
671     /// assigned to `x` are of `'static` lifetime.
672     All,
673
674     /// A "boring" constraint (caused by the given location) is one that
675     /// the user probably doesn't want to see described in diagnostics,
676     /// because it is kind of an artifact of the type system setup.
677     ///
678     /// Example: `x = Foo { field: y }` technically creates
679     /// intermediate regions representing the "type of `Foo { field: y
680     /// }`", and data flows from `y` into those variables, but they
681     /// are not very interesting. The assignment into `x` on the other
682     /// hand might be.
683     Boring(Location),
684
685     /// An *important* outlives constraint (caused by the given
686     /// location) is one that would be useful to highlight in
687     /// diagnostics, because it represents a point where references
688     /// flow from one spot to another (e.g., `x = y`)
689     Interesting(Location),
690 }
691
692 impl Locations {
693     pub fn from_location(&self) -> Option<Location> {
694         match self {
695             Locations::All => None,
696             Locations::Boring(from_location) | Locations::Interesting(from_location) => {
697                 Some(*from_location)
698             }
699         }
700     }
701
702     /// Gets a span representing the location.
703     pub fn span(&self, mir: &Mir<'_>) -> Span {
704         let span_location = match self {
705             Locations::All => Location::START,
706             Locations::Boring(l) | Locations::Interesting(l) => *l,
707         };
708         mir.source_info(span_location).span
709     }
710 }
711
712 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
713     fn new(
714         infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
715         mir: &'a Mir<'tcx>,
716         mir_def_id: DefId,
717         param_env: ty::ParamEnv<'gcx>,
718         region_bound_pairs: &'a [(ty::Region<'tcx>, GenericKind<'tcx>)],
719         implicit_region_bound: Option<ty::Region<'tcx>>,
720         borrowck_context: Option<BorrowCheckContext<'a, 'tcx>>,
721     ) -> Self {
722         TypeChecker {
723             infcx,
724             last_span: DUMMY_SP,
725             mir,
726             mir_def_id,
727             param_env,
728             region_bound_pairs,
729             implicit_region_bound,
730             borrowck_context,
731             reported_errors: FxHashSet(),
732             constraints: MirTypeckRegionConstraints::default(),
733         }
734     }
735
736     /// Given some operation `op` that manipulates types, proves
737     /// predicates, or otherwise uses the inference context, executes
738     /// `op` and then executes all the further obligations that `op`
739     /// returns. This will yield a set of outlives constraints amongst
740     /// regions which are extracted and stored as having occured at
741     /// `locations`.
742     ///
743     /// **Any `rustc::infer` operations that might generate region
744     /// constraints should occur within this method so that those
745     /// constraints can be properly localized!**
746     fn fully_perform_op<R>(
747         &mut self,
748         locations: Locations,
749         op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
750     ) -> Fallible<R> {
751         let (r, opt_data) = op.fully_perform(self.infcx)?;
752
753         if let Some(data) = &opt_data {
754             self.push_region_constraints(locations, data);
755         }
756
757         Ok(r)
758     }
759
760     fn push_region_constraints(
761         &mut self,
762         locations: Locations,
763         data: &[QueryRegionConstraint<'tcx>],
764     ) {
765         debug!(
766             "push_region_constraints: constraints generated at {:?} are {:#?}",
767             locations, data
768         );
769
770         if let Some(borrowck_context) = &mut self.borrowck_context {
771             constraint_conversion::ConstraintConversion::new(
772                 self.infcx.tcx,
773                 borrowck_context.universal_regions,
774                 borrowck_context.location_table,
775                 self.region_bound_pairs,
776                 self.implicit_region_bound,
777                 self.param_env,
778                 locations,
779                 &mut self.constraints.outlives_constraints,
780                 &mut self.constraints.type_tests,
781                 &mut borrowck_context.all_facts,
782             ).convert_all(&data);
783         }
784     }
785
786     fn sub_types(&mut self, sub: Ty<'tcx>, sup: Ty<'tcx>, locations: Locations) -> Fallible<()> {
787         let param_env = self.param_env;
788         self.fully_perform_op(
789             locations,
790             param_env.and(type_op::subtype::Subtype::new(sub, sup)),
791         )
792     }
793
794     fn eq_types(&mut self, a: Ty<'tcx>, b: Ty<'tcx>, locations: Locations) -> Fallible<()> {
795         let param_env = self.param_env;
796         self.fully_perform_op(locations, param_env.and(type_op::eq::Eq::new(b, a)))
797     }
798
799     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
800         self.infcx.tcx
801     }
802
803     fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
804         debug!("check_stmt: {:?}", stmt);
805         let tcx = self.tcx();
806         match stmt.kind {
807             StatementKind::Assign(ref place, ref rv) => {
808                 // Assignments to temporaries are not "interesting";
809                 // they are not caused by the user, but rather artifacts
810                 // of lowering. Assignments to other sorts of places *are* interesting
811                 // though.
812                 let is_temp = if let Place::Local(l) = place {
813                     !mir.local_decls[*l].is_user_variable.is_some()
814                 } else {
815                     false
816                 };
817
818                 let locations = if is_temp {
819                     location.boring()
820                 } else {
821                     location.interesting()
822                 };
823
824                 let place_ty = place.ty(mir, tcx).to_ty(tcx);
825                 let rv_ty = rv.ty(mir, tcx);
826                 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
827                     span_mirbug!(
828                         self,
829                         stmt,
830                         "bad assignment ({:?} = {:?}): {:?}",
831                         place_ty,
832                         rv_ty,
833                         terr
834                     );
835                 }
836                 self.check_rvalue(mir, rv, location);
837                 let trait_ref = ty::TraitRef {
838                     def_id: tcx.lang_items().sized_trait().unwrap(),
839                     substs: tcx.mk_substs_trait(place_ty, &[]),
840                 };
841                 self.prove_trait_ref(trait_ref, location.interesting());
842             }
843             StatementKind::SetDiscriminant {
844                 ref place,
845                 variant_index,
846             } => {
847                 let place_type = place.ty(mir, tcx).to_ty(tcx);
848                 let adt = match place_type.sty {
849                     TypeVariants::TyAdt(adt, _) if adt.is_enum() => adt,
850                     _ => {
851                         span_bug!(
852                             stmt.source_info.span,
853                             "bad set discriminant ({:?} = {:?}): lhs is not an enum",
854                             place,
855                             variant_index
856                         );
857                     }
858                 };
859                 if variant_index >= adt.variants.len() {
860                     span_bug!(
861                         stmt.source_info.span,
862                         "bad set discriminant ({:?} = {:?}): value of of range",
863                         place,
864                         variant_index
865                     );
866                 };
867             }
868             StatementKind::UserAssertTy(ref c_ty, ref local) => {
869                 let local_ty = mir.local_decls()[*local].ty;
870                 let (ty, _) = self.infcx
871                     .instantiate_canonical_with_fresh_inference_vars(stmt.source_info.span, c_ty);
872                 debug!(
873                     "check_stmt: user_assert_ty ty={:?} local_ty={:?}",
874                     ty, local_ty
875                 );
876                 if let Err(terr) = self.eq_types(ty, local_ty, Locations::All) {
877                     span_mirbug!(
878                         self,
879                         stmt,
880                         "bad type assert ({:?} = {:?}): {:?}",
881                         ty,
882                         local_ty,
883                         terr
884                     );
885                 }
886             }
887             StatementKind::ReadForMatch(_)
888             | StatementKind::StorageLive(_)
889             | StatementKind::StorageDead(_)
890             | StatementKind::InlineAsm { .. }
891             | StatementKind::EndRegion(_)
892             | StatementKind::Validate(..)
893             | StatementKind::Nop => {}
894         }
895     }
896
897     fn check_terminator(
898         &mut self,
899         mir: &Mir<'tcx>,
900         term: &Terminator<'tcx>,
901         term_location: Location,
902     ) {
903         debug!("check_terminator: {:?}", term);
904         let tcx = self.tcx();
905         match term.kind {
906             TerminatorKind::Goto { .. }
907             | TerminatorKind::Resume
908             | TerminatorKind::Abort
909             | TerminatorKind::Return
910             | TerminatorKind::GeneratorDrop
911             | TerminatorKind::Unreachable
912             | TerminatorKind::Drop { .. }
913             | TerminatorKind::FalseEdges { .. }
914             | TerminatorKind::FalseUnwind { .. } => {
915                 // no checks needed for these
916             }
917
918             TerminatorKind::DropAndReplace {
919                 ref location,
920                 ref value,
921                 target: _,
922                 unwind: _,
923             } => {
924                 let place_ty = location.ty(mir, tcx).to_ty(tcx);
925                 let rv_ty = value.ty(mir, tcx);
926
927                 let locations = term_location.interesting();
928                 if let Err(terr) = self.sub_types(rv_ty, place_ty, locations) {
929                     span_mirbug!(
930                         self,
931                         term,
932                         "bad DropAndReplace ({:?} = {:?}): {:?}",
933                         place_ty,
934                         rv_ty,
935                         terr
936                     );
937                 }
938             }
939             TerminatorKind::SwitchInt {
940                 ref discr,
941                 switch_ty,
942                 ..
943             } => {
944                 let discr_ty = discr.ty(mir, tcx);
945                 if let Err(terr) = self.sub_types(discr_ty, switch_ty, term_location.boring()) {
946                     span_mirbug!(
947                         self,
948                         term,
949                         "bad SwitchInt ({:?} on {:?}): {:?}",
950                         switch_ty,
951                         discr_ty,
952                         terr
953                     );
954                 }
955                 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
956                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
957                 }
958                 // FIXME: check the values
959             }
960             TerminatorKind::Call {
961                 ref func,
962                 ref args,
963                 ref destination,
964                 ..
965             } => {
966                 let func_ty = func.ty(mir, tcx);
967                 debug!("check_terminator: call, func_ty={:?}", func_ty);
968                 let sig = match func_ty.sty {
969                     ty::TyFnDef(..) | ty::TyFnPtr(_) => func_ty.fn_sig(tcx),
970                     _ => {
971                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
972                         return;
973                     }
974                 };
975                 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
976                     term.source_info.span,
977                     LateBoundRegionConversionTime::FnCall,
978                     &sig,
979                 );
980                 let sig = self.normalize(sig, term_location);
981                 self.check_call_dest(mir, term, &sig, destination, term_location);
982
983                 self.prove_predicates(
984                     sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
985                     term_location.boring(),
986                 );
987
988                 // The ordinary liveness rules will ensure that all
989                 // regions in the type of the callee are live here. We
990                 // then further constrain the late-bound regions that
991                 // were instantiated at the call site to be live as
992                 // well. The resulting is that all the input (and
993                 // output) types in the signature must be live, since
994                 // all the inputs that fed into it were live.
995                 for &late_bound_region in map.values() {
996                     self.constraints
997                         .liveness_set
998                         .push((late_bound_region, term_location));
999                 }
1000
1001                 self.check_call_inputs(mir, term, &sig, args, term_location);
1002             }
1003             TerminatorKind::Assert {
1004                 ref cond, ref msg, ..
1005             } => {
1006                 let cond_ty = cond.ty(mir, tcx);
1007                 if cond_ty != tcx.types.bool {
1008                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1009                 }
1010
1011                 if let BoundsCheck { ref len, ref index } = *msg {
1012                     if len.ty(mir, tcx) != tcx.types.usize {
1013                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1014                     }
1015                     if index.ty(mir, tcx) != tcx.types.usize {
1016                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1017                     }
1018                 }
1019             }
1020             TerminatorKind::Yield { ref value, .. } => {
1021                 let value_ty = value.ty(mir, tcx);
1022                 match mir.yield_ty {
1023                     None => span_mirbug!(self, term, "yield in non-generator"),
1024                     Some(ty) => {
1025                         if let Err(terr) = self.sub_types(value_ty, ty, term_location.interesting())
1026                         {
1027                             span_mirbug!(
1028                                 self,
1029                                 term,
1030                                 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1031                                 value_ty,
1032                                 ty,
1033                                 terr
1034                             );
1035                         }
1036                     }
1037                 }
1038             }
1039         }
1040     }
1041
1042     fn check_call_dest(
1043         &mut self,
1044         mir: &Mir<'tcx>,
1045         term: &Terminator<'tcx>,
1046         sig: &ty::FnSig<'tcx>,
1047         destination: &Option<(Place<'tcx>, BasicBlock)>,
1048         term_location: Location,
1049     ) {
1050         let tcx = self.tcx();
1051         match *destination {
1052             Some((ref dest, _target_block)) => {
1053                 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1054                 let locations = term_location.interesting();
1055                 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations) {
1056                     span_mirbug!(
1057                         self,
1058                         term,
1059                         "call dest mismatch ({:?} <- {:?}): {:?}",
1060                         dest_ty,
1061                         sig.output(),
1062                         terr
1063                     );
1064                 }
1065             }
1066             None => {
1067                 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1068                 if !sig.output().is_never() {
1069                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1070                 }
1071             }
1072         }
1073     }
1074
1075     fn check_call_inputs(
1076         &mut self,
1077         mir: &Mir<'tcx>,
1078         term: &Terminator<'tcx>,
1079         sig: &ty::FnSig<'tcx>,
1080         args: &[Operand<'tcx>],
1081         term_location: Location,
1082     ) {
1083         debug!("check_call_inputs({:?}, {:?})", sig, args);
1084         if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1085             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1086         }
1087         for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1088             let op_arg_ty = op_arg.ty(mir, self.tcx());
1089             if let Err(terr) = self.sub_types(op_arg_ty, fn_arg, term_location.interesting()) {
1090                 span_mirbug!(
1091                     self,
1092                     term,
1093                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1094                     n,
1095                     fn_arg,
1096                     op_arg_ty,
1097                     terr
1098                 );
1099             }
1100         }
1101     }
1102
1103     fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1104         let is_cleanup = block_data.is_cleanup;
1105         self.last_span = block_data.terminator().source_info.span;
1106         match block_data.terminator().kind {
1107             TerminatorKind::Goto { target } => {
1108                 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1109             }
1110             TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1111                 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1112             },
1113             TerminatorKind::Resume => if !is_cleanup {
1114                 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1115             },
1116             TerminatorKind::Abort => if !is_cleanup {
1117                 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1118             },
1119             TerminatorKind::Return => if is_cleanup {
1120                 span_mirbug!(self, block_data, "return on cleanup block")
1121             },
1122             TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1123                 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1124             },
1125             TerminatorKind::Yield { resume, drop, .. } => {
1126                 if is_cleanup {
1127                     span_mirbug!(self, block_data, "yield in cleanup block")
1128                 }
1129                 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1130                 if let Some(drop) = drop {
1131                     self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1132                 }
1133             }
1134             TerminatorKind::Unreachable => {}
1135             TerminatorKind::Drop { target, unwind, .. }
1136             | TerminatorKind::DropAndReplace { target, unwind, .. }
1137             | TerminatorKind::Assert {
1138                 target,
1139                 cleanup: unwind,
1140                 ..
1141             } => {
1142                 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1143                 if let Some(unwind) = unwind {
1144                     if is_cleanup {
1145                         span_mirbug!(self, block_data, "unwind on cleanup block")
1146                     }
1147                     self.assert_iscleanup(mir, block_data, unwind, true);
1148                 }
1149             }
1150             TerminatorKind::Call {
1151                 ref destination,
1152                 cleanup,
1153                 ..
1154             } => {
1155                 if let &Some((_, target)) = destination {
1156                     self.assert_iscleanup(mir, block_data, target, is_cleanup);
1157                 }
1158                 if let Some(cleanup) = cleanup {
1159                     if is_cleanup {
1160                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1161                     }
1162                     self.assert_iscleanup(mir, block_data, cleanup, true);
1163                 }
1164             }
1165             TerminatorKind::FalseEdges {
1166                 real_target,
1167                 ref imaginary_targets,
1168             } => {
1169                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1170                 for target in imaginary_targets {
1171                     self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1172                 }
1173             }
1174             TerminatorKind::FalseUnwind {
1175                 real_target,
1176                 unwind,
1177             } => {
1178                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1179                 if let Some(unwind) = unwind {
1180                     if is_cleanup {
1181                         span_mirbug!(
1182                             self,
1183                             block_data,
1184                             "cleanup in cleanup block via false unwind"
1185                         );
1186                     }
1187                     self.assert_iscleanup(mir, block_data, unwind, true);
1188                 }
1189             }
1190         }
1191     }
1192
1193     fn assert_iscleanup(
1194         &mut self,
1195         mir: &Mir<'tcx>,
1196         ctxt: &dyn fmt::Debug,
1197         bb: BasicBlock,
1198         iscleanuppad: bool,
1199     ) {
1200         if mir[bb].is_cleanup != iscleanuppad {
1201             span_mirbug!(
1202                 self,
1203                 ctxt,
1204                 "cleanuppad mismatch: {:?} should be {:?}",
1205                 bb,
1206                 iscleanuppad
1207             );
1208         }
1209     }
1210
1211     fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1212         match mir.local_kind(local) {
1213             LocalKind::ReturnPointer | LocalKind::Arg => {
1214                 // return values of normal functions are required to be
1215                 // sized by typeck, but return values of ADT constructors are
1216                 // not because we don't include a `Self: Sized` bounds on them.
1217                 //
1218                 // Unbound parts of arguments were never required to be Sized
1219                 // - maybe we should make that a warning.
1220                 return;
1221             }
1222             LocalKind::Var | LocalKind::Temp => {}
1223         }
1224
1225         let span = local_decl.source_info.span;
1226         let ty = local_decl.ty;
1227
1228         // Erase the regions from `ty` to get a global type.  The
1229         // `Sized` bound in no way depends on precise regions, so this
1230         // shouldn't affect `is_sized`.
1231         let gcx = self.tcx().global_tcx();
1232         let erased_ty = gcx.lift(&self.tcx().erase_regions(&ty)).unwrap();
1233         if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1234             // in current MIR construction, all non-control-flow rvalue
1235             // expressions evaluate through `as_temp` or `into` a return
1236             // slot or local, so to find all unsized rvalues it is enough
1237             // to check all temps, return slots and locals.
1238             if let None = self.reported_errors.replace((ty, span)) {
1239                 span_err!(
1240                     self.tcx().sess,
1241                     span,
1242                     E0161,
1243                     "cannot move a value of type {0}: the size of {0} \
1244                      cannot be statically determined",
1245                     ty
1246                 );
1247             }
1248         }
1249     }
1250
1251     fn aggregate_field_ty(
1252         &mut self,
1253         ak: &AggregateKind<'tcx>,
1254         field_index: usize,
1255         location: Location,
1256     ) -> Result<Ty<'tcx>, FieldAccessError> {
1257         let tcx = self.tcx();
1258
1259         match *ak {
1260             AggregateKind::Adt(def, variant_index, substs, active_field_index) => {
1261                 let variant = &def.variants[variant_index];
1262                 let adj_field_index = active_field_index.unwrap_or(field_index);
1263                 if let Some(field) = variant.fields.get(adj_field_index) {
1264                     Ok(self.normalize(field.ty(tcx, substs), location))
1265                 } else {
1266                     Err(FieldAccessError::OutOfRange {
1267                         field_count: variant.fields.len(),
1268                     })
1269                 }
1270             }
1271             AggregateKind::Closure(def_id, substs) => {
1272                 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1273                     Some(ty) => Ok(ty),
1274                     None => Err(FieldAccessError::OutOfRange {
1275                         field_count: substs.upvar_tys(def_id, tcx).count(),
1276                     }),
1277                 }
1278             }
1279             AggregateKind::Generator(def_id, substs, _) => {
1280                 // Try pre-transform fields first (upvars and current state)
1281                 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1282                     Ok(ty)
1283                 } else {
1284                     // Then try `field_tys` which contains all the fields, but it
1285                     // requires the final optimized MIR.
1286                     match substs.field_tys(def_id, tcx).nth(field_index) {
1287                         Some(ty) => Ok(ty),
1288                         None => Err(FieldAccessError::OutOfRange {
1289                             field_count: substs.field_tys(def_id, tcx).count(),
1290                         }),
1291                     }
1292                 }
1293             }
1294             AggregateKind::Array(ty) => Ok(ty),
1295             AggregateKind::Tuple => {
1296                 unreachable!("This should have been covered in check_rvalues");
1297             }
1298         }
1299     }
1300
1301     fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1302         let tcx = self.tcx();
1303
1304         match rvalue {
1305             Rvalue::Aggregate(ak, ops) => {
1306                 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1307             }
1308
1309             Rvalue::Repeat(operand, len) => if *len > 1 {
1310                 let operand_ty = operand.ty(mir, tcx);
1311
1312                 let trait_ref = ty::TraitRef {
1313                     def_id: tcx.lang_items().copy_trait().unwrap(),
1314                     substs: tcx.mk_substs_trait(operand_ty, &[]),
1315                 };
1316
1317                 self.prove_trait_ref(trait_ref, location.interesting());
1318             },
1319
1320             Rvalue::NullaryOp(_, ty) => {
1321                 let trait_ref = ty::TraitRef {
1322                     def_id: tcx.lang_items().sized_trait().unwrap(),
1323                     substs: tcx.mk_substs_trait(ty, &[]),
1324                 };
1325
1326                 self.prove_trait_ref(trait_ref, location.interesting());
1327             }
1328
1329             Rvalue::Cast(cast_kind, op, ty) => match cast_kind {
1330                 CastKind::ReifyFnPointer => {
1331                     let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1332
1333                     // The type that we see in the fcx is like
1334                     // `foo::<'a, 'b>`, where `foo` is the path to a
1335                     // function definition. When we extract the
1336                     // signature, it comes from the `fn_sig` query,
1337                     // and hence may contain unnormalized results.
1338                     let fn_sig = self.normalize(fn_sig, location);
1339
1340                     let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1341
1342                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1343                         span_mirbug!(
1344                             self,
1345                             rvalue,
1346                             "equating {:?} with {:?} yields {:?}",
1347                             ty_fn_ptr_from,
1348                             ty,
1349                             terr
1350                         );
1351                     }
1352                 }
1353
1354                 CastKind::ClosureFnPointer => {
1355                     let sig = match op.ty(mir, tcx).sty {
1356                         ty::TyClosure(def_id, substs) => {
1357                             substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1358                         }
1359                         _ => bug!(),
1360                     };
1361                     let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1362
1363                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1364                         span_mirbug!(
1365                             self,
1366                             rvalue,
1367                             "equating {:?} with {:?} yields {:?}",
1368                             ty_fn_ptr_from,
1369                             ty,
1370                             terr
1371                         );
1372                     }
1373                 }
1374
1375                 CastKind::UnsafeFnPointer => {
1376                     let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1377
1378                     // The type that we see in the fcx is like
1379                     // `foo::<'a, 'b>`, where `foo` is the path to a
1380                     // function definition. When we extract the
1381                     // signature, it comes from the `fn_sig` query,
1382                     // and hence may contain unnormalized results.
1383                     let fn_sig = self.normalize(fn_sig, location);
1384
1385                     let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1386
1387                     if let Err(terr) = self.eq_types(ty_fn_ptr_from, ty, location.interesting()) {
1388                         span_mirbug!(
1389                             self,
1390                             rvalue,
1391                             "equating {:?} with {:?} yields {:?}",
1392                             ty_fn_ptr_from,
1393                             ty,
1394                             terr
1395                         );
1396                     }
1397                 }
1398
1399                 CastKind::Unsize => {
1400                     let &ty = ty;
1401                     let trait_ref = ty::TraitRef {
1402                         def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1403                         substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1404                     };
1405
1406                     self.prove_trait_ref(trait_ref, location.interesting());
1407                 }
1408
1409                 CastKind::Misc => {}
1410             },
1411
1412             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1413                 self.add_reborrow_constraint(location, region, borrowed_place);
1414             }
1415
1416             // FIXME: These other cases have to be implemented in future PRs
1417             Rvalue::Use(..)
1418             | Rvalue::Len(..)
1419             | Rvalue::BinaryOp(..)
1420             | Rvalue::CheckedBinaryOp(..)
1421             | Rvalue::UnaryOp(..)
1422             | Rvalue::Discriminant(..) => {}
1423         }
1424     }
1425
1426     fn check_aggregate_rvalue(
1427         &mut self,
1428         mir: &Mir<'tcx>,
1429         rvalue: &Rvalue<'tcx>,
1430         aggregate_kind: &AggregateKind<'tcx>,
1431         operands: &[Operand<'tcx>],
1432         location: Location,
1433     ) {
1434         let tcx = self.tcx();
1435
1436         self.prove_aggregate_predicates(aggregate_kind, location);
1437
1438         if *aggregate_kind == AggregateKind::Tuple {
1439             // tuple rvalue field type is always the type of the op. Nothing to check here.
1440             return;
1441         }
1442
1443         for (i, operand) in operands.iter().enumerate() {
1444             let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
1445                 Ok(field_ty) => field_ty,
1446                 Err(FieldAccessError::OutOfRange { field_count }) => {
1447                     span_mirbug!(
1448                         self,
1449                         rvalue,
1450                         "accessed field #{} but variant only has {}",
1451                         i,
1452                         field_count
1453                     );
1454                     continue;
1455                 }
1456             };
1457             let operand_ty = operand.ty(mir, tcx);
1458
1459             if let Err(terr) = self.sub_types(operand_ty, field_ty, location.boring()) {
1460                 span_mirbug!(
1461                     self,
1462                     rvalue,
1463                     "{:?} is not a subtype of {:?}: {:?}",
1464                     operand_ty,
1465                     field_ty,
1466                     terr
1467                 );
1468             }
1469         }
1470     }
1471
1472     /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
1473     ///
1474     /// # Parameters
1475     ///
1476     /// - `location`: the location `L` where the borrow expression occurs
1477     /// - `borrow_region`: the region `'a` associated with the borrow
1478     /// - `borrowed_place`: the place `P` being borrowed
1479     fn add_reborrow_constraint(
1480         &mut self,
1481         location: Location,
1482         borrow_region: ty::Region<'tcx>,
1483         borrowed_place: &Place<'tcx>,
1484     ) {
1485         // These constraints are only meaningful during borrowck:
1486         let BorrowCheckContext {
1487             borrow_set,
1488             location_table,
1489             all_facts,
1490             ..
1491         } = match &mut self.borrowck_context {
1492             Some(borrowck_context) => borrowck_context,
1493             None => return,
1494         };
1495
1496         // In Polonius mode, we also push a `borrow_region` fact
1497         // linking the loan to the region (in some cases, though,
1498         // there is no loan associated with this borrow expression --
1499         // that occurs when we are borrowing an unsafe place, for
1500         // example).
1501         if let Some(all_facts) = all_facts {
1502             if let Some(borrow_index) = borrow_set.location_map.get(&location) {
1503                 let region_vid = borrow_region.to_region_vid();
1504                 all_facts.borrow_region.push((
1505                     region_vid,
1506                     *borrow_index,
1507                     location_table.mid_index(location),
1508                 ));
1509             }
1510         }
1511
1512         // If we are reborrowing the referent of another reference, we
1513         // need to add outlives relationships. In a case like `&mut
1514         // *p`, where the `p` has type `&'b mut Foo`, for example, we
1515         // need to ensure that `'b: 'a`.
1516
1517         let mut borrowed_place = borrowed_place;
1518
1519         debug!(
1520             "add_reborrow_constraint({:?}, {:?}, {:?})",
1521             location, borrow_region, borrowed_place
1522         );
1523         while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
1524             debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
1525
1526             match *elem {
1527                 ProjectionElem::Deref => {
1528                     let tcx = self.infcx.tcx;
1529                     let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
1530
1531                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
1532                     match base_ty.sty {
1533                         ty::TyRef(ref_region, _, mutbl) => {
1534                             self.constraints
1535                                 .outlives_constraints
1536                                 .push(OutlivesConstraint {
1537                                     sup: ref_region.to_region_vid(),
1538                                     sub: borrow_region.to_region_vid(),
1539                                     locations: location.boring(),
1540                                 });
1541
1542                             if let Some(all_facts) = all_facts {
1543                                 all_facts.outlives.push((
1544                                     ref_region.to_region_vid(),
1545                                     borrow_region.to_region_vid(),
1546                                     location_table.mid_index(location),
1547                                 ));
1548                             }
1549
1550                             match mutbl {
1551                                 hir::Mutability::MutImmutable => {
1552                                     // Immutable reference. We don't need the base
1553                                     // to be valid for the entire lifetime of
1554                                     // the borrow.
1555                                     break;
1556                                 }
1557                                 hir::Mutability::MutMutable => {
1558                                     // Mutable reference. We *do* need the base
1559                                     // to be valid, because after the base becomes
1560                                     // invalid, someone else can use our mutable deref.
1561
1562                                     // This is in order to make the following function
1563                                     // illegal:
1564                                     // ```
1565                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
1566                                     //     &mut *x
1567                                     // }
1568                                     // ```
1569                                     //
1570                                     // As otherwise you could clone `&mut T` using the
1571                                     // following function:
1572                                     // ```
1573                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
1574                                     //     let my_clone = unsafe_deref(&'a x);
1575                                     //     ENDREGION 'a;
1576                                     //     (my_clone, x)
1577                                     // }
1578                                     // ```
1579                                 }
1580                             }
1581                         }
1582                         ty::TyRawPtr(..) => {
1583                             // deref of raw pointer, guaranteed to be valid
1584                             break;
1585                         }
1586                         ty::TyAdt(def, _) if def.is_box() => {
1587                             // deref of `Box`, need the base to be valid - propagate
1588                         }
1589                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
1590                     }
1591                 }
1592                 ProjectionElem::Field(..)
1593                 | ProjectionElem::Downcast(..)
1594                 | ProjectionElem::Index(..)
1595                 | ProjectionElem::ConstantIndex { .. }
1596                 | ProjectionElem::Subslice { .. } => {
1597                     // other field access
1598                 }
1599             }
1600
1601             // The "propagate" case. We need to check that our base is valid
1602             // for the borrow's lifetime.
1603             borrowed_place = base;
1604         }
1605     }
1606
1607     fn prove_aggregate_predicates(
1608         &mut self,
1609         aggregate_kind: &AggregateKind<'tcx>,
1610         location: Location,
1611     ) {
1612         let tcx = self.tcx();
1613
1614         debug!(
1615             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
1616             aggregate_kind, location
1617         );
1618
1619         let instantiated_predicates = match aggregate_kind {
1620             AggregateKind::Adt(def, _, substs, _) => {
1621                 tcx.predicates_of(def.did).instantiate(tcx, substs)
1622             }
1623
1624             // For closures, we have some **extra requirements** we
1625             //
1626             // have to check. In particular, in their upvars and
1627             // signatures, closures often reference various regions
1628             // from the surrounding function -- we call those the
1629             // closure's free regions. When we borrow-check (and hence
1630             // region-check) closures, we may find that the closure
1631             // requires certain relationships between those free
1632             // regions. However, because those free regions refer to
1633             // portions of the CFG of their caller, the closure is not
1634             // in a position to verify those relationships. In that
1635             // case, the requirements get "propagated" to us, and so
1636             // we have to solve them here where we instantiate the
1637             // closure.
1638             //
1639             // Despite the opacity of the previous parapgrah, this is
1640             // actually relatively easy to understand in terms of the
1641             // desugaring. A closure gets desugared to a struct, and
1642             // these extra requirements are basically like where
1643             // clauses on the struct.
1644             AggregateKind::Closure(def_id, substs) => {
1645                 if let Some(closure_region_requirements) =
1646                     tcx.mir_borrowck(*def_id).closure_requirements
1647                 {
1648                     let closure_constraints = closure_region_requirements.apply_requirements(
1649                         self.infcx.tcx,
1650                         location,
1651                         *def_id,
1652                         *substs,
1653                     );
1654
1655                     // Hmm, are these constraints *really* boring?
1656                     self.push_region_constraints(location.boring(), &closure_constraints);
1657                 }
1658
1659                 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1660             }
1661
1662             AggregateKind::Generator(def_id, substs, _) => {
1663                 tcx.predicates_of(*def_id).instantiate(tcx, substs.substs)
1664             }
1665
1666             AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
1667         };
1668
1669         self.normalize_and_prove_instantiated_predicates(
1670             instantiated_predicates,
1671             location.boring(),
1672         );
1673     }
1674
1675     fn prove_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>, locations: Locations) {
1676         self.prove_predicates(
1677             Some(ty::Predicate::Trait(
1678                 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
1679             )),
1680             locations,
1681         );
1682     }
1683
1684     fn normalize_and_prove_instantiated_predicates(
1685         &mut self,
1686         instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
1687         locations: Locations,
1688     ) {
1689         for predicate in instantiated_predicates.predicates {
1690             let predicate = self.normalize(predicate, locations);
1691             self.prove_predicate(predicate, locations);
1692         }
1693     }
1694
1695     fn prove_predicates(
1696         &mut self,
1697         predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
1698         locations: Locations,
1699     ) {
1700         for predicate in predicates {
1701             debug!(
1702                 "prove_predicates(predicate={:?}, locations={:?})",
1703                 predicate, locations,
1704             );
1705
1706             self.prove_predicate(predicate, locations);
1707         }
1708     }
1709
1710     fn prove_predicate(&mut self, predicate: ty::Predicate<'tcx>, locations: Locations) {
1711         debug!(
1712             "prove_predicate(predicate={:?}, location={:?})",
1713             predicate, locations,
1714         );
1715
1716         let param_env = self.param_env;
1717         self.fully_perform_op(
1718             locations,
1719             param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
1720         ).unwrap_or_else(|NoSolution| {
1721             span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
1722         })
1723     }
1724
1725     fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
1726         self.last_span = mir.span;
1727         debug!("run_on_mir: {:?}", mir.span);
1728
1729         for (local, local_decl) in mir.local_decls.iter_enumerated() {
1730             self.check_local(mir, local, local_decl);
1731         }
1732
1733         for (block, block_data) in mir.basic_blocks().iter_enumerated() {
1734             let mut location = Location {
1735                 block,
1736                 statement_index: 0,
1737             };
1738             for stmt in &block_data.statements {
1739                 if !stmt.source_info.span.is_dummy() {
1740                     self.last_span = stmt.source_info.span;
1741                 }
1742                 self.check_stmt(mir, stmt, location);
1743                 location.statement_index += 1;
1744             }
1745
1746             self.check_terminator(mir, block_data.terminator(), location);
1747             self.check_iscleanup(mir, block_data);
1748         }
1749     }
1750
1751     fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
1752     where
1753         T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
1754     {
1755         debug!("normalize(value={:?}, location={:?})", value, location);
1756         let param_env = self.param_env;
1757         self.fully_perform_op(
1758             location.to_locations(),
1759             param_env.and(type_op::normalize::Normalize::new(value)),
1760         ).unwrap_or_else(|NoSolution| {
1761             span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
1762             value
1763         })
1764     }
1765 }
1766
1767 pub struct TypeckMir;
1768
1769 impl MirPass for TypeckMir {
1770     fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
1771         let def_id = src.def_id;
1772         debug!("run_pass: {:?}", def_id);
1773
1774         // When NLL is enabled, the borrow checker runs the typeck
1775         // itself, so we don't need this MIR pass anymore.
1776         if tcx.use_mir_borrowck() {
1777             return;
1778         }
1779
1780         if tcx.sess.err_count() > 0 {
1781             // compiling a broken program can obviously result in a
1782             // broken MIR, so try not to report duplicate errors.
1783             return;
1784         }
1785
1786         if tcx.is_struct_constructor(def_id) {
1787             // We just assume that the automatically generated struct constructors are
1788             // correct. See the comment in the `mir_borrowck` implementation for an
1789             // explanation why we need this.
1790             return;
1791         }
1792
1793         let param_env = tcx.param_env(def_id);
1794         tcx.infer_ctxt().enter(|infcx| {
1795             let _ =
1796                 type_check_internal(&infcx, def_id, param_env, mir, &[], None, None, &mut |_| ());
1797
1798             // For verification purposes, we just ignore the resulting
1799             // region constraint sets. Not our problem. =)
1800         });
1801     }
1802 }
1803
1804 pub trait AtLocation {
1805     /// Indicates a "boring" constraint that the user probably
1806     /// woudln't want to see highlights.
1807     fn boring(self) -> Locations;
1808
1809     /// Indicates an "interesting" edge, which is of significance only
1810     /// for diagnostics.
1811     fn interesting(self) -> Locations;
1812 }
1813
1814 impl AtLocation for Location {
1815     fn boring(self) -> Locations {
1816         Locations::Boring(self)
1817     }
1818
1819     fn interesting(self) -> Locations {
1820         Locations::Interesting(self)
1821     }
1822 }
1823
1824 trait NormalizeLocation: fmt::Debug + Copy {
1825     fn to_locations(self) -> Locations;
1826 }
1827
1828 impl NormalizeLocation for Locations {
1829     fn to_locations(self) -> Locations {
1830         self
1831     }
1832 }
1833
1834 impl NormalizeLocation for Location {
1835     fn to_locations(self) -> Locations {
1836         self.boring()
1837     }
1838 }