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