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