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