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