]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/mod.rs
forward read_c_str method from Memory to Alloc
[rust.git] / src / librustc / infer / mod.rs
1 //! See the Book for more information.
2
3 pub use self::freshen::TypeFreshener;
4 pub use self::LateBoundRegionConversionTime::*;
5 pub use self::RegionVariableOrigin::*;
6 pub use self::SubregionOrigin::*;
7 pub use self::ValuePairs::*;
8 pub use crate::ty::IntVarValue;
9
10 use crate::hir;
11 use crate::hir::def_id::DefId;
12 use crate::infer::canonical::{Canonical, CanonicalVarValues};
13 use crate::infer::unify_key::{ConstVarValue, ConstVariableValue};
14 use crate::middle::free_region::RegionRelations;
15 use crate::middle::lang_items;
16 use crate::middle::region;
17 use crate::mir::interpret::ConstValue;
18 use crate::session::config::BorrowckMode;
19 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
20 use crate::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
21 use crate::ty::fold::{TypeFolder, TypeFoldable};
22 use crate::ty::relate::RelateResult;
23 use crate::ty::subst::{Kind, InternalSubsts, SubstsRef};
24 use crate::ty::{self, GenericParamDefKind, Ty, TyCtxt, InferConst};
25 use crate::ty::{FloatVid, IntVid, TyVid, ConstVid};
26 use crate::util::nodemap::FxHashMap;
27
28 use errors::DiagnosticBuilder;
29 use rustc_data_structures::unify as ut;
30 use std::cell::{Cell, Ref, RefCell, RefMut};
31 use std::collections::BTreeMap;
32 use std::fmt;
33 use syntax::ast;
34 use syntax_pos::symbol::InternedString;
35 use syntax_pos::Span;
36
37 use self::combine::CombineFields;
38 use self::lexical_region_resolve::LexicalRegionResolutions;
39 use self::outlives::env::OutlivesEnvironment;
40 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
41 use self::region_constraints::{RegionConstraintCollector, RegionSnapshot};
42 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
43 use self::unify_key::{ToType, ConstVariableOrigin, ConstVariableOriginKind};
44
45 pub mod at;
46 pub mod canonical;
47 mod combine;
48 mod equate;
49 pub mod error_reporting;
50 mod freshen;
51 mod fudge;
52 mod glb;
53 mod higher_ranked;
54 pub mod lattice;
55 mod lexical_region_resolve;
56 mod lub;
57 pub mod nll_relate;
58 pub mod opaque_types;
59 pub mod outlives;
60 pub mod region_constraints;
61 pub mod resolve;
62 mod sub;
63 pub mod type_variable;
64 pub mod unify_key;
65
66 #[must_use]
67 #[derive(Debug)]
68 pub struct InferOk<'tcx, T> {
69     pub value: T,
70     pub obligations: PredicateObligations<'tcx>,
71 }
72 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
73
74 pub type Bound<T> = Option<T>;
75 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
76 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
77
78 /// A flag that is used to suppress region errors. This is normally
79 /// false, but sometimes -- when we are doing region checks that the
80 /// NLL borrow checker will also do -- it might be set to true.
81 #[derive(Copy, Clone, Default, Debug)]
82 pub struct SuppressRegionErrors {
83     suppressed: bool,
84 }
85
86 impl SuppressRegionErrors {
87     pub fn suppressed(self) -> bool {
88         self.suppressed
89     }
90
91     /// Indicates that the MIR borrowck will repeat these region
92     /// checks, so we should ignore errors if NLL is (unconditionally)
93     /// enabled.
94     pub fn when_nll_is_enabled(tcx: TyCtxt<'_>) -> Self {
95         match tcx.borrowck_mode() {
96             // If we're on Migrate mode, report AST region errors
97             BorrowckMode::Migrate => SuppressRegionErrors { suppressed: false },
98
99             // If we're on MIR, don't report AST region errors as they should be reported by NLL
100             BorrowckMode::Mir => SuppressRegionErrors { suppressed: true },
101         }
102     }
103 }
104
105 pub struct InferCtxt<'a, 'tcx> {
106     pub tcx: TyCtxt<'tcx>,
107
108     /// During type-checking/inference of a body, `in_progress_tables`
109     /// contains a reference to the tables being built up, which are
110     /// used for reading closure kinds/signatures as they are inferred,
111     /// and for error reporting logic to read arbitrary node types.
112     pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
113
114     /// Cache for projections. This cache is snapshotted along with the
115     /// infcx.
116     ///
117     /// Public so that `traits::project` can use it.
118     pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
119
120     /// We instantiate `UnificationTable` with `bounds<Ty>` because the
121     /// types that might instantiate a general type variable have an
122     /// order, represented by its upper and lower bounds.
123     pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
124
125     /// Map from const parameter variable to the kind of const it represents.
126     const_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::ConstVid<'tcx>>>>,
127
128     /// Map from integral variable to the kind of integer it represents.
129     int_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::IntVid>>>,
130
131     /// Map from floating variable to the kind of float it represents
132     float_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::FloatVid>>>,
133
134     /// Tracks the set of region variables and the constraints between
135     /// them.  This is initially `Some(_)` but when
136     /// `resolve_regions_and_report_errors` is invoked, this gets set
137     /// to `None` -- further attempts to perform unification etc may
138     /// fail if new region constraints would've been added.
139     region_constraints: RefCell<Option<RegionConstraintCollector<'tcx>>>,
140
141     /// Once region inference is done, the values for each variable.
142     lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
143
144     /// Caches the results of trait selection. This cache is used
145     /// for things that have to do with the parameters in scope.
146     pub selection_cache: traits::SelectionCache<'tcx>,
147
148     /// Caches the results of trait evaluation.
149     pub evaluation_cache: traits::EvaluationCache<'tcx>,
150
151     /// the set of predicates on which errors have been reported, to
152     /// avoid reporting the same error twice.
153     pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
154
155     /// When an error occurs, we want to avoid reporting "derived"
156     /// errors that are due to this original failure. Normally, we
157     /// handle this with the `err_count_on_creation` count, which
158     /// basically just tracks how many errors were reported when we
159     /// started type-checking a fn and checks to see if any new errors
160     /// have been reported since then. Not great, but it works.
161     ///
162     /// However, when errors originated in other passes -- notably
163     /// resolve -- this heuristic breaks down. Therefore, we have this
164     /// auxiliary flag that one can set whenever one creates a
165     /// type-error that is due to an error in a prior pass.
166     ///
167     /// Don't read this flag directly, call `is_tainted_by_errors()`
168     /// and `set_tainted_by_errors()`.
169     tainted_by_errors_flag: Cell<bool>,
170
171     /// Track how many errors were reported when this infcx is created.
172     /// If the number of errors increases, that's also a sign (line
173     /// `tained_by_errors`) to avoid reporting certain kinds of errors.
174     // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
175     err_count_on_creation: usize,
176
177     /// This flag is true while there is an active snapshot.
178     in_snapshot: Cell<bool>,
179
180     /// A set of constraints that regionck must validate. Each
181     /// constraint has the form `T:'a`, meaning "some type `T` must
182     /// outlive the lifetime 'a". These constraints derive from
183     /// instantiated type parameters. So if you had a struct defined
184     /// like
185     ///
186     ///     struct Foo<T:'static> { ... }
187     ///
188     /// then in some expression `let x = Foo { ... }` it will
189     /// instantiate the type parameter `T` with a fresh type `$0`. At
190     /// the same time, it will record a region obligation of
191     /// `$0:'static`. This will get checked later by regionck. (We
192     /// can't generally check these things right away because we have
193     /// to wait until types are resolved.)
194     ///
195     /// These are stored in a map keyed to the id of the innermost
196     /// enclosing fn body / static initializer expression. This is
197     /// because the location where the obligation was incurred can be
198     /// relevant with respect to which sublifetime assumptions are in
199     /// place. The reason that we store under the fn-id, and not
200     /// something more fine-grained, is so that it is easier for
201     /// regionck to be sure that it has found *all* the region
202     /// obligations (otherwise, it's easy to fail to walk to a
203     /// particular node-id).
204     ///
205     /// Before running `resolve_regions_and_report_errors`, the creator
206     /// of the inference context is expected to invoke
207     /// `process_region_obligations` (defined in `self::region_obligations`)
208     /// for each body-id in this map, which will process the
209     /// obligations within. This is expected to be done 'late enough'
210     /// that all type inference variables have been bound and so forth.
211     pub region_obligations: RefCell<Vec<(hir::HirId, RegionObligation<'tcx>)>>,
212
213     /// What is the innermost universe we have created? Starts out as
214     /// `UniverseIndex::root()` but grows from there as we enter
215     /// universal quantifiers.
216     ///
217     /// N.B., at present, we exclude the universal quantifiers on the
218     /// item we are type-checking, and just consider those names as
219     /// part of the root universe. So this would only get incremented
220     /// when we enter into a higher-ranked (`for<..>`) type or trait
221     /// bound.
222     universe: Cell<ty::UniverseIndex>,
223 }
224
225 /// A map returned by `replace_bound_vars_with_placeholders()`
226 /// indicating the placeholder region that each late-bound region was
227 /// replaced with.
228 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
229
230 /// See the `error_reporting` module for more details.
231 #[derive(Clone, Debug, PartialEq, Eq)]
232 pub enum ValuePairs<'tcx> {
233     Types(ExpectedFound<Ty<'tcx>>),
234     Regions(ExpectedFound<ty::Region<'tcx>>),
235     Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
236     TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
237     PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
238 }
239
240 /// The trace designates the path through inference that we took to
241 /// encounter an error or subtyping constraint.
242 ///
243 /// See the `error_reporting` module for more details.
244 #[derive(Clone)]
245 pub struct TypeTrace<'tcx> {
246     cause: ObligationCause<'tcx>,
247     values: ValuePairs<'tcx>,
248 }
249
250 /// The origin of a `r1 <= r2` constraint.
251 ///
252 /// See `error_reporting` module for more details
253 #[derive(Clone, Debug)]
254 pub enum SubregionOrigin<'tcx> {
255     /// Arose from a subtyping relation
256     Subtype(TypeTrace<'tcx>),
257
258     /// Stack-allocated closures cannot outlive innermost loop
259     /// or function so as to ensure we only require finite stack
260     InfStackClosure(Span),
261
262     /// Invocation of closure must be within its lifetime
263     InvokeClosure(Span),
264
265     /// Dereference of reference must be within its lifetime
266     DerefPointer(Span),
267
268     /// Closure bound must not outlive captured variables
269     ClosureCapture(Span, hir::HirId),
270
271     /// Index into slice must be within its lifetime
272     IndexSlice(Span),
273
274     /// When casting `&'a T` to an `&'b Trait` object,
275     /// relating `'a` to `'b`
276     RelateObjectBound(Span),
277
278     /// Some type parameter was instantiated with the given type,
279     /// and that type must outlive some region.
280     RelateParamBound(Span, Ty<'tcx>),
281
282     /// The given region parameter was instantiated with a region
283     /// that must outlive some other region.
284     RelateRegionParamBound(Span),
285
286     /// A bound placed on type parameters that states that must outlive
287     /// the moment of their instantiation.
288     RelateDefaultParamBound(Span, Ty<'tcx>),
289
290     /// Creating a pointer `b` to contents of another reference
291     Reborrow(Span),
292
293     /// Creating a pointer `b` to contents of an upvar
294     ReborrowUpvar(Span, ty::UpvarId),
295
296     /// Data with type `Ty<'tcx>` was borrowed
297     DataBorrowed(Ty<'tcx>, Span),
298
299     /// (&'a &'b T) where a >= b
300     ReferenceOutlivesReferent(Ty<'tcx>, Span),
301
302     /// Type or region parameters must be in scope.
303     ParameterInScope(ParameterOrigin, Span),
304
305     /// The type T of an expression E must outlive the lifetime for E.
306     ExprTypeIsNotInScope(Ty<'tcx>, Span),
307
308     /// A `ref b` whose region does not enclose the decl site
309     BindingTypeIsNotValidAtDecl(Span),
310
311     /// Regions appearing in a method receiver must outlive method call
312     CallRcvr(Span),
313
314     /// Regions appearing in a function argument must outlive func call
315     CallArg(Span),
316
317     /// Region in return type of invoked fn must enclose call
318     CallReturn(Span),
319
320     /// Operands must be in scope
321     Operand(Span),
322
323     /// Region resulting from a `&` expr must enclose the `&` expr
324     AddrOf(Span),
325
326     /// An auto-borrow that does not enclose the expr where it occurs
327     AutoBorrow(Span),
328
329     /// Region constraint arriving from destructor safety
330     SafeDestructor(Span),
331
332     /// Comparing the signature and requirements of an impl method against
333     /// the containing trait.
334     CompareImplMethodObligation {
335         span: Span,
336         item_name: ast::Name,
337         impl_item_def_id: DefId,
338         trait_item_def_id: DefId,
339     },
340 }
341
342 /// Places that type/region parameters can appear.
343 #[derive(Clone, Copy, Debug)]
344 pub enum ParameterOrigin {
345     Path,               // foo::bar
346     MethodCall,         // foo.bar() <-- parameters on impl providing bar()
347     OverloadedOperator, // a + b when overloaded
348     OverloadedDeref,    // *a when overloaded
349 }
350
351 /// Times when we replace late-bound regions with variables:
352 #[derive(Clone, Copy, Debug)]
353 pub enum LateBoundRegionConversionTime {
354     /// when a fn is called
355     FnCall,
356
357     /// when two higher-ranked types are compared
358     HigherRankedType,
359
360     /// when projecting an associated type
361     AssocTypeProjection(DefId),
362 }
363
364 /// Reasons to create a region inference variable
365 ///
366 /// See `error_reporting` module for more details
367 #[derive(Copy, Clone, Debug)]
368 pub enum RegionVariableOrigin {
369     /// Region variables created for ill-categorized reasons,
370     /// mostly indicates places in need of refactoring
371     MiscVariable(Span),
372
373     /// Regions created by a `&P` or `[...]` pattern
374     PatternRegion(Span),
375
376     /// Regions created by `&` operator
377     AddrOfRegion(Span),
378
379     /// Regions created as part of an autoref of a method receiver
380     Autoref(Span),
381
382     /// Regions created as part of an automatic coercion
383     Coercion(Span),
384
385     /// Region variables created as the values for early-bound regions
386     EarlyBoundRegion(Span, InternedString),
387
388     /// Region variables created for bound regions
389     /// in a function or method that is called
390     LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
391
392     UpvarRegion(ty::UpvarId, Span),
393
394     BoundRegionInCoherence(ast::Name),
395
396     /// This origin is used for the inference variables that we create
397     /// during NLL region processing.
398     NLL(NLLRegionVariableOrigin),
399 }
400
401 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
402 pub enum NLLRegionVariableOrigin {
403     /// During NLL region processing, we create variables for free
404     /// regions that we encounter in the function signature and
405     /// elsewhere. This origin indices we've got one of those.
406     FreeRegion,
407
408     /// "Universal" instantiation of a higher-ranked region (e.g.,
409     /// from a `for<'a> T` binder). Meant to represent "any region".
410     Placeholder(ty::PlaceholderRegion),
411
412     Existential,
413 }
414
415 impl NLLRegionVariableOrigin {
416     pub fn is_universal(self) -> bool {
417         match self {
418             NLLRegionVariableOrigin::FreeRegion => true,
419             NLLRegionVariableOrigin::Placeholder(..) => true,
420             NLLRegionVariableOrigin::Existential => false,
421         }
422     }
423
424     pub fn is_existential(self) -> bool {
425         !self.is_universal()
426     }
427 }
428
429 #[derive(Copy, Clone, Debug)]
430 pub enum FixupError<'tcx> {
431     UnresolvedIntTy(IntVid),
432     UnresolvedFloatTy(FloatVid),
433     UnresolvedTy(TyVid),
434     UnresolvedConst(ConstVid<'tcx>),
435 }
436
437 /// See the `region_obligations` field for more information.
438 #[derive(Clone)]
439 pub struct RegionObligation<'tcx> {
440     pub sub_region: ty::Region<'tcx>,
441     pub sup_type: Ty<'tcx>,
442     pub origin: SubregionOrigin<'tcx>,
443 }
444
445 impl<'tcx> fmt::Display for FixupError<'tcx> {
446     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
447         use self::FixupError::*;
448
449         match *self {
450             UnresolvedIntTy(_) => write!(
451                 f,
452                 "cannot determine the type of this integer; \
453                  add a suffix to specify the type explicitly"
454             ),
455             UnresolvedFloatTy(_) => write!(
456                 f,
457                 "cannot determine the type of this number; \
458                  add a suffix to specify the type explicitly"
459             ),
460             UnresolvedTy(_) => write!(f, "unconstrained type"),
461             UnresolvedConst(_) => write!(f, "unconstrained const value"),
462         }
463     }
464 }
465
466 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
467 /// Necessary because we can't write the following bound:
468 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
469 pub struct InferCtxtBuilder<'tcx> {
470     global_tcx: TyCtxt<'tcx>,
471     fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
472 }
473
474 impl TyCtxt<'tcx> {
475     pub fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
476         InferCtxtBuilder {
477             global_tcx: self,
478             fresh_tables: None,
479         }
480     }
481 }
482
483 impl<'tcx> InferCtxtBuilder<'tcx> {
484     /// Used only by `rustc_typeck` during body type-checking/inference,
485     /// will initialize `in_progress_tables` with fresh `TypeckTables`.
486     pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
487         self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
488         self
489     }
490
491     /// Given a canonical value `C` as a starting point, create an
492     /// inference context that contains each of the bound values
493     /// within instantiated as a fresh variable. The `f` closure is
494     /// invoked with the new infcx, along with the instantiated value
495     /// `V` and a substitution `S`. This substitution `S` maps from
496     /// the bound values in `C` to their instantiated values in `V`
497     /// (in other words, `S(C) = V`).
498     pub fn enter_with_canonical<T, R>(
499         &mut self,
500         span: Span,
501         canonical: &Canonical<'tcx, T>,
502         f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
503     ) -> R
504     where
505         T: TypeFoldable<'tcx>,
506     {
507         self.enter(|infcx| {
508             let (value, subst) =
509                 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
510             f(infcx, value, subst)
511         })
512     }
513
514     pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
515         let InferCtxtBuilder {
516             global_tcx,
517             ref fresh_tables,
518         } = *self;
519         let in_progress_tables = fresh_tables.as_ref();
520         global_tcx.enter_local(|tcx| {
521             f(InferCtxt {
522                 tcx,
523                 in_progress_tables,
524                 projection_cache: Default::default(),
525                 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
526                 const_unification_table: RefCell::new(ut::UnificationTable::new()),
527                 int_unification_table: RefCell::new(ut::UnificationTable::new()),
528                 float_unification_table: RefCell::new(ut::UnificationTable::new()),
529                 region_constraints: RefCell::new(Some(RegionConstraintCollector::new())),
530                 lexical_region_resolutions: RefCell::new(None),
531                 selection_cache: Default::default(),
532                 evaluation_cache: Default::default(),
533                 reported_trait_errors: Default::default(),
534                 tainted_by_errors_flag: Cell::new(false),
535                 err_count_on_creation: tcx.sess.err_count(),
536                 in_snapshot: Cell::new(false),
537                 region_obligations: RefCell::new(vec![]),
538                 universe: Cell::new(ty::UniverseIndex::ROOT),
539             })
540         })
541     }
542 }
543
544 impl<T> ExpectedFound<T> {
545     pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
546         if a_is_expected {
547             ExpectedFound {
548                 expected: a,
549                 found: b,
550             }
551         } else {
552             ExpectedFound {
553                 expected: b,
554                 found: a,
555             }
556         }
557     }
558 }
559
560 impl<'tcx, T> InferOk<'tcx, T> {
561     pub fn unit(self) -> InferOk<'tcx, ()> {
562         InferOk {
563             value: (),
564             obligations: self.obligations,
565         }
566     }
567
568     /// Extracts `value`, registering any obligations into `fulfill_cx`.
569     pub fn into_value_registering_obligations(
570         self,
571         infcx: &InferCtxt<'_, 'tcx>,
572         fulfill_cx: &mut dyn TraitEngine<'tcx>,
573     ) -> T {
574         let InferOk { value, obligations } = self;
575         for obligation in obligations {
576             fulfill_cx.register_predicate_obligation(infcx, obligation);
577         }
578         value
579     }
580 }
581
582 impl<'tcx> InferOk<'tcx, ()> {
583     pub fn into_obligations(self) -> PredicateObligations<'tcx> {
584         self.obligations
585     }
586 }
587
588 #[must_use = "once you start a snapshot, you should always consume it"]
589 pub struct CombinedSnapshot<'a, 'tcx> {
590     projection_cache_snapshot: traits::ProjectionCacheSnapshot,
591     type_snapshot: type_variable::Snapshot<'tcx>,
592     const_snapshot: ut::Snapshot<ut::InPlace<ty::ConstVid<'tcx>>>,
593     int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
594     float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
595     region_constraints_snapshot: RegionSnapshot,
596     region_obligations_snapshot: usize,
597     universe: ty::UniverseIndex,
598     was_in_snapshot: bool,
599     _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
600 }
601
602 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
603     pub fn is_in_snapshot(&self) -> bool {
604         self.in_snapshot.get()
605     }
606
607     pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
608         t.fold_with(&mut self.freshener())
609     }
610
611     pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
612         match ty.sty {
613             ty::Infer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
614             _ => false,
615         }
616     }
617
618     pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
619         freshen::TypeFreshener::new(self)
620     }
621
622     pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
623         use crate::ty::error::UnconstrainedNumeric::Neither;
624         use crate::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
625         match ty.sty {
626             ty::Infer(ty::IntVar(vid)) => {
627                 if self.int_unification_table
628                     .borrow_mut()
629                     .probe_value(vid)
630                     .is_some()
631                 {
632                     Neither
633                 } else {
634                     UnconstrainedInt
635                 }
636             }
637             ty::Infer(ty::FloatVar(vid)) => {
638                 if self.float_unification_table
639                     .borrow_mut()
640                     .probe_value(vid)
641                     .is_some()
642                 {
643                     Neither
644                 } else {
645                     UnconstrainedFloat
646                 }
647             }
648             _ => Neither,
649         }
650     }
651
652     pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
653         let mut type_variables = self.type_variables.borrow_mut();
654         let mut int_unification_table = self.int_unification_table.borrow_mut();
655         let mut float_unification_table = self.float_unification_table.borrow_mut();
656         // FIXME(const_generics): should there be an equivalent function for const variables?
657
658         type_variables
659             .unsolved_variables()
660             .into_iter()
661             .map(|t| self.tcx.mk_ty_var(t))
662             .chain(
663                 (0..int_unification_table.len())
664                     .map(|i| ty::IntVid { index: i as u32 })
665                     .filter(|&vid| int_unification_table.probe_value(vid).is_none())
666                     .map(|v| self.tcx.mk_int_var(v)),
667             )
668             .chain(
669                 (0..float_unification_table.len())
670                     .map(|i| ty::FloatVid { index: i as u32 })
671                     .filter(|&vid| float_unification_table.probe_value(vid).is_none())
672                     .map(|v| self.tcx.mk_float_var(v)),
673             )
674             .collect()
675     }
676
677     fn combine_fields(
678         &'a self,
679         trace: TypeTrace<'tcx>,
680         param_env: ty::ParamEnv<'tcx>,
681     ) -> CombineFields<'a, 'tcx> {
682         CombineFields {
683             infcx: self,
684             trace,
685             cause: None,
686             param_env,
687             obligations: PredicateObligations::new(),
688         }
689     }
690
691     /// Clear the "currently in a snapshot" flag, invoke the closure,
692     /// then restore the flag to its original value. This flag is a
693     /// debugging measure designed to detect cases where we start a
694     /// snapshot, create type variables, and register obligations
695     /// which may involve those type variables in the fulfillment cx,
696     /// potentially leaving "dangling type variables" behind.
697     /// In such cases, an assertion will fail when attempting to
698     /// register obligations, within a snapshot. Very useful, much
699     /// better than grovelling through megabytes of `RUSTC_LOG` output.
700     ///
701     /// HOWEVER, in some cases the flag is unhelpful. In particular, we
702     /// sometimes create a "mini-fulfilment-cx" in which we enroll
703     /// obligations. As long as this fulfillment cx is fully drained
704     /// before we return, this is not a problem, as there won't be any
705     /// escaping obligations in the main cx. In those cases, you can
706     /// use this function.
707     pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
708     where
709         F: FnOnce(&Self) -> R,
710     {
711         let flag = self.in_snapshot.get();
712         self.in_snapshot.set(false);
713         let result = func(self);
714         self.in_snapshot.set(flag);
715         result
716     }
717
718     fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
719         debug!("start_snapshot()");
720
721         let in_snapshot = self.in_snapshot.get();
722         self.in_snapshot.set(true);
723
724         CombinedSnapshot {
725             projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
726             type_snapshot: self.type_variables.borrow_mut().snapshot(),
727             const_snapshot: self.const_unification_table.borrow_mut().snapshot(),
728             int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
729             float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
730             region_constraints_snapshot: self.borrow_region_constraints().start_snapshot(),
731             region_obligations_snapshot: self.region_obligations.borrow().len(),
732             universe: self.universe(),
733             was_in_snapshot: in_snapshot,
734             // Borrow tables "in progress" (i.e., during typeck)
735             // to ban writes from within a snapshot to them.
736             _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
737         }
738     }
739
740     fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
741         debug!("rollback_to(cause={})", cause);
742         let CombinedSnapshot {
743             projection_cache_snapshot,
744             type_snapshot,
745             const_snapshot,
746             int_snapshot,
747             float_snapshot,
748             region_constraints_snapshot,
749             region_obligations_snapshot,
750             universe,
751             was_in_snapshot,
752             _in_progress_tables,
753         } = snapshot;
754
755         self.in_snapshot.set(was_in_snapshot);
756         self.universe.set(universe);
757
758         self.projection_cache.borrow_mut().rollback_to(projection_cache_snapshot);
759         self.type_variables.borrow_mut().rollback_to(type_snapshot);
760         self.const_unification_table.borrow_mut().rollback_to(const_snapshot);
761         self.int_unification_table.borrow_mut().rollback_to(int_snapshot);
762         self.float_unification_table.borrow_mut().rollback_to(float_snapshot);
763         self.region_obligations.borrow_mut().truncate(region_obligations_snapshot);
764         self.borrow_region_constraints().rollback_to(region_constraints_snapshot);
765     }
766
767     fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
768         debug!("commit_from()");
769         let CombinedSnapshot {
770             projection_cache_snapshot,
771             type_snapshot,
772             const_snapshot,
773             int_snapshot,
774             float_snapshot,
775             region_constraints_snapshot,
776             region_obligations_snapshot: _,
777             universe: _,
778             was_in_snapshot,
779             _in_progress_tables,
780         } = snapshot;
781
782         self.in_snapshot.set(was_in_snapshot);
783
784         self.projection_cache.borrow_mut().commit(projection_cache_snapshot);
785         self.type_variables.borrow_mut().commit(type_snapshot);
786         self.const_unification_table.borrow_mut().commit(const_snapshot);
787         self.int_unification_table.borrow_mut().commit(int_snapshot);
788         self.float_unification_table.borrow_mut().commit(float_snapshot);
789         self.borrow_region_constraints().commit(region_constraints_snapshot);
790     }
791
792     /// Executes `f` and commit the bindings.
793     pub fn commit_unconditionally<R, F>(&self, f: F) -> R
794     where
795         F: FnOnce() -> R,
796     {
797         debug!("commit()");
798         let snapshot = self.start_snapshot();
799         let r = f();
800         self.commit_from(snapshot);
801         r
802     }
803
804     /// Executes `f` and commit the bindings if closure `f` returns `Ok(_)`.
805     pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
806     where
807         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
808     {
809         debug!("commit_if_ok()");
810         let snapshot = self.start_snapshot();
811         let r = f(&snapshot);
812         debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
813         match r {
814             Ok(_) => {
815                 self.commit_from(snapshot);
816             }
817             Err(_) => {
818                 self.rollback_to("commit_if_ok -- error", snapshot);
819             }
820         }
821         r
822     }
823
824     /// Execute `f` in a snapshot, and commit the bindings it creates.
825     pub fn in_snapshot<T, F>(&self, f: F) -> T
826     where
827         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> T,
828     {
829         debug!("in_snapshot()");
830         let snapshot = self.start_snapshot();
831         let r = f(&snapshot);
832         self.commit_from(snapshot);
833         r
834     }
835
836     /// Executes `f` then unroll any bindings it creates.
837     pub fn probe<R, F>(&self, f: F) -> R
838     where
839         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
840     {
841         debug!("probe()");
842         let snapshot = self.start_snapshot();
843         let r = f(&snapshot);
844         self.rollback_to("probe", snapshot);
845         r
846     }
847
848     /// Scan the constraints produced since `snapshot` began and returns:
849     ///
850     /// - `None` -- if none of them involve "region outlives" constraints
851     /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
852     /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
853     pub fn region_constraints_added_in_snapshot(
854         &self,
855         snapshot: &CombinedSnapshot<'a, 'tcx>,
856     ) -> Option<bool> {
857         self.borrow_region_constraints().region_constraints_added_in_snapshot(
858             &snapshot.region_constraints_snapshot,
859         )
860     }
861
862     pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
863         self.borrow_region_constraints().add_given(sub, sup);
864     }
865
866     pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
867     where
868         T: at::ToTrace<'tcx>,
869     {
870         let origin = &ObligationCause::dummy();
871         self.probe(|_| {
872             self.at(origin, param_env)
873                 .sub(a, b)
874                 .map(|InferOk { obligations: _, .. }| {
875                     // Ignore obligations, since we are unrolling
876                     // everything anyway.
877                 })
878         })
879     }
880
881     pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
882     where
883         T: at::ToTrace<'tcx>,
884     {
885         let origin = &ObligationCause::dummy();
886         self.probe(|_| {
887             self.at(origin, param_env)
888                 .eq(a, b)
889                 .map(|InferOk { obligations: _, .. }| {
890                     // Ignore obligations, since we are unrolling
891                     // everything anyway.
892                 })
893         })
894     }
895
896     pub fn sub_regions(
897         &self,
898         origin: SubregionOrigin<'tcx>,
899         a: ty::Region<'tcx>,
900         b: ty::Region<'tcx>,
901     ) {
902         debug!("sub_regions({:?} <: {:?})", a, b);
903         self.borrow_region_constraints()
904             .make_subregion(origin, a, b);
905     }
906
907     pub fn subtype_predicate(
908         &self,
909         cause: &ObligationCause<'tcx>,
910         param_env: ty::ParamEnv<'tcx>,
911         predicate: &ty::PolySubtypePredicate<'tcx>,
912     ) -> Option<InferResult<'tcx, ()>> {
913         // Subtle: it's ok to skip the binder here and resolve because
914         // `shallow_resolve` just ignores anything that is not a type
915         // variable, and because type variable's can't (at present, at
916         // least) capture any of the things bound by this binder.
917         //
918         // NOTE(nmatsakis): really, there is no *particular* reason to do this
919         // `shallow_resolve` here except as a micro-optimization.
920         // Naturally I could not resist.
921         let two_unbound_type_vars = {
922             let a = self.shallow_resolve(predicate.skip_binder().a);
923             let b = self.shallow_resolve(predicate.skip_binder().b);
924             a.is_ty_var() && b.is_ty_var()
925         };
926
927         if two_unbound_type_vars {
928             // Two unbound type variables? Can't make progress.
929             return None;
930         }
931
932         Some(self.commit_if_ok(|snapshot| {
933             let (
934                 ty::SubtypePredicate {
935                     a_is_expected,
936                     a,
937                     b,
938                 },
939                 placeholder_map,
940             ) = self.replace_bound_vars_with_placeholders(predicate);
941
942             let ok = self.at(cause, param_env)
943                 .sub_exp(a_is_expected, a, b)?;
944
945             self.leak_check(false, &placeholder_map, snapshot)?;
946
947             Ok(ok.unit())
948         }))
949     }
950
951     pub fn region_outlives_predicate(
952         &self,
953         cause: &traits::ObligationCause<'tcx>,
954         predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
955     ) -> UnitResult<'tcx> {
956         self.commit_if_ok(|snapshot| {
957             let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
958                 self.replace_bound_vars_with_placeholders(predicate);
959             let origin = SubregionOrigin::from_obligation_cause(
960                 cause,
961                 || RelateRegionParamBound(cause.span),
962             );
963             self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
964             self.leak_check(false, &placeholder_map, snapshot)?;
965             Ok(())
966         })
967     }
968
969     pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
970         self.type_variables
971             .borrow_mut()
972             .new_var(self.universe(), diverging, origin)
973     }
974
975     pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
976         self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
977     }
978
979     pub fn next_ty_var_in_universe(
980         &self,
981         origin: TypeVariableOrigin,
982         universe: ty::UniverseIndex
983     ) -> Ty<'tcx> {
984         let vid = self.type_variables
985             .borrow_mut()
986             .new_var(universe, false, origin);
987         self.tcx.mk_ty_var(vid)
988     }
989
990     pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
991         self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
992     }
993
994     pub fn next_const_var(
995         &self,
996         ty: Ty<'tcx>,
997         origin: ConstVariableOrigin
998     ) -> &'tcx ty::Const<'tcx> {
999         self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1000     }
1001
1002     pub fn next_const_var_in_universe(
1003         &self,
1004         ty: Ty<'tcx>,
1005         origin: ConstVariableOrigin,
1006         universe: ty::UniverseIndex,
1007     ) -> &'tcx ty::Const<'tcx> {
1008         let vid = self.const_unification_table
1009             .borrow_mut()
1010             .new_key(ConstVarValue {
1011                 origin,
1012                 val: ConstVariableValue::Unknown { universe },
1013             });
1014         self.tcx.mk_const_var(vid, ty)
1015     }
1016
1017     pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1018         self.const_unification_table
1019             .borrow_mut()
1020             .new_key(ConstVarValue {
1021                 origin,
1022                 val: ConstVariableValue::Unknown { universe: self.universe() },
1023             })
1024     }
1025
1026     fn next_int_var_id(&self) -> IntVid {
1027         self.int_unification_table.borrow_mut().new_key(None)
1028     }
1029
1030     pub fn next_int_var(&self) -> Ty<'tcx> {
1031         self.tcx.mk_int_var(self.next_int_var_id())
1032     }
1033
1034     fn next_float_var_id(&self) -> FloatVid {
1035         self.float_unification_table.borrow_mut().new_key(None)
1036     }
1037
1038     pub fn next_float_var(&self) -> Ty<'tcx> {
1039         self.tcx.mk_float_var(self.next_float_var_id())
1040     }
1041
1042     /// Creates a fresh region variable with the next available index.
1043     /// The variable will be created in the maximum universe created
1044     /// thus far, allowing it to name any region created thus far.
1045     pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1046         self.next_region_var_in_universe(origin, self.universe())
1047     }
1048
1049     /// Creates a fresh region variable with the next available index
1050     /// in the given universe; typically, you can use
1051     /// `next_region_var` and just use the maximal universe.
1052     pub fn next_region_var_in_universe(
1053         &self,
1054         origin: RegionVariableOrigin,
1055         universe: ty::UniverseIndex,
1056     ) -> ty::Region<'tcx> {
1057         let region_var = self.borrow_region_constraints()
1058             .new_region_var(universe, origin);
1059         self.tcx.mk_region(ty::ReVar(region_var))
1060     }
1061
1062     /// Return the universe that the region `r` was created in.  For
1063     /// most regions (e.g., `'static`, named regions from the user,
1064     /// etc) this is the root universe U0. For inference variables or
1065     /// placeholders, however, it will return the universe which which
1066     /// they are associated.
1067     fn universe_of_region(
1068         &self,
1069         r: ty::Region<'tcx>,
1070     ) -> ty::UniverseIndex {
1071         self.borrow_region_constraints().universe(r)
1072     }
1073
1074     /// Number of region variables created so far.
1075     pub fn num_region_vars(&self) -> usize {
1076         self.borrow_region_constraints().num_region_vars()
1077     }
1078
1079     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1080     pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1081         self.next_region_var(RegionVariableOrigin::NLL(origin))
1082     }
1083
1084     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1085     pub fn next_nll_region_var_in_universe(
1086         &self,
1087         origin: NLLRegionVariableOrigin,
1088         universe: ty::UniverseIndex,
1089     ) -> ty::Region<'tcx> {
1090         self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1091     }
1092
1093     pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> Kind<'tcx> {
1094         match param.kind {
1095             GenericParamDefKind::Lifetime => {
1096                 // Create a region inference variable for the given
1097                 // region parameter definition.
1098                 self.next_region_var(EarlyBoundRegion(span, param.name))
1099                     .into()
1100             }
1101             GenericParamDefKind::Type { .. } => {
1102                 // Create a type inference variable for the given
1103                 // type parameter definition. The substitutions are
1104                 // for actual parameters that may be referred to by
1105                 // the default of this type parameter, if it exists.
1106                 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1107                 // used in a path such as `Foo::<T, U>::new()` will
1108                 // use an inference variable for `C` with `[T, U]`
1109                 // as the substitutions for the default, `(T, U)`.
1110                 let ty_var_id = self.type_variables.borrow_mut().new_var(
1111                     self.universe(),
1112                     false,
1113                     TypeVariableOrigin {
1114                         kind: TypeVariableOriginKind::TypeParameterDefinition(param.name),
1115                         span,
1116                     },
1117                 );
1118
1119                 self.tcx.mk_ty_var(ty_var_id).into()
1120             }
1121             GenericParamDefKind::Const { .. } => {
1122                 let origin = ConstVariableOrigin {
1123                     kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1124                     span,
1125                 };
1126                 let const_var_id =
1127                     self.const_unification_table
1128                         .borrow_mut()
1129                         .new_key(ConstVarValue {
1130                             origin,
1131                             val: ConstVariableValue::Unknown { universe: self.universe() },
1132                         });
1133                 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1134             }
1135         }
1136     }
1137
1138     /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1139     /// type/region parameter to a fresh inference variable.
1140     pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1141         InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1142     }
1143
1144     /// Returns `true` if errors have been reported since this infcx was
1145     /// created. This is sometimes used as a heuristic to skip
1146     /// reporting errors that often occur as a result of earlier
1147     /// errors, but where it's hard to be 100% sure (e.g., unresolved
1148     /// inference variables, regionck errors).
1149     pub fn is_tainted_by_errors(&self) -> bool {
1150         debug!(
1151             "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1152              tainted_by_errors_flag={})",
1153             self.tcx.sess.err_count(),
1154             self.err_count_on_creation,
1155             self.tainted_by_errors_flag.get()
1156         );
1157
1158         if self.tcx.sess.err_count() > self.err_count_on_creation {
1159             return true; // errors reported since this infcx was made
1160         }
1161         self.tainted_by_errors_flag.get()
1162     }
1163
1164     /// Set the "tainted by errors" flag to true. We call this when we
1165     /// observe an error from a prior pass.
1166     pub fn set_tainted_by_errors(&self) {
1167         debug!("set_tainted_by_errors()");
1168         self.tainted_by_errors_flag.set(true)
1169     }
1170
1171     /// Process the region constraints and report any errors that
1172     /// result. After this, no more unification operations should be
1173     /// done -- or the compiler will panic -- but it is legal to use
1174     /// `resolve_vars_if_possible` as well as `fully_resolve`.
1175     pub fn resolve_regions_and_report_errors(
1176         &self,
1177         region_context: DefId,
1178         region_map: &region::ScopeTree,
1179         outlives_env: &OutlivesEnvironment<'tcx>,
1180         suppress: SuppressRegionErrors,
1181     ) {
1182         assert!(
1183             self.is_tainted_by_errors() || self.region_obligations.borrow().is_empty(),
1184             "region_obligations not empty: {:#?}",
1185             self.region_obligations.borrow()
1186         );
1187
1188         let region_rels = &RegionRelations::new(
1189             self.tcx,
1190             region_context,
1191             region_map,
1192             outlives_env.free_region_map(),
1193         );
1194         let (var_infos, data) = self.region_constraints
1195             .borrow_mut()
1196             .take()
1197             .expect("regions already resolved")
1198             .into_infos_and_data();
1199         let (lexical_region_resolutions, errors) =
1200             lexical_region_resolve::resolve(region_rels, var_infos, data);
1201
1202         let old_value = self.lexical_region_resolutions
1203             .replace(Some(lexical_region_resolutions));
1204         assert!(old_value.is_none());
1205
1206         if !self.is_tainted_by_errors() {
1207             // As a heuristic, just skip reporting region errors
1208             // altogether if other errors have been reported while
1209             // this infcx was in use.  This is totally hokey but
1210             // otherwise we have a hard time separating legit region
1211             // errors from silly ones.
1212             self.report_region_errors(region_map, &errors, suppress);
1213         }
1214     }
1215
1216     /// Obtains (and clears) the current set of region
1217     /// constraints. The inference context is still usable: further
1218     /// unifications will simply add new constraints.
1219     ///
1220     /// This method is not meant to be used with normal lexical region
1221     /// resolution. Rather, it is used in the NLL mode as a kind of
1222     /// interim hack: basically we run normal type-check and generate
1223     /// region constraints as normal, but then we take them and
1224     /// translate them into the form that the NLL solver
1225     /// understands. See the NLL module for mode details.
1226     pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1227         assert!(
1228             self.region_obligations.borrow().is_empty(),
1229             "region_obligations not empty: {:#?}",
1230             self.region_obligations.borrow()
1231         );
1232
1233         self.borrow_region_constraints().take_and_reset_data()
1234     }
1235
1236     /// Gives temporary access to the region constraint data.
1237     #[allow(non_camel_case_types)] // bug with impl trait
1238     pub fn with_region_constraints<R>(
1239         &self,
1240         op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1241     ) -> R {
1242         let region_constraints = self.borrow_region_constraints();
1243         op(region_constraints.data())
1244     }
1245
1246     /// Takes ownership of the list of variable regions. This implies
1247     /// that all the region constraints have already been taken, and
1248     /// hence that `resolve_regions_and_report_errors` can never be
1249     /// called. This is used only during NLL processing to "hand off" ownership
1250     /// of the set of region variables into the NLL region context.
1251     pub fn take_region_var_origins(&self) -> VarInfos {
1252         let (var_infos, data) = self.region_constraints
1253             .borrow_mut()
1254             .take()
1255             .expect("regions already resolved")
1256             .into_infos_and_data();
1257         assert!(data.is_empty());
1258         var_infos
1259     }
1260
1261     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1262         self.resolve_vars_if_possible(&t).to_string()
1263     }
1264
1265     pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1266         let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1267         format!("({})", tstrs.join(", "))
1268     }
1269
1270     pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1271         self.resolve_vars_if_possible(t).to_string()
1272     }
1273
1274     /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1275     /// universe index of `TyVar(vid)`.
1276     pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1277         use self::type_variable::TypeVariableValue;
1278
1279         match self.type_variables.borrow_mut().probe(vid) {
1280             TypeVariableValue::Known { value } => Ok(value),
1281             TypeVariableValue::Unknown { universe } => Err(universe),
1282         }
1283     }
1284
1285     pub fn shallow_resolve<T>(&self, value: T) -> T
1286     where
1287         T: TypeFoldable<'tcx>,
1288     {
1289         let mut r = ShallowResolver::new(self);
1290         value.fold_with(&mut r)
1291     }
1292
1293     pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1294         self.type_variables.borrow_mut().root_var(var)
1295     }
1296
1297     /// Where possible, replaces type/const variables in
1298     /// `value` with their final value. Note that region variables
1299     /// are unaffected. If a type/const variable has not been unified, it
1300     /// is left as is. This is an idempotent operation that does
1301     /// not affect inference state in any way and so you can do it
1302     /// at will.
1303     pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1304     where
1305         T: TypeFoldable<'tcx>,
1306     {
1307         if !value.needs_infer() {
1308             return value.clone(); // avoid duplicated subst-folding
1309         }
1310         let mut r = resolve::OpportunisticVarResolver::new(self);
1311         value.fold_with(&mut r)
1312     }
1313
1314     /// Returns first unresolved variable contained in `T`. In the
1315     /// process of visiting `T`, this will resolve (where possible)
1316     /// type variables in `T`, but it never constructs the final,
1317     /// resolved type, so it's more efficient than
1318     /// `resolve_vars_if_possible()`.
1319     pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1320     where
1321         T: TypeFoldable<'tcx>,
1322     {
1323         let mut r = resolve::UnresolvedTypeFinder::new(self);
1324         value.visit_with(&mut r);
1325         r.first_unresolved
1326     }
1327
1328     pub fn probe_const_var(
1329         &self,
1330         vid: ty::ConstVid<'tcx>
1331     ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1332         match self.const_unification_table.borrow_mut().probe_value(vid).val {
1333             ConstVariableValue::Known { value } => Ok(value),
1334             ConstVariableValue::Unknown { universe } => Err(universe),
1335         }
1336     }
1337
1338     pub fn resolve_const_var(
1339         &self,
1340         ct: &'tcx ty::Const<'tcx>
1341     ) -> &'tcx ty::Const<'tcx> {
1342         if let ty::Const { val: ConstValue::Infer(InferConst::Var(v)), .. } = ct {
1343             self.const_unification_table
1344                 .borrow_mut()
1345                 .probe_value(*v)
1346                 .val
1347                 .known()
1348                 .map(|c| self.resolve_const_var(c))
1349                 .unwrap_or(ct)
1350         } else {
1351             ct
1352         }
1353     }
1354
1355     pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1356         /*!
1357          * Attempts to resolve all type/region/const variables in
1358          * `value`. Region inference must have been run already (e.g.,
1359          * by calling `resolve_regions_and_report_errors`). If some
1360          * variable was never unified, an `Err` results.
1361          *
1362          * This method is idempotent, but it not typically not invoked
1363          * except during the writeback phase.
1364          */
1365
1366         resolve::fully_resolve(self, value)
1367     }
1368
1369     // [Note-Type-error-reporting]
1370     // An invariant is that anytime the expected or actual type is Error (the special
1371     // error type, meaning that an error occurred when typechecking this expression),
1372     // this is a derived error. The error cascaded from another error (that was already
1373     // reported), so it's not useful to display it to the user.
1374     // The following methods implement this logic.
1375     // They check if either the actual or expected type is Error, and don't print the error
1376     // in this case. The typechecker should only ever report type errors involving mismatched
1377     // types using one of these methods, and should not call span_err directly for such
1378     // errors.
1379
1380     pub fn type_error_struct_with_diag<M>(
1381         &self,
1382         sp: Span,
1383         mk_diag: M,
1384         actual_ty: Ty<'tcx>,
1385     ) -> DiagnosticBuilder<'tcx>
1386     where
1387         M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1388     {
1389         let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1390         debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1391
1392         // Don't report an error if actual type is `Error`.
1393         if actual_ty.references_error() {
1394             return self.tcx.sess.diagnostic().struct_dummy();
1395         }
1396
1397         mk_diag(self.ty_to_string(actual_ty))
1398     }
1399
1400     pub fn report_mismatched_types(
1401         &self,
1402         cause: &ObligationCause<'tcx>,
1403         expected: Ty<'tcx>,
1404         actual: Ty<'tcx>,
1405         err: TypeError<'tcx>,
1406     ) -> DiagnosticBuilder<'tcx> {
1407         let trace = TypeTrace::types(cause, true, expected, actual);
1408         self.report_and_explain_type_error(trace, &err)
1409     }
1410
1411     pub fn replace_bound_vars_with_fresh_vars<T>(
1412         &self,
1413         span: Span,
1414         lbrct: LateBoundRegionConversionTime,
1415         value: &ty::Binder<T>
1416     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1417     where
1418         T: TypeFoldable<'tcx>
1419     {
1420         let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1421         let fld_t = |_| {
1422             self.next_ty_var(TypeVariableOrigin {
1423                 kind: TypeVariableOriginKind::MiscVariable,
1424                 span,
1425             })
1426         };
1427         let fld_c = |_, ty| self.next_const_var(ty, ConstVariableOrigin {
1428             kind: ConstVariableOriginKind:: MiscVariable,
1429             span,
1430         });
1431         self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1432     }
1433
1434     /// See the [`region_constraints::verify_generic_bound`] method.
1435     pub fn verify_generic_bound(
1436         &self,
1437         origin: SubregionOrigin<'tcx>,
1438         kind: GenericKind<'tcx>,
1439         a: ty::Region<'tcx>,
1440         bound: VerifyBound<'tcx>,
1441     ) {
1442         debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1443
1444         self.borrow_region_constraints()
1445             .verify_generic_bound(origin, kind, a, bound);
1446     }
1447
1448     pub fn type_is_copy_modulo_regions(
1449         &self,
1450         param_env: ty::ParamEnv<'tcx>,
1451         ty: Ty<'tcx>,
1452         span: Span,
1453     ) -> bool {
1454         let ty = self.resolve_vars_if_possible(&ty);
1455
1456         // Even if the type may have no inference variables, during
1457         // type-checking closure types are in local tables only.
1458         if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1459             if let Some((param_env, ty)) = self.tcx.lift_to_global(&(param_env, ty)) {
1460                 return ty.is_copy_modulo_regions(self.tcx.global_tcx(), param_env, span);
1461             }
1462         }
1463
1464         let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1465
1466         // this can get called from typeck (by euv), and moves_by_default
1467         // rightly refuses to work with inference variables, but
1468         // moves_by_default has a cache, which we want to use in other
1469         // cases.
1470         traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id, span)
1471     }
1472
1473     /// Obtains the latest type of the given closure; this may be a
1474     /// closure in the current function, in which case its
1475     /// `ClosureKind` may not yet be known.
1476     pub fn closure_kind(
1477         &self,
1478         closure_def_id: DefId,
1479         closure_substs: ty::ClosureSubsts<'tcx>,
1480     ) -> Option<ty::ClosureKind> {
1481         let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx);
1482         let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1483         closure_kind_ty.to_opt_closure_kind()
1484     }
1485
1486     /// Obtain the signature of a closure. For closures, unlike
1487     /// `tcx.fn_sig(def_id)`, this method will work during the
1488     /// type-checking of the enclosing function and return the closure
1489     /// signature in its partially inferred state.
1490     pub fn closure_sig(
1491         &self,
1492         def_id: DefId,
1493         substs: ty::ClosureSubsts<'tcx>,
1494     ) -> ty::PolyFnSig<'tcx> {
1495         let closure_sig_ty = substs.closure_sig_ty(def_id, self.tcx);
1496         let closure_sig_ty = self.shallow_resolve(closure_sig_ty);
1497         closure_sig_ty.fn_sig(self.tcx)
1498     }
1499
1500     /// Normalizes associated types in `value`, potentially returning
1501     /// new obligations that must further be processed.
1502     pub fn partially_normalize_associated_types_in<T>(
1503         &self,
1504         span: Span,
1505         body_id: hir::HirId,
1506         param_env: ty::ParamEnv<'tcx>,
1507         value: &T,
1508     ) -> InferOk<'tcx, T>
1509     where
1510         T: TypeFoldable<'tcx>,
1511     {
1512         debug!("partially_normalize_associated_types_in(value={:?})", value);
1513         let mut selcx = traits::SelectionContext::new(self);
1514         let cause = ObligationCause::misc(span, body_id);
1515         let traits::Normalized { value, obligations } =
1516             traits::normalize(&mut selcx, param_env, cause, value);
1517         debug!(
1518             "partially_normalize_associated_types_in: result={:?} predicates={:?}",
1519             value, obligations
1520         );
1521         InferOk { value, obligations }
1522     }
1523
1524     pub fn borrow_region_constraints(&self) -> RefMut<'_, RegionConstraintCollector<'tcx>> {
1525         RefMut::map(self.region_constraints.borrow_mut(), |c| {
1526             c.as_mut().expect("region constraints already solved")
1527         })
1528     }
1529
1530     /// Clears the selection, evaluation, and projection caches. This is useful when
1531     /// repeatedly attempting to select an `Obligation` while changing only
1532     /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1533     pub fn clear_caches(&self) {
1534         self.selection_cache.clear();
1535         self.evaluation_cache.clear();
1536         self.projection_cache.borrow_mut().clear();
1537     }
1538
1539     fn universe(&self) -> ty::UniverseIndex {
1540         self.universe.get()
1541     }
1542
1543     /// Creates and return a fresh universe that extends all previous
1544     /// universes. Updates `self.universe` to that new universe.
1545     pub fn create_next_universe(&self) -> ty::UniverseIndex {
1546         let u = self.universe.get().next_universe();
1547         self.universe.set(u);
1548         u
1549     }
1550 }
1551
1552 pub struct ShallowResolver<'a, 'tcx> {
1553     infcx: &'a InferCtxt<'a, 'tcx>,
1554 }
1555
1556 impl<'a, 'tcx> ShallowResolver<'a, 'tcx> {
1557     #[inline(always)]
1558     pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self {
1559         ShallowResolver { infcx }
1560     }
1561
1562     // We have this force-inlined variant of `shallow_resolve` for the one
1563     // callsite that is extremely hot. All other callsites use the normal
1564     // variant.
1565     #[inline(always)]
1566     pub fn inlined_shallow_resolve(&mut self, typ: Ty<'tcx>) -> Ty<'tcx> {
1567         match typ.sty {
1568             ty::Infer(ty::TyVar(v)) => {
1569                 // Not entirely obvious: if `typ` is a type variable,
1570                 // it can be resolved to an int/float variable, which
1571                 // can then be recursively resolved, hence the
1572                 // recursion. Note though that we prevent type
1573                 // variables from unifyxing to other type variables
1574                 // directly (though they may be embedded
1575                 // structurally), and we prevent cycles in any case,
1576                 // so this recursion should always be of very limited
1577                 // depth.
1578                 self.infcx.type_variables
1579                     .borrow_mut()
1580                     .probe(v)
1581                     .known()
1582                     .map(|t| self.fold_ty(t))
1583                     .unwrap_or(typ)
1584             }
1585
1586             ty::Infer(ty::IntVar(v)) => self.infcx.int_unification_table
1587                 .borrow_mut()
1588                 .probe_value(v)
1589                 .map(|v| v.to_type(self.infcx.tcx))
1590                 .unwrap_or(typ),
1591
1592             ty::Infer(ty::FloatVar(v)) => self.infcx.float_unification_table
1593                 .borrow_mut()
1594                 .probe_value(v)
1595                 .map(|v| v.to_type(self.infcx.tcx))
1596                 .unwrap_or(typ),
1597
1598             _ => typ,
1599         }
1600     }
1601 }
1602
1603 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1604     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1605         self.infcx.tcx
1606     }
1607
1608     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1609         self.inlined_shallow_resolve(ty)
1610     }
1611
1612     fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1613         match ct {
1614             ty::Const { val: ConstValue::Infer(InferConst::Var(vid)), .. } => {
1615                 self.infcx.const_unification_table
1616                     .borrow_mut()
1617                     .probe_value(*vid)
1618                     .val
1619                     .known()
1620                     .map(|c| self.fold_const(c))
1621                     .unwrap_or(ct)
1622             }
1623             _ => ct,
1624         }
1625     }
1626 }
1627
1628 impl<'tcx> TypeTrace<'tcx> {
1629     pub fn span(&self) -> Span {
1630         self.cause.span
1631     }
1632
1633     pub fn types(
1634         cause: &ObligationCause<'tcx>,
1635         a_is_expected: bool,
1636         a: Ty<'tcx>,
1637         b: Ty<'tcx>,
1638     ) -> TypeTrace<'tcx> {
1639         TypeTrace {
1640             cause: cause.clone(),
1641             values: Types(ExpectedFound::new(a_is_expected, a, b)),
1642         }
1643     }
1644
1645     pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1646         TypeTrace {
1647             cause: ObligationCause::dummy(),
1648             values: Types(ExpectedFound {
1649                 expected: tcx.types.err,
1650                 found: tcx.types.err,
1651             }),
1652         }
1653     }
1654 }
1655
1656 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1657     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1658         write!(f, "TypeTrace({:?})", self.cause)
1659     }
1660 }
1661
1662 impl<'tcx> SubregionOrigin<'tcx> {
1663     pub fn span(&self) -> Span {
1664         match *self {
1665             Subtype(ref a) => a.span(),
1666             InfStackClosure(a) => a,
1667             InvokeClosure(a) => a,
1668             DerefPointer(a) => a,
1669             ClosureCapture(a, _) => a,
1670             IndexSlice(a) => a,
1671             RelateObjectBound(a) => a,
1672             RelateParamBound(a, _) => a,
1673             RelateRegionParamBound(a) => a,
1674             RelateDefaultParamBound(a, _) => a,
1675             Reborrow(a) => a,
1676             ReborrowUpvar(a, _) => a,
1677             DataBorrowed(_, a) => a,
1678             ReferenceOutlivesReferent(_, a) => a,
1679             ParameterInScope(_, a) => a,
1680             ExprTypeIsNotInScope(_, a) => a,
1681             BindingTypeIsNotValidAtDecl(a) => a,
1682             CallRcvr(a) => a,
1683             CallArg(a) => a,
1684             CallReturn(a) => a,
1685             Operand(a) => a,
1686             AddrOf(a) => a,
1687             AutoBorrow(a) => a,
1688             SafeDestructor(a) => a,
1689             CompareImplMethodObligation { span, .. } => span,
1690         }
1691     }
1692
1693     pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1694     where
1695         F: FnOnce() -> Self,
1696     {
1697         match cause.code {
1698             traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1699                 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1700             }
1701
1702             traits::ObligationCauseCode::CompareImplMethodObligation {
1703                 item_name,
1704                 impl_item_def_id,
1705                 trait_item_def_id,
1706             } => SubregionOrigin::CompareImplMethodObligation {
1707                 span: cause.span,
1708                 item_name,
1709                 impl_item_def_id,
1710                 trait_item_def_id,
1711             },
1712
1713             _ => default(),
1714         }
1715     }
1716 }
1717
1718 impl RegionVariableOrigin {
1719     pub fn span(&self) -> Span {
1720         match *self {
1721             MiscVariable(a) => a,
1722             PatternRegion(a) => a,
1723             AddrOfRegion(a) => a,
1724             Autoref(a) => a,
1725             Coercion(a) => a,
1726             EarlyBoundRegion(a, ..) => a,
1727             LateBoundRegion(a, ..) => a,
1728             BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1729             UpvarRegion(_, a) => a,
1730             NLL(..) => bug!("NLL variable used with `span`"),
1731         }
1732     }
1733 }
1734
1735 EnumTypeFoldableImpl! {
1736     impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1737         (ValuePairs::Types)(a),
1738         (ValuePairs::Regions)(a),
1739         (ValuePairs::Consts)(a),
1740         (ValuePairs::TraitRefs)(a),
1741         (ValuePairs::PolyTraitRefs)(a),
1742     }
1743 }
1744
1745 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1746     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1747         write!(
1748             f,
1749             "RegionObligation(sub_region={:?}, sup_type={:?})",
1750             self.sub_region, self.sup_type
1751         )
1752     }
1753 }