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