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