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