]>
Commit | Line | Data |
---|---|---|
353b0b11 | 1 | pub use self::at::DefineOpaqueTypes; |
74b04a01 | 2 | pub use self::freshen::TypeFreshener; |
94222f64 | 3 | pub use self::lexical_region_resolve::RegionResolutionError; |
74b04a01 XL |
4 | pub use self::LateBoundRegionConversionTime::*; |
5 | pub use self::RegionVariableOrigin::*; | |
6 | pub use self::SubregionOrigin::*; | |
7 | pub use self::ValuePairs::*; | |
9ffffee4 | 8 | pub use combine::ObligationEmittingRelation; |
74b04a01 | 9 | |
5e7ed085 | 10 | use self::opaque_types::OpaqueTypeStorage; |
f9f354fc XL |
11 | pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog}; |
12 | ||
064997fb | 13 | use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine, TraitEngineExt}; |
74b04a01 | 14 | |
487cf647 | 15 | use rustc_data_structures::fx::FxIndexMap; |
74b04a01 XL |
16 | use rustc_data_structures::fx::{FxHashMap, FxHashSet}; |
17 | use rustc_data_structures::sync::Lrc; | |
f9f354fc | 18 | use rustc_data_structures::undo_log::Rollback; |
74b04a01 | 19 | use rustc_data_structures::unify as ut; |
5e7ed085 | 20 | use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed}; |
ba9703b0 XL |
21 | use rustc_hir::def_id::{DefId, LocalDefId}; |
22 | use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues}; | |
23 | use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue}; | |
24 | use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType}; | |
923072b8 | 25 | use rustc_middle::mir::interpret::{ErrorHandled, EvalToValTreeResult}; |
f2b60f7d | 26 | use rustc_middle::mir::ConstraintCategory; |
49aad941 | 27 | use rustc_middle::traits::{select, DefiningAnchor}; |
94222f64 | 28 | use rustc_middle::ty::error::{ExpectedFound, TypeError}; |
064997fb | 29 | use rustc_middle::ty::fold::BoundVarReplacerDelegate; |
923072b8 | 30 | use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; |
ba9703b0 XL |
31 | use rustc_middle::ty::relate::RelateResult; |
32 | use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef}; | |
9ffffee4 | 33 | use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; |
ba9703b0 | 34 | pub use rustc_middle::ty::IntVarValue; |
9ffffee4 | 35 | use rustc_middle::ty::{self, GenericParamDefKind, InferConst, InferTy, Ty, TyCtxt}; |
ba9703b0 | 36 | use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid}; |
74b04a01 | 37 | use rustc_span::symbol::Symbol; |
487cf647 | 38 | use rustc_span::Span; |
ba9703b0 | 39 | |
2b03887a | 40 | use std::cell::{Cell, RefCell}; |
74b04a01 XL |
41 | use std::fmt; |
42 | ||
43 | use self::combine::CombineFields; | |
2b03887a | 44 | use self::error_reporting::TypeErrCtxt; |
f9f354fc | 45 | use self::free_regions::RegionRelations; |
74b04a01 | 46 | use self::lexical_region_resolve::LexicalRegionResolutions; |
353b0b11 | 47 | use self::region_constraints::{GenericKind, VarInfos, VerifyBound}; |
f9f354fc XL |
48 | use self::region_constraints::{ |
49 | RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot, | |
50 | }; | |
c295e0f8 | 51 | use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; |
74b04a01 XL |
52 | |
53 | pub mod at; | |
54 | pub mod canonical; | |
55 | mod combine; | |
56 | mod equate; | |
57 | pub mod error_reporting; | |
f9f354fc | 58 | pub mod free_regions; |
74b04a01 XL |
59 | mod freshen; |
60 | mod fudge; | |
49aad941 | 61 | mod generalize; |
74b04a01 XL |
62 | mod glb; |
63 | mod higher_ranked; | |
64 | pub mod lattice; | |
65 | mod lexical_region_resolve; | |
66 | mod lub; | |
67 | pub mod nll_relate; | |
94222f64 | 68 | pub mod opaque_types; |
74b04a01 | 69 | pub mod outlives; |
c295e0f8 | 70 | mod projection; |
74b04a01 XL |
71 | pub mod region_constraints; |
72 | pub mod resolve; | |
73 | mod sub; | |
74 | pub mod type_variable; | |
f9f354fc | 75 | mod undo_log; |
74b04a01 | 76 | |
74b04a01 XL |
77 | #[must_use] |
78 | #[derive(Debug)] | |
79 | pub struct InferOk<'tcx, T> { | |
80 | pub value: T, | |
81 | pub obligations: PredicateObligations<'tcx>, | |
82 | } | |
83 | pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>; | |
84 | ||
74b04a01 XL |
85 | pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result" |
86 | pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result" | |
87 | ||
f9f354fc XL |
88 | pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable< |
89 | ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>, | |
90 | >; | |
91 | ||
74b04a01 XL |
92 | /// This type contains all the things within `InferCtxt` that sit within a |
93 | /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot | |
94 | /// operations are hot enough that we want only one call to `borrow_mut` per | |
95 | /// call to `start_snapshot` and `rollback_to`. | |
5099ac24 | 96 | #[derive(Clone)] |
74b04a01 | 97 | pub struct InferCtxtInner<'tcx> { |
353b0b11 | 98 | /// Cache for projections. |
74b04a01 | 99 | /// |
353b0b11 FG |
100 | /// This cache is snapshotted along with the infcx. |
101 | projection_cache: traits::ProjectionCacheStorage<'tcx>, | |
74b04a01 XL |
102 | |
103 | /// We instantiate `UnificationTable` with `bounds<Ty>` because the types | |
104 | /// that might instantiate a general type variable have an order, | |
105 | /// represented by its upper and lower bounds. | |
f9f354fc | 106 | type_variable_storage: type_variable::TypeVariableStorage<'tcx>, |
74b04a01 XL |
107 | |
108 | /// Map from const parameter variable to the kind of const it represents. | |
f9f354fc | 109 | const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>, |
74b04a01 XL |
110 | |
111 | /// Map from integral variable to the kind of integer it represents. | |
f9f354fc | 112 | int_unification_storage: ut::UnificationTableStorage<ty::IntVid>, |
74b04a01 XL |
113 | |
114 | /// Map from floating variable to the kind of float it represents. | |
f9f354fc | 115 | float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>, |
74b04a01 XL |
116 | |
117 | /// Tracks the set of region variables and the constraints between them. | |
353b0b11 | 118 | /// |
74b04a01 XL |
119 | /// This is initially `Some(_)` but when |
120 | /// `resolve_regions_and_report_errors` is invoked, this gets set to `None` | |
121 | /// -- further attempts to perform unification, etc., may fail if new | |
122 | /// region constraints would've been added. | |
f9f354fc | 123 | region_constraint_storage: Option<RegionConstraintStorage<'tcx>>, |
74b04a01 | 124 | |
353b0b11 FG |
125 | /// A set of constraints that regionck must validate. |
126 | /// | |
127 | /// Each constraint has the form `T:'a`, meaning "some type `T` must | |
74b04a01 XL |
128 | /// outlive the lifetime 'a". These constraints derive from |
129 | /// instantiated type parameters. So if you had a struct defined | |
353b0b11 | 130 | /// like the following: |
04454e1e | 131 | /// ```ignore (illustrative) |
353b0b11 | 132 | /// struct Foo<T: 'static> { ... } |
04454e1e | 133 | /// ``` |
353b0b11 | 134 | /// In some expression `let x = Foo { ... }`, it will |
74b04a01 XL |
135 | /// instantiate the type parameter `T` with a fresh type `$0`. At |
136 | /// the same time, it will record a region obligation of | |
353b0b11 | 137 | /// `$0: 'static`. This will get checked later by regionck. (We |
74b04a01 XL |
138 | /// can't generally check these things right away because we have |
139 | /// to wait until types are resolved.) | |
140 | /// | |
141 | /// These are stored in a map keyed to the id of the innermost | |
142 | /// enclosing fn body / static initializer expression. This is | |
143 | /// because the location where the obligation was incurred can be | |
144 | /// relevant with respect to which sublifetime assumptions are in | |
145 | /// place. The reason that we store under the fn-id, and not | |
146 | /// something more fine-grained, is so that it is easier for | |
147 | /// regionck to be sure that it has found *all* the region | |
148 | /// obligations (otherwise, it's easy to fail to walk to a | |
149 | /// particular node-id). | |
150 | /// | |
151 | /// Before running `resolve_regions_and_report_errors`, the creator | |
152 | /// of the inference context is expected to invoke | |
923072b8 | 153 | /// [`InferCtxt::process_registered_region_obligations`] |
74b04a01 XL |
154 | /// for each body-id in this map, which will process the |
155 | /// obligations within. This is expected to be done 'late enough' | |
156 | /// that all type inference variables have been bound and so forth. | |
064997fb | 157 | region_obligations: Vec<RegionObligation<'tcx>>, |
f9f354fc XL |
158 | |
159 | undo_log: InferCtxtUndoLogs<'tcx>, | |
94222f64 | 160 | |
5e7ed085 | 161 | /// Caches for opaque type inference. |
9ffffee4 | 162 | opaque_type_storage: OpaqueTypeStorage<'tcx>, |
74b04a01 XL |
163 | } |
164 | ||
165 | impl<'tcx> InferCtxtInner<'tcx> { | |
166 | fn new() -> InferCtxtInner<'tcx> { | |
167 | InferCtxtInner { | |
168 | projection_cache: Default::default(), | |
f9f354fc XL |
169 | type_variable_storage: type_variable::TypeVariableStorage::new(), |
170 | undo_log: InferCtxtUndoLogs::default(), | |
171 | const_unification_storage: ut::UnificationTableStorage::new(), | |
172 | int_unification_storage: ut::UnificationTableStorage::new(), | |
173 | float_unification_storage: ut::UnificationTableStorage::new(), | |
174 | region_constraint_storage: Some(RegionConstraintStorage::new()), | |
74b04a01 | 175 | region_obligations: vec![], |
5e7ed085 | 176 | opaque_type_storage: Default::default(), |
74b04a01 XL |
177 | } |
178 | } | |
179 | ||
f9f354fc | 180 | #[inline] |
064997fb | 181 | pub fn region_obligations(&self) -> &[RegionObligation<'tcx>] { |
f9f354fc XL |
182 | &self.region_obligations |
183 | } | |
184 | ||
185 | #[inline] | |
186 | pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> { | |
187 | self.projection_cache.with_log(&mut self.undo_log) | |
188 | } | |
189 | ||
353b0b11 FG |
190 | #[inline] |
191 | fn try_type_variables_probe_ref( | |
192 | &self, | |
193 | vid: ty::TyVid, | |
194 | ) -> Option<&type_variable::TypeVariableValue<'tcx>> { | |
195 | // Uses a read-only view of the unification table, this way we don't | |
196 | // need an undo log. | |
197 | self.type_variable_storage.eq_relations_ref().try_probe_value(vid) | |
198 | } | |
199 | ||
f9f354fc XL |
200 | #[inline] |
201 | fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { | |
202 | self.type_variable_storage.with_log(&mut self.undo_log) | |
203 | } | |
204 | ||
5e7ed085 FG |
205 | #[inline] |
206 | pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> { | |
207 | self.opaque_type_storage.with_log(&mut self.undo_log) | |
208 | } | |
209 | ||
f9f354fc | 210 | #[inline] |
9ffffee4 | 211 | fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> { |
f9f354fc XL |
212 | self.int_unification_storage.with_log(&mut self.undo_log) |
213 | } | |
214 | ||
215 | #[inline] | |
9ffffee4 | 216 | fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> { |
f9f354fc XL |
217 | self.float_unification_storage.with_log(&mut self.undo_log) |
218 | } | |
219 | ||
220 | #[inline] | |
9ffffee4 | 221 | fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::ConstVid<'tcx>> { |
f9f354fc XL |
222 | self.const_unification_storage.with_log(&mut self.undo_log) |
223 | } | |
224 | ||
225 | #[inline] | |
226 | pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { | |
227 | self.region_constraint_storage | |
228 | .as_mut() | |
229 | .expect("region constraints already solved") | |
230 | .with_log(&mut self.undo_log) | |
74b04a01 XL |
231 | } |
232 | } | |
233 | ||
2b03887a | 234 | pub struct InferCtxt<'tcx> { |
74b04a01 XL |
235 | pub tcx: TyCtxt<'tcx>, |
236 | ||
94222f64 XL |
237 | /// The `DefId` of the item in whose context we are performing inference or typeck. |
238 | /// It is used to check whether an opaque type use is a defining use. | |
5099ac24 | 239 | /// |
064997fb | 240 | /// If it is `DefiningAnchor::Bubble`, we can't resolve opaque types here and need to bubble up |
5099ac24 FG |
241 | /// the obligation. This frequently happens for |
242 | /// short lived InferCtxt within queries. The opaque type obligations are forwarded | |
243 | /// to the outside until the end up in an `InferCtxt` for typeck or borrowck. | |
064997fb | 244 | /// |
9ffffee4 | 245 | /// Its default value is `DefiningAnchor::Error`, this way it is easier to catch errors that |
064997fb FG |
246 | /// might come up during inference or typeck. |
247 | pub defining_use_anchor: DefiningAnchor, | |
248 | ||
249 | /// Whether this inference context should care about region obligations in | |
250 | /// the root universe. Most notably, this is used during hir typeck as region | |
251 | /// solving is left to borrowck instead. | |
252 | pub considering_regions: bool, | |
94222f64 | 253 | |
74b04a01 XL |
254 | pub inner: RefCell<InferCtxtInner<'tcx>>, |
255 | ||
256 | /// If set, this flag causes us to skip the 'leak check' during | |
257 | /// higher-ranked subtyping operations. This flag is a temporary one used | |
258 | /// to manage the removal of the leak-check: for the time being, we still run the | |
259 | /// leak-check, but we issue warnings. This flag can only be set to true | |
260 | /// when entering a snapshot. | |
261 | skip_leak_check: Cell<bool>, | |
262 | ||
263 | /// Once region inference is done, the values for each variable. | |
264 | lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>, | |
265 | ||
266 | /// Caches the results of trait selection. This cache is used | |
267 | /// for things that have to do with the parameters in scope. | |
ba9703b0 | 268 | pub selection_cache: select::SelectionCache<'tcx>, |
74b04a01 XL |
269 | |
270 | /// Caches the results of trait evaluation. | |
ba9703b0 | 271 | pub evaluation_cache: select::EvaluationCache<'tcx>, |
74b04a01 | 272 | |
353b0b11 | 273 | /// The set of predicates on which errors have been reported, to |
74b04a01 | 274 | /// avoid reporting the same error twice. |
487cf647 | 275 | pub reported_trait_errors: RefCell<FxIndexMap<Span, Vec<ty::Predicate<'tcx>>>>, |
74b04a01 XL |
276 | |
277 | pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>, | |
278 | ||
279 | /// When an error occurs, we want to avoid reporting "derived" | |
280 | /// errors that are due to this original failure. Normally, we | |
281 | /// handle this with the `err_count_on_creation` count, which | |
282 | /// basically just tracks how many errors were reported when we | |
283 | /// started type-checking a fn and checks to see if any new errors | |
284 | /// have been reported since then. Not great, but it works. | |
285 | /// | |
286 | /// However, when errors originated in other passes -- notably | |
287 | /// resolve -- this heuristic breaks down. Therefore, we have this | |
288 | /// auxiliary flag that one can set whenever one creates a | |
289 | /// type-error that is due to an error in a prior pass. | |
290 | /// | |
291 | /// Don't read this flag directly, call `is_tainted_by_errors()` | |
292 | /// and `set_tainted_by_errors()`. | |
f2b60f7d | 293 | tainted_by_errors: Cell<Option<ErrorGuaranteed>>, |
74b04a01 XL |
294 | |
295 | /// Track how many errors were reported when this infcx is created. | |
353b0b11 | 296 | /// If the number of errors increases, that's also a sign (like |
5e7ed085 | 297 | /// `tainted_by_errors`) to avoid reporting certain kinds of errors. |
f2b60f7d | 298 | // FIXME(matthewjasper) Merge into `tainted_by_errors` |
74b04a01 XL |
299 | err_count_on_creation: usize, |
300 | ||
301 | /// This flag is true while there is an active snapshot. | |
302 | in_snapshot: Cell<bool>, | |
303 | ||
304 | /// What is the innermost universe we have created? Starts out as | |
305 | /// `UniverseIndex::root()` but grows from there as we enter | |
306 | /// universal quantifiers. | |
307 | /// | |
308 | /// N.B., at present, we exclude the universal quantifiers on the | |
309 | /// item we are type-checking, and just consider those names as | |
310 | /// part of the root universe. So this would only get incremented | |
311 | /// when we enter into a higher-ranked (`for<..>`) type or trait | |
312 | /// bound. | |
313 | universe: Cell<ty::UniverseIndex>, | |
f2b60f7d | 314 | |
487cf647 FG |
315 | /// During coherence we have to assume that other crates may add |
316 | /// additional impls which we currently don't know about. | |
317 | /// | |
353b0b11 | 318 | /// To deal with this evaluation, we should be conservative |
487cf647 FG |
319 | /// and consider the possibility of impls from outside this crate. |
320 | /// This comes up primarily when resolving ambiguity. Imagine | |
321 | /// there is some trait reference `$0: Bar` where `$0` is an | |
322 | /// inference variable. If `intercrate` is true, then we can never | |
323 | /// say for sure that this reference is not implemented, even if | |
324 | /// there are *no impls at all for `Bar`*, because `$0` could be | |
325 | /// bound to some type that in a downstream crate that implements | |
326 | /// `Bar`. | |
327 | /// | |
353b0b11 | 328 | /// Outside of coherence, we set this to false because we are only |
487cf647 FG |
329 | /// interested in types that the user could actually have written. |
330 | /// In other words, we consider `$0: Bar` to be unimplemented if | |
331 | /// there is no type that the user could *actually name* that | |
332 | /// would satisfy it. This avoids crippling inference, basically. | |
333 | pub intercrate: bool, | |
74b04a01 XL |
334 | } |
335 | ||
74b04a01 | 336 | /// See the `error_reporting` module for more details. |
064997fb | 337 | #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)] |
74b04a01 | 338 | pub enum ValuePairs<'tcx> { |
74b04a01 | 339 | Regions(ExpectedFound<ty::Region<'tcx>>), |
5099ac24 | 340 | Terms(ExpectedFound<ty::Term<'tcx>>), |
353b0b11 | 341 | Aliases(ExpectedFound<ty::AliasTy<'tcx>>), |
74b04a01 XL |
342 | TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>), |
343 | PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>), | |
9c376795 | 344 | Sigs(ExpectedFound<ty::FnSig<'tcx>>), |
74b04a01 XL |
345 | } |
346 | ||
5099ac24 FG |
347 | impl<'tcx> ValuePairs<'tcx> { |
348 | pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> { | |
f2b60f7d FG |
349 | if let ValuePairs::Terms(ExpectedFound { expected, found }) = self |
350 | && let Some(expected) = expected.ty() | |
351 | && let Some(found) = found.ty() | |
5099ac24 | 352 | { |
f2b60f7d | 353 | Some((expected, found)) |
5099ac24 FG |
354 | } else { |
355 | None | |
356 | } | |
357 | } | |
358 | } | |
359 | ||
74b04a01 XL |
360 | /// The trace designates the path through inference that we took to |
361 | /// encounter an error or subtyping constraint. | |
362 | /// | |
363 | /// See the `error_reporting` module for more details. | |
364 | #[derive(Clone, Debug)] | |
365 | pub struct TypeTrace<'tcx> { | |
04454e1e FG |
366 | pub cause: ObligationCause<'tcx>, |
367 | pub values: ValuePairs<'tcx>, | |
74b04a01 XL |
368 | } |
369 | ||
370 | /// The origin of a `r1 <= r2` constraint. | |
371 | /// | |
372 | /// See `error_reporting` module for more details | |
373 | #[derive(Clone, Debug)] | |
374 | pub enum SubregionOrigin<'tcx> { | |
375 | /// Arose from a subtyping relation | |
376 | Subtype(Box<TypeTrace<'tcx>>), | |
377 | ||
74b04a01 | 378 | /// When casting `&'a T` to an `&'b Trait` object, |
353b0b11 | 379 | /// relating `'a` to `'b`. |
74b04a01 XL |
380 | RelateObjectBound(Span), |
381 | ||
382 | /// Some type parameter was instantiated with the given type, | |
383 | /// and that type must outlive some region. | |
94222f64 | 384 | RelateParamBound(Span, Ty<'tcx>, Option<Span>), |
74b04a01 XL |
385 | |
386 | /// The given region parameter was instantiated with a region | |
387 | /// that must outlive some other region. | |
388 | RelateRegionParamBound(Span), | |
389 | ||
353b0b11 | 390 | /// Creating a pointer `b` to contents of another reference. |
74b04a01 XL |
391 | Reborrow(Span), |
392 | ||
74b04a01 XL |
393 | /// (&'a &'b T) where a >= b |
394 | ReferenceOutlivesReferent(Ty<'tcx>, Span), | |
395 | ||
74b04a01 XL |
396 | /// Comparing the signature and requirements of an impl method against |
397 | /// the containing trait. | |
f2b60f7d FG |
398 | CompareImplItemObligation { |
399 | span: Span, | |
400 | impl_item_def_id: LocalDefId, | |
401 | trait_item_def_id: DefId, | |
402 | }, | |
5099ac24 | 403 | |
353b0b11 | 404 | /// Checking that the bounds of a trait's associated type hold for a given impl. |
5099ac24 FG |
405 | CheckAssociatedTypeBounds { |
406 | parent: Box<SubregionOrigin<'tcx>>, | |
5e7ed085 | 407 | impl_item_def_id: LocalDefId, |
5099ac24 FG |
408 | trait_item_def_id: DefId, |
409 | }, | |
f2b60f7d FG |
410 | |
411 | AscribeUserTypeProvePredicate(Span), | |
74b04a01 XL |
412 | } |
413 | ||
414 | // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger. | |
6a06907d | 415 | #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] |
74b04a01 XL |
416 | static_assert_size!(SubregionOrigin<'_>, 32); |
417 | ||
f2b60f7d FG |
418 | impl<'tcx> SubregionOrigin<'tcx> { |
419 | pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> { | |
420 | match self { | |
421 | Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(), | |
422 | Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span), | |
423 | _ => ConstraintCategory::BoringNoLocation, | |
424 | } | |
425 | } | |
426 | } | |
427 | ||
74b04a01 XL |
428 | /// Times when we replace late-bound regions with variables: |
429 | #[derive(Clone, Copy, Debug)] | |
430 | pub enum LateBoundRegionConversionTime { | |
431 | /// when a fn is called | |
432 | FnCall, | |
433 | ||
434 | /// when two higher-ranked types are compared | |
435 | HigherRankedType, | |
436 | ||
437 | /// when projecting an associated type | |
438 | AssocTypeProjection(DefId), | |
439 | } | |
440 | ||
353b0b11 | 441 | /// Reasons to create a region inference variable. |
74b04a01 | 442 | /// |
353b0b11 | 443 | /// See `error_reporting` module for more details. |
74b04a01 XL |
444 | #[derive(Copy, Clone, Debug)] |
445 | pub enum RegionVariableOrigin { | |
353b0b11 FG |
446 | /// Region variables created for ill-categorized reasons. |
447 | /// | |
448 | /// They mostly indicate places in need of refactoring. | |
74b04a01 XL |
449 | MiscVariable(Span), |
450 | ||
353b0b11 | 451 | /// Regions created by a `&P` or `[...]` pattern. |
74b04a01 XL |
452 | PatternRegion(Span), |
453 | ||
353b0b11 FG |
454 | /// Regions created by `&` operator. |
455 | /// | |
74b04a01 | 456 | AddrOfRegion(Span), |
353b0b11 | 457 | /// Regions created as part of an autoref of a method receiver. |
3c0e092e | 458 | Autoref(Span), |
74b04a01 | 459 | |
353b0b11 | 460 | /// Regions created as part of an automatic coercion. |
74b04a01 XL |
461 | Coercion(Span), |
462 | ||
353b0b11 | 463 | /// Region variables created as the values for early-bound regions. |
74b04a01 XL |
464 | EarlyBoundRegion(Span, Symbol), |
465 | ||
466 | /// Region variables created for bound regions | |
353b0b11 | 467 | /// in a function or method that is called. |
fc512014 | 468 | LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime), |
74b04a01 XL |
469 | |
470 | UpvarRegion(ty::UpvarId, Span), | |
471 | ||
74b04a01 XL |
472 | /// This origin is used for the inference variables that we create |
473 | /// during NLL region processing. | |
5869c6ff | 474 | Nll(NllRegionVariableOrigin), |
74b04a01 XL |
475 | } |
476 | ||
477 | #[derive(Copy, Clone, Debug)] | |
5869c6ff | 478 | pub enum NllRegionVariableOrigin { |
74b04a01 XL |
479 | /// During NLL region processing, we create variables for free |
480 | /// regions that we encounter in the function signature and | |
481 | /// elsewhere. This origin indices we've got one of those. | |
482 | FreeRegion, | |
483 | ||
484 | /// "Universal" instantiation of a higher-ranked region (e.g., | |
485 | /// from a `for<'a> T` binder). Meant to represent "any region". | |
486 | Placeholder(ty::PlaceholderRegion), | |
487 | ||
488 | Existential { | |
489 | /// If this is true, then this variable was created to represent a lifetime | |
490 | /// bound in a `for` binder. For example, it might have been created to | |
491 | /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`. | |
492 | /// Such variables are created when we are trying to figure out if there | |
493 | /// is any valid instantiation of `'a` that could fit into some scenario. | |
494 | /// | |
495 | /// This is used to inform error reporting: in the case that we are trying to | |
496 | /// determine whether there is any valid instantiation of a `'a` variable that meets | |
497 | /// some constraint C, we want to blame the "source" of that `for` type, | |
498 | /// rather than blaming the source of the constraint C. | |
499 | from_forall: bool, | |
500 | }, | |
501 | } | |
502 | ||
ba9703b0 | 503 | // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`. |
74b04a01 XL |
504 | #[derive(Copy, Clone, Debug)] |
505 | pub enum FixupError<'tcx> { | |
506 | UnresolvedIntTy(IntVid), | |
507 | UnresolvedFloatTy(FloatVid), | |
508 | UnresolvedTy(TyVid), | |
509 | UnresolvedConst(ConstVid<'tcx>), | |
510 | } | |
511 | ||
512 | /// See the `region_obligations` field for more information. | |
f2b60f7d | 513 | #[derive(Clone, Debug)] |
74b04a01 XL |
514 | pub struct RegionObligation<'tcx> { |
515 | pub sub_region: ty::Region<'tcx>, | |
516 | pub sup_type: Ty<'tcx>, | |
517 | pub origin: SubregionOrigin<'tcx>, | |
518 | } | |
519 | ||
520 | impl<'tcx> fmt::Display for FixupError<'tcx> { | |
521 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
522 | use self::FixupError::*; | |
523 | ||
524 | match *self { | |
525 | UnresolvedIntTy(_) => write!( | |
526 | f, | |
527 | "cannot determine the type of this integer; \ | |
528 | add a suffix to specify the type explicitly" | |
529 | ), | |
530 | UnresolvedFloatTy(_) => write!( | |
531 | f, | |
532 | "cannot determine the type of this number; \ | |
533 | add a suffix to specify the type explicitly" | |
534 | ), | |
535 | UnresolvedTy(_) => write!(f, "unconstrained type"), | |
536 | UnresolvedConst(_) => write!(f, "unconstrained const value"), | |
537 | } | |
538 | } | |
539 | } | |
540 | ||
353b0b11 | 541 | /// Used to configure inference contexts before their creation. |
74b04a01 | 542 | pub struct InferCtxtBuilder<'tcx> { |
f035d41b | 543 | tcx: TyCtxt<'tcx>, |
064997fb FG |
544 | defining_use_anchor: DefiningAnchor, |
545 | considering_regions: bool, | |
487cf647 FG |
546 | /// Whether we are in coherence mode. |
547 | intercrate: bool, | |
74b04a01 XL |
548 | } |
549 | ||
550 | pub trait TyCtxtInferExt<'tcx> { | |
551 | fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>; | |
552 | } | |
553 | ||
a2a8927a | 554 | impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> { |
74b04a01 | 555 | fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { |
064997fb FG |
556 | InferCtxtBuilder { |
557 | tcx: self, | |
558 | defining_use_anchor: DefiningAnchor::Error, | |
559 | considering_regions: true, | |
487cf647 | 560 | intercrate: false, |
064997fb | 561 | } |
74b04a01 XL |
562 | } |
563 | } | |
564 | ||
565 | impl<'tcx> InferCtxtBuilder<'tcx> { | |
94222f64 XL |
566 | /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types, |
567 | /// you need to call this function. Otherwise the opaque type will be treated opaquely. | |
568 | /// | |
569 | /// It is only meant to be called in two places, for typeck | |
2b03887a | 570 | /// (via `Inherited::build`) and for the inference context used |
94222f64 | 571 | /// in mir borrowck. |
064997fb FG |
572 | pub fn with_opaque_type_inference(mut self, defining_use_anchor: DefiningAnchor) -> Self { |
573 | self.defining_use_anchor = defining_use_anchor; | |
574 | self | |
575 | } | |
576 | ||
353b0b11 FG |
577 | pub fn intercrate(mut self, intercrate: bool) -> Self { |
578 | self.intercrate = intercrate; | |
74b04a01 XL |
579 | self |
580 | } | |
581 | ||
487cf647 FG |
582 | pub fn ignoring_regions(mut self) -> Self { |
583 | self.considering_regions = false; | |
f2b60f7d FG |
584 | self |
585 | } | |
586 | ||
74b04a01 XL |
587 | /// Given a canonical value `C` as a starting point, create an |
588 | /// inference context that contains each of the bound values | |
589 | /// within instantiated as a fresh variable. The `f` closure is | |
590 | /// invoked with the new infcx, along with the instantiated value | |
591 | /// `V` and a substitution `S`. This substitution `S` maps from | |
592 | /// the bound values in `C` to their instantiated values in `V` | |
593 | /// (in other words, `S(C) = V`). | |
2b03887a | 594 | pub fn build_with_canonical<T>( |
74b04a01 XL |
595 | &mut self, |
596 | span: Span, | |
597 | canonical: &Canonical<'tcx, T>, | |
2b03887a | 598 | ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>) |
74b04a01 | 599 | where |
9ffffee4 | 600 | T: TypeFoldable<TyCtxt<'tcx>>, |
74b04a01 | 601 | { |
2b03887a FG |
602 | let infcx = self.build(); |
603 | let (value, subst) = infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); | |
604 | (infcx, value, subst) | |
74b04a01 XL |
605 | } |
606 | ||
2b03887a | 607 | pub fn build(&mut self) -> InferCtxt<'tcx> { |
487cf647 | 608 | let InferCtxtBuilder { tcx, defining_use_anchor, considering_regions, intercrate } = *self; |
2b03887a | 609 | InferCtxt { |
f035d41b | 610 | tcx, |
94222f64 | 611 | defining_use_anchor, |
064997fb | 612 | considering_regions, |
f035d41b XL |
613 | inner: RefCell::new(InferCtxtInner::new()), |
614 | lexical_region_resolutions: RefCell::new(None), | |
615 | selection_cache: Default::default(), | |
616 | evaluation_cache: Default::default(), | |
617 | reported_trait_errors: Default::default(), | |
618 | reported_closure_mismatch: Default::default(), | |
f2b60f7d | 619 | tainted_by_errors: Cell::new(None), |
f035d41b XL |
620 | err_count_on_creation: tcx.sess.err_count(), |
621 | in_snapshot: Cell::new(false), | |
622 | skip_leak_check: Cell::new(false), | |
623 | universe: Cell::new(ty::UniverseIndex::ROOT), | |
487cf647 | 624 | intercrate, |
2b03887a | 625 | } |
74b04a01 XL |
626 | } |
627 | } | |
628 | ||
629 | impl<'tcx, T> InferOk<'tcx, T> { | |
630 | pub fn unit(self) -> InferOk<'tcx, ()> { | |
631 | InferOk { value: (), obligations: self.obligations } | |
632 | } | |
633 | ||
634 | /// Extracts `value`, registering any obligations into `fulfill_cx`. | |
635 | pub fn into_value_registering_obligations( | |
636 | self, | |
2b03887a | 637 | infcx: &InferCtxt<'tcx>, |
74b04a01 XL |
638 | fulfill_cx: &mut dyn TraitEngine<'tcx>, |
639 | ) -> T { | |
640 | let InferOk { value, obligations } = self; | |
064997fb | 641 | fulfill_cx.register_predicate_obligations(infcx, obligations); |
74b04a01 XL |
642 | value |
643 | } | |
644 | } | |
645 | ||
646 | impl<'tcx> InferOk<'tcx, ()> { | |
647 | pub fn into_obligations(self) -> PredicateObligations<'tcx> { | |
648 | self.obligations | |
649 | } | |
650 | } | |
651 | ||
652 | #[must_use = "once you start a snapshot, you should always consume it"] | |
2b03887a | 653 | pub struct CombinedSnapshot<'tcx> { |
f9f354fc | 654 | undo_snapshot: Snapshot<'tcx>, |
74b04a01 | 655 | region_constraints_snapshot: RegionSnapshot, |
74b04a01 XL |
656 | universe: ty::UniverseIndex, |
657 | was_in_snapshot: bool, | |
74b04a01 XL |
658 | } |
659 | ||
2b03887a FG |
660 | impl<'tcx> InferCtxt<'tcx> { |
661 | /// Creates a `TypeErrCtxt` for emitting various inference errors. | |
487cf647 | 662 | /// During typeck, use `FnCtxt::err_ctxt` instead. |
2b03887a | 663 | pub fn err_ctxt(&self) -> TypeErrCtxt<'_, 'tcx> { |
487cf647 FG |
664 | TypeErrCtxt { |
665 | infcx: self, | |
666 | typeck_results: None, | |
667 | fallback_has_occurred: false, | |
668 | normalize_fn_sig: Box::new(|fn_sig| fn_sig), | |
9c376795 FG |
669 | autoderef_steps: Box::new(|ty| { |
670 | debug_assert!(false, "shouldn't be using autoderef_steps outside of typeck"); | |
671 | vec![(ty, vec![])] | |
672 | }), | |
5e7ed085 | 673 | } |
94222f64 XL |
674 | } |
675 | ||
74b04a01 XL |
676 | pub fn is_in_snapshot(&self) -> bool { |
677 | self.in_snapshot.get() | |
678 | } | |
679 | ||
9ffffee4 | 680 | pub fn freshen<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> T { |
74b04a01 XL |
681 | t.fold_with(&mut self.freshener()) |
682 | } | |
683 | ||
94222f64 XL |
684 | /// Returns the origin of the type variable identified by `vid`, or `None` |
685 | /// if this is not a type variable. | |
686 | /// | |
687 | /// No attempt is made to resolve `ty`. | |
2b03887a | 688 | pub fn type_var_origin(&self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> { |
94222f64 XL |
689 | match *ty.kind() { |
690 | ty::Infer(ty::TyVar(vid)) => { | |
691 | Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) | |
692 | } | |
693 | _ => None, | |
74b04a01 XL |
694 | } |
695 | } | |
696 | ||
697 | pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { | |
353b0b11 | 698 | freshen::TypeFreshener::new(self) |
74b04a01 XL |
699 | } |
700 | ||
74b04a01 XL |
701 | pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> { |
702 | let mut inner = self.inner.borrow_mut(); | |
74b04a01 | 703 | let mut vars: Vec<Ty<'_>> = inner |
f9f354fc | 704 | .type_variables() |
74b04a01 XL |
705 | .unsolved_variables() |
706 | .into_iter() | |
707 | .map(|t| self.tcx.mk_ty_var(t)) | |
708 | .collect(); | |
709 | vars.extend( | |
f9f354fc | 710 | (0..inner.int_unification_table().len()) |
74b04a01 | 711 | .map(|i| ty::IntVid { index: i as u32 }) |
f9f354fc | 712 | .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none()) |
74b04a01 XL |
713 | .map(|v| self.tcx.mk_int_var(v)), |
714 | ); | |
715 | vars.extend( | |
f9f354fc | 716 | (0..inner.float_unification_table().len()) |
74b04a01 | 717 | .map(|i| ty::FloatVid { index: i as u32 }) |
f9f354fc | 718 | .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none()) |
74b04a01 XL |
719 | .map(|v| self.tcx.mk_float_var(v)), |
720 | ); | |
721 | vars | |
722 | } | |
723 | ||
2b03887a | 724 | fn combine_fields<'a>( |
74b04a01 XL |
725 | &'a self, |
726 | trace: TypeTrace<'tcx>, | |
727 | param_env: ty::ParamEnv<'tcx>, | |
353b0b11 | 728 | define_opaque_types: DefineOpaqueTypes, |
74b04a01 XL |
729 | ) -> CombineFields<'a, 'tcx> { |
730 | CombineFields { | |
731 | infcx: self, | |
732 | trace, | |
733 | cause: None, | |
734 | param_env, | |
735 | obligations: PredicateObligations::new(), | |
5e7ed085 | 736 | define_opaque_types, |
74b04a01 XL |
737 | } |
738 | } | |
739 | ||
2b03887a | 740 | fn start_snapshot(&self) -> CombinedSnapshot<'tcx> { |
74b04a01 XL |
741 | debug!("start_snapshot()"); |
742 | ||
743 | let in_snapshot = self.in_snapshot.replace(true); | |
744 | ||
745 | let mut inner = self.inner.borrow_mut(); | |
f9f354fc | 746 | |
74b04a01 | 747 | CombinedSnapshot { |
f9f354fc | 748 | undo_snapshot: inner.undo_log.start_snapshot(), |
74b04a01 | 749 | region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(), |
74b04a01 XL |
750 | universe: self.universe(), |
751 | was_in_snapshot: in_snapshot, | |
74b04a01 XL |
752 | } |
753 | } | |
754 | ||
c295e0f8 | 755 | #[instrument(skip(self, snapshot), level = "debug")] |
2b03887a | 756 | fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'tcx>) { |
74b04a01 | 757 | let CombinedSnapshot { |
f9f354fc | 758 | undo_snapshot, |
74b04a01 | 759 | region_constraints_snapshot, |
74b04a01 XL |
760 | universe, |
761 | was_in_snapshot, | |
74b04a01 XL |
762 | } = snapshot; |
763 | ||
764 | self.in_snapshot.set(was_in_snapshot); | |
765 | self.universe.set(universe); | |
74b04a01 XL |
766 | |
767 | let mut inner = self.inner.borrow_mut(); | |
f9f354fc | 768 | inner.rollback_to(undo_snapshot); |
74b04a01 | 769 | inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); |
74b04a01 XL |
770 | } |
771 | ||
c295e0f8 | 772 | #[instrument(skip(self, snapshot), level = "debug")] |
2b03887a | 773 | fn commit_from(&self, snapshot: CombinedSnapshot<'tcx>) { |
74b04a01 | 774 | let CombinedSnapshot { |
f9f354fc XL |
775 | undo_snapshot, |
776 | region_constraints_snapshot: _, | |
74b04a01 XL |
777 | universe: _, |
778 | was_in_snapshot, | |
74b04a01 XL |
779 | } = snapshot; |
780 | ||
781 | self.in_snapshot.set(was_in_snapshot); | |
74b04a01 | 782 | |
f9f354fc | 783 | self.inner.borrow_mut().commit(undo_snapshot); |
74b04a01 XL |
784 | } |
785 | ||
74b04a01 | 786 | /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. |
c295e0f8 | 787 | #[instrument(skip(self, f), level = "debug")] |
74b04a01 XL |
788 | pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> |
789 | where | |
2b03887a | 790 | F: FnOnce(&CombinedSnapshot<'tcx>) -> Result<T, E>, |
74b04a01 | 791 | { |
74b04a01 XL |
792 | let snapshot = self.start_snapshot(); |
793 | let r = f(&snapshot); | |
794 | debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); | |
795 | match r { | |
796 | Ok(_) => { | |
797 | self.commit_from(snapshot); | |
798 | } | |
799 | Err(_) => { | |
800 | self.rollback_to("commit_if_ok -- error", snapshot); | |
801 | } | |
802 | } | |
803 | r | |
804 | } | |
805 | ||
806 | /// Execute `f` then unroll any bindings it creates. | |
c295e0f8 | 807 | #[instrument(skip(self, f), level = "debug")] |
74b04a01 XL |
808 | pub fn probe<R, F>(&self, f: F) -> R |
809 | where | |
2b03887a | 810 | F: FnOnce(&CombinedSnapshot<'tcx>) -> R, |
74b04a01 | 811 | { |
74b04a01 XL |
812 | let snapshot = self.start_snapshot(); |
813 | let r = f(&snapshot); | |
814 | self.rollback_to("probe", snapshot); | |
815 | r | |
816 | } | |
817 | ||
818 | /// If `should_skip` is true, then execute `f` then unroll any bindings it creates. | |
c295e0f8 | 819 | #[instrument(skip(self, f), level = "debug")] |
74b04a01 XL |
820 | pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R |
821 | where | |
2b03887a | 822 | F: FnOnce(&CombinedSnapshot<'tcx>) -> R, |
74b04a01 | 823 | { |
74b04a01 | 824 | let snapshot = self.start_snapshot(); |
f9f354fc XL |
825 | let was_skip_leak_check = self.skip_leak_check.get(); |
826 | if should_skip { | |
827 | self.skip_leak_check.set(true); | |
828 | } | |
74b04a01 XL |
829 | let r = f(&snapshot); |
830 | self.rollback_to("probe", snapshot); | |
f9f354fc | 831 | self.skip_leak_check.set(was_skip_leak_check); |
74b04a01 XL |
832 | r |
833 | } | |
834 | ||
835 | /// Scan the constraints produced since `snapshot` began and returns: | |
836 | /// | |
353b0b11 FG |
837 | /// - `None` -- if none of them involves "region outlives" constraints. |
838 | /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder. | |
839 | /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders. | |
74b04a01 XL |
840 | pub fn region_constraints_added_in_snapshot( |
841 | &self, | |
2b03887a | 842 | snapshot: &CombinedSnapshot<'tcx>, |
74b04a01 XL |
843 | ) -> Option<bool> { |
844 | self.inner | |
845 | .borrow_mut() | |
846 | .unwrap_region_constraints() | |
f9f354fc | 847 | .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) |
74b04a01 XL |
848 | } |
849 | ||
2b03887a | 850 | pub fn opaque_types_added_in_snapshot(&self, snapshot: &CombinedSnapshot<'tcx>) -> bool { |
04454e1e FG |
851 | self.inner.borrow().undo_log.opaque_types_in_snapshot(&snapshot.undo_snapshot) |
852 | } | |
853 | ||
9ffffee4 | 854 | pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> bool |
74b04a01 XL |
855 | where |
856 | T: at::ToTrace<'tcx>, | |
857 | { | |
858 | let origin = &ObligationCause::dummy(); | |
353b0b11 | 859 | self.probe(|_| self.at(origin, param_env).sub(DefineOpaqueTypes::No, a, b).is_ok()) |
74b04a01 XL |
860 | } |
861 | ||
9ffffee4 | 862 | pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> bool |
74b04a01 XL |
863 | where |
864 | T: at::ToTrace<'tcx>, | |
865 | { | |
866 | let origin = &ObligationCause::dummy(); | |
353b0b11 | 867 | self.probe(|_| self.at(origin, param_env).eq(DefineOpaqueTypes::No, a, b).is_ok()) |
74b04a01 XL |
868 | } |
869 | ||
c295e0f8 | 870 | #[instrument(skip(self), level = "debug")] |
74b04a01 XL |
871 | pub fn sub_regions( |
872 | &self, | |
873 | origin: SubregionOrigin<'tcx>, | |
874 | a: ty::Region<'tcx>, | |
875 | b: ty::Region<'tcx>, | |
876 | ) { | |
74b04a01 XL |
877 | self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b); |
878 | } | |
879 | ||
880 | /// Require that the region `r` be equal to one of the regions in | |
881 | /// the set `regions`. | |
c295e0f8 | 882 | #[instrument(skip(self), level = "debug")] |
74b04a01 XL |
883 | pub fn member_constraint( |
884 | &self, | |
064997fb | 885 | key: ty::OpaqueTypeKey<'tcx>, |
74b04a01 XL |
886 | definition_span: Span, |
887 | hidden_ty: Ty<'tcx>, | |
888 | region: ty::Region<'tcx>, | |
889 | in_regions: &Lrc<Vec<ty::Region<'tcx>>>, | |
890 | ) { | |
74b04a01 | 891 | self.inner.borrow_mut().unwrap_region_constraints().member_constraint( |
064997fb | 892 | key, |
74b04a01 XL |
893 | definition_span, |
894 | hidden_ty, | |
895 | region, | |
896 | in_regions, | |
897 | ); | |
898 | } | |
899 | ||
94222f64 XL |
900 | /// Processes a `Coerce` predicate from the fulfillment context. |
901 | /// This is NOT the preferred way to handle coercion, which is to | |
902 | /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`). | |
903 | /// | |
904 | /// This method here is actually a fallback that winds up being | |
905 | /// invoked when `FnCtxt::coerce` encounters unresolved type variables | |
906 | /// and records a coercion predicate. Presently, this method is equivalent | |
907 | /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up | |
908 | /// actually requiring `a <: b`. This is of course a valid coercion, | |
909 | /// but it's not as flexible as `FnCtxt::coerce` would be. | |
910 | /// | |
911 | /// (We may refactor this in the future, but there are a number of | |
912 | /// practical obstacles. Among other things, `FnCtxt::coerce` presently | |
913 | /// records adjustments that are required on the HIR in order to perform | |
914 | /// the coercion, and we don't currently have a way to manage that.) | |
915 | pub fn coerce_predicate( | |
916 | &self, | |
917 | cause: &ObligationCause<'tcx>, | |
918 | param_env: ty::ParamEnv<'tcx>, | |
919 | predicate: ty::PolyCoercePredicate<'tcx>, | |
f2b60f7d | 920 | ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> { |
94222f64 XL |
921 | let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate { |
922 | a_is_expected: false, // when coercing from `a` to `b`, `b` is expected | |
923 | a: p.a, | |
924 | b: p.b, | |
925 | }); | |
926 | self.subtype_predicate(cause, param_env, subtype_predicate) | |
927 | } | |
928 | ||
74b04a01 XL |
929 | pub fn subtype_predicate( |
930 | &self, | |
931 | cause: &ObligationCause<'tcx>, | |
932 | param_env: ty::ParamEnv<'tcx>, | |
f9f354fc | 933 | predicate: ty::PolySubtypePredicate<'tcx>, |
f2b60f7d | 934 | ) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> { |
94222f64 XL |
935 | // Check for two unresolved inference variables, in which case we can |
936 | // make no progress. This is partly a micro-optimization, but it's | |
937 | // also an opportunity to "sub-unify" the variables. This isn't | |
938 | // *necessary* to prevent cycles, because they would eventually be sub-unified | |
939 | // anyhow during generalization, but it helps with diagnostics (we can detect | |
940 | // earlier that they are sub-unified). | |
941 | // | |
942 | // Note that we can just skip the binders here because | |
943 | // type variables can't (at present, at | |
74b04a01 XL |
944 | // least) capture any of the things bound by this binder. |
945 | // | |
94222f64 XL |
946 | // Note that this sub here is not just for diagnostics - it has semantic |
947 | // effects as well. | |
948 | let r_a = self.shallow_resolve(predicate.skip_binder().a); | |
949 | let r_b = self.shallow_resolve(predicate.skip_binder().b); | |
950 | match (r_a.kind(), r_b.kind()) { | |
951 | (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => { | |
952 | self.inner.borrow_mut().type_variables().sub(a_vid, b_vid); | |
f2b60f7d | 953 | return Err((a_vid, b_vid)); |
94222f64 XL |
954 | } |
955 | _ => {} | |
74b04a01 XL |
956 | } |
957 | ||
f2b60f7d | 958 | Ok(self.commit_if_ok(|_snapshot| { |
29967ef6 | 959 | let ty::SubtypePredicate { a_is_expected, a, b } = |
9ffffee4 | 960 | self.instantiate_binder_with_placeholders(predicate); |
74b04a01 | 961 | |
353b0b11 FG |
962 | let ok = |
963 | self.at(cause, param_env).sub_exp(DefineOpaqueTypes::No, a_is_expected, a, b)?; | |
74b04a01 | 964 | |
74b04a01 XL |
965 | Ok(ok.unit()) |
966 | })) | |
967 | } | |
968 | ||
969 | pub fn region_outlives_predicate( | |
970 | &self, | |
971 | cause: &traits::ObligationCause<'tcx>, | |
f9f354fc | 972 | predicate: ty::PolyRegionOutlivesPredicate<'tcx>, |
064997fb | 973 | ) { |
9ffffee4 | 974 | let ty::OutlivesPredicate(r_a, r_b) = self.instantiate_binder_with_placeholders(predicate); |
064997fb FG |
975 | let origin = |
976 | SubregionOrigin::from_obligation_cause(cause, || RelateRegionParamBound(cause.span)); | |
977 | self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` | |
74b04a01 XL |
978 | } |
979 | ||
c295e0f8 XL |
980 | /// Number of type variables created so far. |
981 | pub fn num_ty_vars(&self) -> usize { | |
982 | self.inner.borrow_mut().type_variables().num_vars() | |
983 | } | |
984 | ||
985 | pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { | |
986 | self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) | |
74b04a01 XL |
987 | } |
988 | ||
989 | pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { | |
c295e0f8 | 990 | self.tcx.mk_ty_var(self.next_ty_var_id(origin)) |
74b04a01 XL |
991 | } |
992 | ||
5e7ed085 FG |
993 | pub fn next_ty_var_id_in_universe( |
994 | &self, | |
995 | origin: TypeVariableOrigin, | |
996 | universe: ty::UniverseIndex, | |
997 | ) -> TyVid { | |
998 | self.inner.borrow_mut().type_variables().new_var(universe, origin) | |
999 | } | |
1000 | ||
74b04a01 XL |
1001 | pub fn next_ty_var_in_universe( |
1002 | &self, | |
1003 | origin: TypeVariableOrigin, | |
1004 | universe: ty::UniverseIndex, | |
1005 | ) -> Ty<'tcx> { | |
5e7ed085 | 1006 | let vid = self.next_ty_var_id_in_universe(origin, universe); |
74b04a01 XL |
1007 | self.tcx.mk_ty_var(vid) |
1008 | } | |
1009 | ||
5099ac24 | 1010 | pub fn next_const_var(&self, ty: Ty<'tcx>, origin: ConstVariableOrigin) -> ty::Const<'tcx> { |
487cf647 | 1011 | self.tcx.mk_const(self.next_const_var_id(origin), ty) |
74b04a01 XL |
1012 | } |
1013 | ||
1014 | pub fn next_const_var_in_universe( | |
1015 | &self, | |
1016 | ty: Ty<'tcx>, | |
1017 | origin: ConstVariableOrigin, | |
1018 | universe: ty::UniverseIndex, | |
5099ac24 | 1019 | ) -> ty::Const<'tcx> { |
74b04a01 XL |
1020 | let vid = self |
1021 | .inner | |
1022 | .borrow_mut() | |
f9f354fc | 1023 | .const_unification_table() |
74b04a01 | 1024 | .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } }); |
487cf647 | 1025 | self.tcx.mk_const(vid, ty) |
74b04a01 XL |
1026 | } |
1027 | ||
1028 | pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> { | |
f9f354fc | 1029 | self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { |
74b04a01 XL |
1030 | origin, |
1031 | val: ConstVariableValue::Unknown { universe: self.universe() }, | |
1032 | }) | |
1033 | } | |
1034 | ||
1035 | fn next_int_var_id(&self) -> IntVid { | |
f9f354fc | 1036 | self.inner.borrow_mut().int_unification_table().new_key(None) |
74b04a01 XL |
1037 | } |
1038 | ||
1039 | pub fn next_int_var(&self) -> Ty<'tcx> { | |
1040 | self.tcx.mk_int_var(self.next_int_var_id()) | |
1041 | } | |
1042 | ||
1043 | fn next_float_var_id(&self) -> FloatVid { | |
f9f354fc | 1044 | self.inner.borrow_mut().float_unification_table().new_key(None) |
74b04a01 XL |
1045 | } |
1046 | ||
1047 | pub fn next_float_var(&self) -> Ty<'tcx> { | |
1048 | self.tcx.mk_float_var(self.next_float_var_id()) | |
1049 | } | |
1050 | ||
1051 | /// Creates a fresh region variable with the next available index. | |
1052 | /// The variable will be created in the maximum universe created | |
1053 | /// thus far, allowing it to name any region created thus far. | |
1054 | pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { | |
1055 | self.next_region_var_in_universe(origin, self.universe()) | |
1056 | } | |
1057 | ||
1058 | /// Creates a fresh region variable with the next available index | |
1059 | /// in the given universe; typically, you can use | |
1060 | /// `next_region_var` and just use the maximal universe. | |
1061 | pub fn next_region_var_in_universe( | |
1062 | &self, | |
1063 | origin: RegionVariableOrigin, | |
1064 | universe: ty::UniverseIndex, | |
1065 | ) -> ty::Region<'tcx> { | |
1066 | let region_var = | |
1067 | self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); | |
9ffffee4 | 1068 | self.tcx.mk_re_var(region_var) |
74b04a01 XL |
1069 | } |
1070 | ||
9c376795 | 1071 | /// Return the universe that the region `r` was created in. For |
74b04a01 XL |
1072 | /// most regions (e.g., `'static`, named regions from the user, |
1073 | /// etc) this is the root universe U0. For inference variables or | |
2b03887a FG |
1074 | /// placeholders, however, it will return the universe which they |
1075 | /// are associated. | |
94222f64 | 1076 | pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { |
74b04a01 XL |
1077 | self.inner.borrow_mut().unwrap_region_constraints().universe(r) |
1078 | } | |
1079 | ||
1080 | /// Number of region variables created so far. | |
1081 | pub fn num_region_vars(&self) -> usize { | |
1082 | self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() | |
1083 | } | |
1084 | ||
1085 | /// Just a convenient wrapper of `next_region_var` for using during NLL. | |
9ffffee4 | 1086 | #[instrument(skip(self), level = "debug")] |
5869c6ff XL |
1087 | pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { |
1088 | self.next_region_var(RegionVariableOrigin::Nll(origin)) | |
74b04a01 XL |
1089 | } |
1090 | ||
1091 | /// Just a convenient wrapper of `next_region_var` for using during NLL. | |
9ffffee4 | 1092 | #[instrument(skip(self), level = "debug")] |
74b04a01 XL |
1093 | pub fn next_nll_region_var_in_universe( |
1094 | &self, | |
5869c6ff | 1095 | origin: NllRegionVariableOrigin, |
74b04a01 XL |
1096 | universe: ty::UniverseIndex, |
1097 | ) -> ty::Region<'tcx> { | |
5869c6ff | 1098 | self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) |
74b04a01 XL |
1099 | } |
1100 | ||
1101 | pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { | |
1102 | match param.kind { | |
1103 | GenericParamDefKind::Lifetime => { | |
1104 | // Create a region inference variable for the given | |
1105 | // region parameter definition. | |
1106 | self.next_region_var(EarlyBoundRegion(span, param.name)).into() | |
1107 | } | |
1108 | GenericParamDefKind::Type { .. } => { | |
1109 | // Create a type inference variable for the given | |
1110 | // type parameter definition. The substitutions are | |
1111 | // for actual parameters that may be referred to by | |
1112 | // the default of this type parameter, if it exists. | |
1113 | // e.g., `struct Foo<A, B, C = (A, B)>(...);` when | |
1114 | // used in a path such as `Foo::<T, U>::new()` will | |
1115 | // use an inference variable for `C` with `[T, U]` | |
1116 | // as the substitutions for the default, `(T, U)`. | |
f9f354fc | 1117 | let ty_var_id = self.inner.borrow_mut().type_variables().new_var( |
74b04a01 | 1118 | self.universe(), |
74b04a01 XL |
1119 | TypeVariableOrigin { |
1120 | kind: TypeVariableOriginKind::TypeParameterDefinition( | |
1121 | param.name, | |
1122 | Some(param.def_id), | |
1123 | ), | |
1124 | span, | |
1125 | }, | |
1126 | ); | |
1127 | ||
1128 | self.tcx.mk_ty_var(ty_var_id).into() | |
1129 | } | |
1130 | GenericParamDefKind::Const { .. } => { | |
1131 | let origin = ConstVariableOrigin { | |
1b1a35ee XL |
1132 | kind: ConstVariableOriginKind::ConstParameterDefinition( |
1133 | param.name, | |
1134 | param.def_id, | |
1135 | ), | |
74b04a01 XL |
1136 | span, |
1137 | }; | |
1138 | let const_var_id = | |
f9f354fc | 1139 | self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { |
74b04a01 XL |
1140 | origin, |
1141 | val: ConstVariableValue::Unknown { universe: self.universe() }, | |
1142 | }); | |
9ffffee4 FG |
1143 | self.tcx |
1144 | .mk_const( | |
1145 | const_var_id, | |
1146 | self.tcx | |
1147 | .type_of(param.def_id) | |
1148 | .no_bound_vars() | |
1149 | .expect("const parameter types cannot be generic"), | |
1150 | ) | |
1151 | .into() | |
74b04a01 XL |
1152 | } |
1153 | } | |
1154 | } | |
1155 | ||
1156 | /// Given a set of generics defined on a type or impl, returns a substitution mapping each | |
1157 | /// type/region parameter to a fresh inference variable. | |
1158 | pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { | |
1159 | InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) | |
1160 | } | |
1161 | ||
1162 | /// Returns `true` if errors have been reported since this infcx was | |
1163 | /// created. This is sometimes used as a heuristic to skip | |
1164 | /// reporting errors that often occur as a result of earlier | |
1165 | /// errors, but where it's hard to be 100% sure (e.g., unresolved | |
1166 | /// inference variables, regionck errors). | |
487cf647 FG |
1167 | #[must_use = "this method does not have any side effects"] |
1168 | pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> { | |
74b04a01 XL |
1169 | debug!( |
1170 | "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \ | |
f2b60f7d | 1171 | tainted_by_errors={})", |
74b04a01 XL |
1172 | self.tcx.sess.err_count(), |
1173 | self.err_count_on_creation, | |
f2b60f7d | 1174 | self.tainted_by_errors.get().is_some() |
74b04a01 XL |
1175 | ); |
1176 | ||
487cf647 FG |
1177 | if let Some(e) = self.tainted_by_errors.get() { |
1178 | return Some(e); | |
1179 | } | |
1180 | ||
74b04a01 | 1181 | if self.tcx.sess.err_count() > self.err_count_on_creation { |
487cf647 FG |
1182 | // errors reported since this infcx was made |
1183 | let e = self.tcx.sess.has_errors().unwrap(); | |
1184 | self.set_tainted_by_errors(e); | |
1185 | return Some(e); | |
74b04a01 | 1186 | } |
487cf647 FG |
1187 | |
1188 | None | |
74b04a01 XL |
1189 | } |
1190 | ||
1191 | /// Set the "tainted by errors" flag to true. We call this when we | |
1192 | /// observe an error from a prior pass. | |
487cf647 FG |
1193 | pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) { |
1194 | debug!("set_tainted_by_errors(ErrorGuaranteed)"); | |
1195 | self.tainted_by_errors.set(Some(e)); | |
74b04a01 XL |
1196 | } |
1197 | ||
94222f64 XL |
1198 | pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin { |
1199 | let mut inner = self.inner.borrow_mut(); | |
1200 | let inner = &mut *inner; | |
1201 | inner | |
1202 | .region_constraint_storage | |
1203 | .as_mut() | |
1204 | .expect("regions already resolved") | |
1205 | .with_log(&mut inner.undo_log) | |
1206 | .var_origin(vid) | |
1207 | } | |
1208 | ||
74b04a01 XL |
1209 | /// Takes ownership of the list of variable regions. This implies |
1210 | /// that all the region constraints have already been taken, and | |
1211 | /// hence that `resolve_regions_and_report_errors` can never be | |
1212 | /// called. This is used only during NLL processing to "hand off" ownership | |
1213 | /// of the set of region variables into the NLL region context. | |
49aad941 | 1214 | pub fn get_region_var_origins(&self) -> VarInfos { |
f9f354fc XL |
1215 | let mut inner = self.inner.borrow_mut(); |
1216 | let (var_infos, data) = inner | |
1217 | .region_constraint_storage | |
49aad941 | 1218 | .clone() |
74b04a01 | 1219 | .expect("regions already resolved") |
f9f354fc | 1220 | .with_log(&mut inner.undo_log) |
74b04a01 XL |
1221 | .into_infos_and_data(); |
1222 | assert!(data.is_empty()); | |
1223 | var_infos | |
1224 | } | |
1225 | ||
9c376795 FG |
1226 | #[instrument(level = "debug", skip(self), ret)] |
1227 | pub fn take_opaque_types(&self) -> opaque_types::OpaqueTypeMap<'tcx> { | |
1228 | debug_assert_ne!(self.defining_use_anchor, DefiningAnchor::Error); | |
1229 | std::mem::take(&mut self.inner.borrow_mut().opaque_type_storage.opaque_types) | |
1230 | } | |
1231 | ||
74b04a01 | 1232 | pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { |
fc512014 | 1233 | self.resolve_vars_if_possible(t).to_string() |
74b04a01 XL |
1234 | } |
1235 | ||
74b04a01 XL |
1236 | /// If `TyVar(vid)` resolves to a type, return that type. Else, return the |
1237 | /// universe index of `TyVar(vid)`. | |
1238 | pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> { | |
1239 | use self::type_variable::TypeVariableValue; | |
1240 | ||
f9f354fc | 1241 | match self.inner.borrow_mut().type_variables().probe(vid) { |
74b04a01 XL |
1242 | TypeVariableValue::Known { value } => Ok(value), |
1243 | TypeVariableValue::Unknown { universe } => Err(universe), | |
1244 | } | |
1245 | } | |
1246 | ||
1247 | /// Resolve any type variables found in `value` -- but only one | |
9c376795 | 1248 | /// level. So, if the variable `?X` is bound to some type |
74b04a01 XL |
1249 | /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may |
1250 | /// itself be bound to a type). | |
1251 | /// | |
1252 | /// Useful when you only need to inspect the outermost level of | |
1253 | /// the type and don't care about nested types (or perhaps you | |
1254 | /// will be resolving them as well, e.g. in a loop). | |
1255 | pub fn shallow_resolve<T>(&self, value: T) -> T | |
1256 | where | |
9ffffee4 | 1257 | T: TypeFoldable<TyCtxt<'tcx>>, |
74b04a01 | 1258 | { |
ba9703b0 | 1259 | value.fold_with(&mut ShallowResolver { infcx: self }) |
74b04a01 XL |
1260 | } |
1261 | ||
1262 | pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { | |
f9f354fc | 1263 | self.inner.borrow_mut().type_variables().root_var(var) |
74b04a01 XL |
1264 | } |
1265 | ||
353b0b11 FG |
1266 | pub fn root_const_var(&self, var: ty::ConstVid<'tcx>) -> ty::ConstVid<'tcx> { |
1267 | self.inner.borrow_mut().const_unification_table().find(var) | |
1268 | } | |
1269 | ||
1270 | /// Resolves an int var to a rigid int type, if it was constrained to one, | |
1271 | /// or else the root int var in the unification table. | |
1272 | pub fn opportunistic_resolve_int_var(&self, vid: ty::IntVid) -> Ty<'tcx> { | |
1273 | let mut inner = self.inner.borrow_mut(); | |
1274 | if let Some(value) = inner.int_unification_table().probe_value(vid) { | |
1275 | value.to_type(self.tcx) | |
1276 | } else { | |
1277 | self.tcx.mk_int_var(inner.int_unification_table().find(vid)) | |
1278 | } | |
1279 | } | |
1280 | ||
1281 | /// Resolves a float var to a rigid int type, if it was constrained to one, | |
1282 | /// or else the root float var in the unification table. | |
1283 | pub fn opportunistic_resolve_float_var(&self, vid: ty::FloatVid) -> Ty<'tcx> { | |
1284 | let mut inner = self.inner.borrow_mut(); | |
1285 | if let Some(value) = inner.float_unification_table().probe_value(vid) { | |
1286 | value.to_type(self.tcx) | |
1287 | } else { | |
1288 | self.tcx.mk_float_var(inner.float_unification_table().find(vid)) | |
1289 | } | |
1290 | } | |
1291 | ||
74b04a01 XL |
1292 | /// Where possible, replaces type/const variables in |
1293 | /// `value` with their final value. Note that region variables | |
1294 | /// are unaffected. If a type/const variable has not been unified, it | |
1295 | /// is left as is. This is an idempotent operation that does | |
1296 | /// not affect inference state in any way and so you can do it | |
1297 | /// at will. | |
fc512014 | 1298 | pub fn resolve_vars_if_possible<T>(&self, value: T) -> T |
74b04a01 | 1299 | where |
9ffffee4 | 1300 | T: TypeFoldable<TyCtxt<'tcx>>, |
74b04a01 | 1301 | { |
9ffffee4 FG |
1302 | if !value.has_non_region_infer() { |
1303 | return value; | |
74b04a01 XL |
1304 | } |
1305 | let mut r = resolve::OpportunisticVarResolver::new(self); | |
1306 | value.fold_with(&mut r) | |
1307 | } | |
1308 | ||
5e7ed085 FG |
1309 | pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T |
1310 | where | |
9ffffee4 | 1311 | T: TypeFoldable<TyCtxt<'tcx>>, |
5e7ed085 | 1312 | { |
49aad941 | 1313 | if !value.has_infer() { |
5e7ed085 FG |
1314 | return value; // Avoid duplicated subst-folding. |
1315 | } | |
1316 | let mut r = InferenceLiteralEraser { tcx: self.tcx }; | |
1317 | value.fold_with(&mut r) | |
1318 | } | |
1319 | ||
487cf647 FG |
1320 | /// Returns the first unresolved type or const variable contained in `T`. |
1321 | pub fn first_unresolved_const_or_ty_var<T>( | |
1322 | &self, | |
1323 | value: &T, | |
1324 | ) -> Option<(ty::Term<'tcx>, Option<Span>)> | |
74b04a01 | 1325 | where |
9ffffee4 | 1326 | T: TypeVisitable<TyCtxt<'tcx>>, |
74b04a01 | 1327 | { |
487cf647 | 1328 | value.visit_with(&mut resolve::UnresolvedTypeOrConstFinder::new(self)).break_value() |
74b04a01 XL |
1329 | } |
1330 | ||
1331 | pub fn probe_const_var( | |
1332 | &self, | |
1333 | vid: ty::ConstVid<'tcx>, | |
5099ac24 | 1334 | ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> { |
f9f354fc | 1335 | match self.inner.borrow_mut().const_unification_table().probe_value(vid).val { |
74b04a01 XL |
1336 | ConstVariableValue::Known { value } => Ok(value), |
1337 | ConstVariableValue::Unknown { universe } => Err(universe), | |
1338 | } | |
1339 | } | |
1340 | ||
9ffffee4 FG |
1341 | /// Attempts to resolve all type/region/const variables in |
1342 | /// `value`. Region inference must have been run already (e.g., | |
1343 | /// by calling `resolve_regions_and_report_errors`). If some | |
1344 | /// variable was never unified, an `Err` results. | |
1345 | /// | |
1346 | /// This method is idempotent, but it not typically not invoked | |
1347 | /// except during the writeback phase. | |
1348 | pub fn fully_resolve<T: TypeFoldable<TyCtxt<'tcx>>>(&self, value: T) -> FixupResult<'tcx, T> { | |
2b03887a FG |
1349 | let value = resolve::fully_resolve(self, value); |
1350 | assert!( | |
49aad941 | 1351 | value.as_ref().map_or(true, |value| !value.has_infer()), |
2b03887a FG |
1352 | "`{value:?}` is not fully resolved" |
1353 | ); | |
1354 | value | |
f9f354fc XL |
1355 | } |
1356 | ||
9ffffee4 FG |
1357 | // Instantiates the bound variables in a given binder with fresh inference |
1358 | // variables in the current universe. | |
1359 | // | |
1360 | // Use this method if you'd like to find some substitution of the binder's | |
1361 | // variables (e.g. during a method call). If there isn't a [`LateBoundRegionConversionTime`] | |
1362 | // that corresponds to your use case, consider whether or not you should | |
1363 | // use [`InferCtxt::instantiate_binder_with_placeholders`] instead. | |
1364 | pub fn instantiate_binder_with_fresh_vars<T>( | |
74b04a01 XL |
1365 | &self, |
1366 | span: Span, | |
1367 | lbrct: LateBoundRegionConversionTime, | |
cdc7bbd5 | 1368 | value: ty::Binder<'tcx, T>, |
923072b8 | 1369 | ) -> T |
74b04a01 | 1370 | where |
9ffffee4 | 1371 | T: TypeFoldable<TyCtxt<'tcx>> + Copy, |
74b04a01 | 1372 | { |
923072b8 FG |
1373 | if let Some(inner) = value.no_bound_vars() { |
1374 | return inner; | |
1375 | } | |
1376 | ||
064997fb | 1377 | struct ToFreshVars<'a, 'tcx> { |
2b03887a | 1378 | infcx: &'a InferCtxt<'tcx>, |
064997fb FG |
1379 | span: Span, |
1380 | lbrct: LateBoundRegionConversionTime, | |
1381 | map: FxHashMap<ty::BoundVar, ty::GenericArg<'tcx>>, | |
1382 | } | |
923072b8 | 1383 | |
064997fb FG |
1384 | impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'_, 'tcx> { |
1385 | fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> { | |
1386 | self.map | |
1387 | .entry(br.var) | |
1388 | .or_insert_with(|| { | |
1389 | self.infcx | |
1390 | .next_region_var(LateBoundRegion(self.span, br.kind, self.lbrct)) | |
1391 | .into() | |
1392 | }) | |
1393 | .expect_region() | |
1394 | } | |
1395 | fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> { | |
1396 | self.map | |
1397 | .entry(bt.var) | |
1398 | .or_insert_with(|| { | |
1399 | self.infcx | |
1400 | .next_ty_var(TypeVariableOrigin { | |
1401 | kind: TypeVariableOriginKind::MiscVariable, | |
1402 | span: self.span, | |
1403 | }) | |
1404 | .into() | |
1405 | }) | |
1406 | .expect_ty() | |
1407 | } | |
1408 | fn replace_const(&mut self, bv: ty::BoundVar, ty: Ty<'tcx>) -> ty::Const<'tcx> { | |
1409 | self.map | |
1410 | .entry(bv) | |
1411 | .or_insert_with(|| { | |
1412 | self.infcx | |
1413 | .next_const_var( | |
1414 | ty, | |
1415 | ConstVariableOrigin { | |
1416 | kind: ConstVariableOriginKind::MiscVariable, | |
1417 | span: self.span, | |
1418 | }, | |
1419 | ) | |
1420 | .into() | |
1421 | }) | |
1422 | .expect_const() | |
1423 | } | |
1424 | } | |
1425 | let delegate = ToFreshVars { infcx: self, span, lbrct, map: Default::default() }; | |
1426 | self.tcx.replace_bound_vars_uncached(value, delegate) | |
74b04a01 XL |
1427 | } |
1428 | ||
f9f354fc | 1429 | /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. |
74b04a01 XL |
1430 | pub fn verify_generic_bound( |
1431 | &self, | |
1432 | origin: SubregionOrigin<'tcx>, | |
1433 | kind: GenericKind<'tcx>, | |
1434 | a: ty::Region<'tcx>, | |
1435 | bound: VerifyBound<'tcx>, | |
1436 | ) { | |
1437 | debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound); | |
1438 | ||
1439 | self.inner | |
1440 | .borrow_mut() | |
1441 | .unwrap_region_constraints() | |
1442 | .verify_generic_bound(origin, kind, a, bound); | |
1443 | } | |
1444 | ||
74b04a01 XL |
1445 | /// Obtains the latest type of the given closure; this may be a |
1446 | /// closure in the current function, in which case its | |
1447 | /// `ClosureKind` may not yet be known. | |
ba9703b0 XL |
1448 | pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> { |
1449 | let closure_kind_ty = closure_substs.as_closure().kind_ty(); | |
74b04a01 XL |
1450 | let closure_kind_ty = self.shallow_resolve(closure_kind_ty); |
1451 | closure_kind_ty.to_opt_closure_kind() | |
1452 | } | |
1453 | ||
74b04a01 XL |
1454 | /// Clears the selection, evaluation, and projection caches. This is useful when |
1455 | /// repeatedly attempting to select an `Obligation` while changing only | |
1456 | /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing. | |
1457 | pub fn clear_caches(&self) { | |
1458 | self.selection_cache.clear(); | |
1459 | self.evaluation_cache.clear(); | |
f9f354fc | 1460 | self.inner.borrow_mut().projection_cache().clear(); |
74b04a01 XL |
1461 | } |
1462 | ||
94222f64 | 1463 | pub fn universe(&self) -> ty::UniverseIndex { |
74b04a01 XL |
1464 | self.universe.get() |
1465 | } | |
1466 | ||
1467 | /// Creates and return a fresh universe that extends all previous | |
1468 | /// universes. Updates `self.universe` to that new universe. | |
1469 | pub fn create_next_universe(&self) -> ty::UniverseIndex { | |
1470 | let u = self.universe.get().next_universe(); | |
1471 | self.universe.set(u); | |
1472 | u | |
1473 | } | |
1474 | ||
923072b8 FG |
1475 | pub fn try_const_eval_resolve( |
1476 | &self, | |
1477 | param_env: ty::ParamEnv<'tcx>, | |
2b03887a | 1478 | unevaluated: ty::UnevaluatedConst<'tcx>, |
923072b8 FG |
1479 | ty: Ty<'tcx>, |
1480 | span: Option<Span>, | |
1481 | ) -> Result<ty::Const<'tcx>, ErrorHandled> { | |
1482 | match self.const_eval_resolve(param_env, unevaluated, span) { | |
487cf647 | 1483 | Ok(Some(val)) => Ok(self.tcx.mk_const(val, ty)), |
923072b8 FG |
1484 | Ok(None) => { |
1485 | let tcx = self.tcx; | |
49aad941 | 1486 | let def_id = unevaluated.def; |
923072b8 FG |
1487 | span_bug!( |
1488 | tcx.def_span(def_id), | |
1489 | "unable to construct a constant value for the unevaluated constant {:?}", | |
1490 | unevaluated | |
1491 | ); | |
1492 | } | |
1493 | Err(err) => Err(err), | |
1494 | } | |
1495 | } | |
1496 | ||
74b04a01 XL |
1497 | /// Resolves and evaluates a constant. |
1498 | /// | |
1499 | /// The constant can be located on a trait like `<A as B>::C`, in which case the given | |
1500 | /// substitutions and environment are used to resolve the constant. Alternatively if the | |
1501 | /// constant has generic parameters in scope the substitutions are used to evaluate the value of | |
1502 | /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count | |
1503 | /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still | |
1504 | /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is | |
1505 | /// returned. | |
1506 | /// | |
1507 | /// This handles inferences variables within both `param_env` and `substs` by | |
1508 | /// performing the operation on their respective canonical forms. | |
5e7ed085 | 1509 | #[instrument(skip(self), level = "debug")] |
74b04a01 XL |
1510 | pub fn const_eval_resolve( |
1511 | &self, | |
064997fb | 1512 | mut param_env: ty::ParamEnv<'tcx>, |
2b03887a | 1513 | unevaluated: ty::UnevaluatedConst<'tcx>, |
74b04a01 | 1514 | span: Option<Span>, |
923072b8 | 1515 | ) -> EvalToValTreeResult<'tcx> { |
064997fb | 1516 | let mut substs = self.resolve_vars_if_possible(unevaluated.substs); |
5e7ed085 | 1517 | debug!(?substs); |
a2a8927a XL |
1518 | |
1519 | // Postpone the evaluation of constants whose substs depend on inference | |
1520 | // variables | |
487cf647 | 1521 | let tcx = self.tcx; |
2b03887a | 1522 | if substs.has_non_region_infer() { |
49aad941 | 1523 | if let Some(ct) = tcx.thir_abstract_const(unevaluated.def)? { |
487cf647 FG |
1524 | let ct = tcx.expand_abstract_consts(ct.subst(tcx, substs)); |
1525 | if let Err(e) = ct.error_reported() { | |
49aad941 | 1526 | return Err(ErrorHandled::Reported(e.into())); |
487cf647 FG |
1527 | } else if ct.has_non_region_infer() || ct.has_non_region_param() { |
1528 | return Err(ErrorHandled::TooGeneric); | |
1529 | } else { | |
1530 | substs = replace_param_and_infer_substs_with_placeholder(tcx, substs); | |
064997fb | 1531 | } |
487cf647 | 1532 | } else { |
49aad941 FG |
1533 | substs = InternalSubsts::identity_for_item(tcx, unevaluated.def); |
1534 | param_env = tcx.param_env(unevaluated.def); | |
064997fb | 1535 | } |
a2a8927a XL |
1536 | } |
1537 | ||
487cf647 FG |
1538 | let param_env_erased = tcx.erase_regions(param_env); |
1539 | let substs_erased = tcx.erase_regions(substs); | |
5e7ed085 FG |
1540 | debug!(?param_env_erased); |
1541 | debug!(?substs_erased); | |
a2a8927a | 1542 | |
2b03887a | 1543 | let unevaluated = ty::UnevaluatedConst { def: unevaluated.def, substs: substs_erased }; |
74b04a01 | 1544 | |
74b04a01 XL |
1545 | // The return value is the evaluated value which doesn't contain any reference to inference |
1546 | // variables, thus we don't need to substitute back the original values. | |
487cf647 | 1547 | tcx.const_eval_resolve_for_typeck(param_env_erased, unevaluated, span) |
74b04a01 | 1548 | } |
74b04a01 | 1549 | |
353b0b11 FG |
1550 | /// The returned function is used in a fast path. If it returns `true` the variable is |
1551 | /// unchanged, `false` indicates that the status is unknown. | |
1552 | #[inline] | |
1553 | pub fn is_ty_infer_var_definitely_unchanged<'a>( | |
1554 | &'a self, | |
1555 | ) -> (impl Fn(TyOrConstInferVar<'tcx>) -> bool + 'a) { | |
1556 | // This hoists the borrow/release out of the loop body. | |
1557 | let inner = self.inner.try_borrow(); | |
1558 | ||
1559 | return move |infer_var: TyOrConstInferVar<'tcx>| match (infer_var, &inner) { | |
1560 | (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => { | |
1561 | use self::type_variable::TypeVariableValue; | |
1562 | ||
49aad941 FG |
1563 | matches!( |
1564 | inner.try_type_variables_probe_ref(ty_var), | |
1565 | Some(TypeVariableValue::Unknown { .. }) | |
1566 | ) | |
353b0b11 FG |
1567 | } |
1568 | _ => false, | |
1569 | }; | |
1570 | } | |
1571 | ||
ba9703b0 XL |
1572 | /// `ty_or_const_infer_var_changed` is equivalent to one of these two: |
1573 | /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`) | |
1574 | /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`) | |
1575 | /// | |
1576 | /// However, `ty_or_const_infer_var_changed` is more efficient. It's always | |
1577 | /// inlined, despite being large, because it has only two call sites that | |
1578 | /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on` | |
1579 | /// inference variables), and it handles both `Ty` and `ty::Const` without | |
1580 | /// having to resort to storing full `GenericArg`s in `stalled_on`. | |
74b04a01 | 1581 | #[inline(always)] |
ba9703b0 XL |
1582 | pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool { |
1583 | match infer_var { | |
1584 | TyOrConstInferVar::Ty(v) => { | |
74b04a01 XL |
1585 | use self::type_variable::TypeVariableValue; |
1586 | ||
ba9703b0 XL |
1587 | // If `inlined_probe` returns a `Known` value, it never equals |
1588 | // `ty::Infer(ty::TyVar(v))`. | |
f9f354fc | 1589 | match self.inner.borrow_mut().type_variables().inlined_probe(v) { |
74b04a01 XL |
1590 | TypeVariableValue::Unknown { .. } => false, |
1591 | TypeVariableValue::Known { .. } => true, | |
1592 | } | |
1593 | } | |
1594 | ||
ba9703b0 XL |
1595 | TyOrConstInferVar::TyInt(v) => { |
1596 | // If `inlined_probe_value` returns a value it's always a | |
74b04a01 XL |
1597 | // `ty::Int(_)` or `ty::UInt(_)`, which never matches a |
1598 | // `ty::Infer(_)`. | |
f9f354fc | 1599 | self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some() |
74b04a01 XL |
1600 | } |
1601 | ||
ba9703b0 XL |
1602 | TyOrConstInferVar::TyFloat(v) => { |
1603 | // If `probe_value` returns a value it's always a | |
74b04a01 XL |
1604 | // `ty::Float(_)`, which never matches a `ty::Infer(_)`. |
1605 | // | |
1606 | // Not `inlined_probe_value(v)` because this call site is colder. | |
f9f354fc | 1607 | self.inner.borrow_mut().float_unification_table().probe_value(v).is_some() |
74b04a01 XL |
1608 | } |
1609 | ||
ba9703b0 XL |
1610 | TyOrConstInferVar::Const(v) => { |
1611 | // If `probe_value` returns a `Known` value, it never equals | |
1612 | // `ty::ConstKind::Infer(ty::InferConst::Var(v))`. | |
1613 | // | |
1614 | // Not `inlined_probe_value(v)` because this call site is colder. | |
f9f354fc | 1615 | match self.inner.borrow_mut().const_unification_table().probe_value(v).val { |
ba9703b0 XL |
1616 | ConstVariableValue::Unknown { .. } => false, |
1617 | ConstVariableValue::Known { .. } => true, | |
1618 | } | |
1619 | } | |
1620 | } | |
1621 | } | |
353b0b11 | 1622 | } |
2b03887a | 1623 | |
353b0b11 | 1624 | impl<'tcx> TypeErrCtxt<'_, 'tcx> { |
2b03887a FG |
1625 | // [Note-Type-error-reporting] |
1626 | // An invariant is that anytime the expected or actual type is Error (the special | |
1627 | // error type, meaning that an error occurred when typechecking this expression), | |
1628 | // this is a derived error. The error cascaded from another error (that was already | |
1629 | // reported), so it's not useful to display it to the user. | |
1630 | // The following methods implement this logic. | |
1631 | // They check if either the actual or expected type is Error, and don't print the error | |
1632 | // in this case. The typechecker should only ever report type errors involving mismatched | |
1633 | // types using one of these methods, and should not call span_err directly for such | |
1634 | // errors. | |
2b03887a FG |
1635 | pub fn type_error_struct_with_diag<M>( |
1636 | &self, | |
1637 | sp: Span, | |
1638 | mk_diag: M, | |
1639 | actual_ty: Ty<'tcx>, | |
1640 | ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> | |
1641 | where | |
1642 | M: FnOnce(String) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>, | |
1643 | { | |
1644 | let actual_ty = self.resolve_vars_if_possible(actual_ty); | |
1645 | debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty); | |
1646 | ||
1647 | let mut err = mk_diag(self.ty_to_string(actual_ty)); | |
1648 | ||
1649 | // Don't report an error if actual type is `Error`. | |
1650 | if actual_ty.references_error() { | |
1651 | err.downgrade_to_delayed_bug(); | |
1652 | } | |
1653 | ||
1654 | err | |
1655 | } | |
1656 | ||
1657 | pub fn report_mismatched_types( | |
1658 | &self, | |
1659 | cause: &ObligationCause<'tcx>, | |
1660 | expected: Ty<'tcx>, | |
1661 | actual: Ty<'tcx>, | |
1662 | err: TypeError<'tcx>, | |
1663 | ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { | |
1664 | self.report_and_explain_type_error(TypeTrace::types(cause, true, expected, actual), err) | |
1665 | } | |
1666 | ||
1667 | pub fn report_mismatched_consts( | |
1668 | &self, | |
1669 | cause: &ObligationCause<'tcx>, | |
1670 | expected: ty::Const<'tcx>, | |
1671 | actual: ty::Const<'tcx>, | |
1672 | err: TypeError<'tcx>, | |
1673 | ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { | |
1674 | self.report_and_explain_type_error(TypeTrace::consts(cause, true, expected, actual), err) | |
1675 | } | |
1676 | } | |
1677 | ||
353b0b11 | 1678 | /// Helper for [InferCtxt::ty_or_const_infer_var_changed] (see comment on that), currently |
ba9703b0 XL |
1679 | /// used only for `traits::fulfill`'s list of `stalled_on` inference variables. |
1680 | #[derive(Copy, Clone, Debug)] | |
1681 | pub enum TyOrConstInferVar<'tcx> { | |
1682 | /// Equivalent to `ty::Infer(ty::TyVar(_))`. | |
1683 | Ty(TyVid), | |
1684 | /// Equivalent to `ty::Infer(ty::IntVar(_))`. | |
1685 | TyInt(IntVid), | |
1686 | /// Equivalent to `ty::Infer(ty::FloatVar(_))`. | |
1687 | TyFloat(FloatVid), | |
1688 | ||
1689 | /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`. | |
1690 | Const(ConstVid<'tcx>), | |
1691 | } | |
1692 | ||
a2a8927a | 1693 | impl<'tcx> TyOrConstInferVar<'tcx> { |
ba9703b0 XL |
1694 | /// Tries to extract an inference variable from a type or a constant, returns `None` |
1695 | /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and | |
1696 | /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). | |
1697 | pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> { | |
1698 | match arg.unpack() { | |
1699 | GenericArgKind::Type(ty) => Self::maybe_from_ty(ty), | |
1700 | GenericArgKind::Const(ct) => Self::maybe_from_const(ct), | |
1701 | GenericArgKind::Lifetime(_) => None, | |
74b04a01 XL |
1702 | } |
1703 | } | |
ba9703b0 XL |
1704 | |
1705 | /// Tries to extract an inference variable from a type, returns `None` | |
1706 | /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). | |
f2b60f7d | 1707 | fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> { |
1b1a35ee | 1708 | match *ty.kind() { |
ba9703b0 XL |
1709 | ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), |
1710 | ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), | |
1711 | ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), | |
1712 | _ => None, | |
1713 | } | |
1714 | } | |
1715 | ||
1716 | /// Tries to extract an inference variable from a constant, returns `None` | |
1717 | /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). | |
f2b60f7d | 1718 | fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> { |
923072b8 | 1719 | match ct.kind() { |
ba9703b0 XL |
1720 | ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)), |
1721 | _ => None, | |
1722 | } | |
1723 | } | |
1724 | } | |
1725 | ||
5e7ed085 FG |
1726 | /// Replace `{integer}` with `i32` and `{float}` with `f64`. |
1727 | /// Used only for diagnostics. | |
1728 | struct InferenceLiteralEraser<'tcx> { | |
1729 | tcx: TyCtxt<'tcx>, | |
1730 | } | |
1731 | ||
9ffffee4 FG |
1732 | impl<'tcx> TypeFolder<TyCtxt<'tcx>> for InferenceLiteralEraser<'tcx> { |
1733 | fn interner(&self) -> TyCtxt<'tcx> { | |
5e7ed085 FG |
1734 | self.tcx |
1735 | } | |
1736 | ||
1737 | fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { | |
1738 | match ty.kind() { | |
1739 | ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32, | |
1740 | ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64, | |
1741 | _ => ty.super_fold_with(self), | |
1742 | } | |
1743 | } | |
1744 | } | |
1745 | ||
ba9703b0 | 1746 | struct ShallowResolver<'a, 'tcx> { |
2b03887a | 1747 | infcx: &'a InferCtxt<'tcx>, |
74b04a01 XL |
1748 | } |
1749 | ||
9ffffee4 FG |
1750 | impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ShallowResolver<'a, 'tcx> { |
1751 | fn interner(&self) -> TyCtxt<'tcx> { | |
74b04a01 XL |
1752 | self.infcx.tcx |
1753 | } | |
1754 | ||
04454e1e FG |
1755 | /// If `ty` is a type variable of some kind, resolve it one level |
1756 | /// (but do not resolve types found in the result). If `typ` is | |
1757 | /// not a type variable, just return it unmodified. | |
9ffffee4 | 1758 | #[inline] |
74b04a01 | 1759 | fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { |
9ffffee4 FG |
1760 | if let ty::Infer(v) = ty.kind() { self.fold_infer_ty(*v).unwrap_or(ty) } else { ty } |
1761 | } | |
1762 | ||
1763 | fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> { | |
1764 | if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() { | |
1765 | self.infcx | |
1766 | .inner | |
1767 | .borrow_mut() | |
1768 | .const_unification_table() | |
1769 | .probe_value(vid) | |
1770 | .val | |
1771 | .known() | |
1772 | .unwrap_or(ct) | |
1773 | } else { | |
1774 | ct | |
1775 | } | |
1776 | } | |
1777 | } | |
1778 | ||
1779 | impl<'a, 'tcx> ShallowResolver<'a, 'tcx> { | |
1780 | // This is separate from `fold_ty` to keep that method small and inlinable. | |
1781 | #[inline(never)] | |
1782 | fn fold_infer_ty(&mut self, v: InferTy) -> Option<Ty<'tcx>> { | |
1783 | match v { | |
1784 | ty::TyVar(v) => { | |
04454e1e FG |
1785 | // Not entirely obvious: if `typ` is a type variable, |
1786 | // it can be resolved to an int/float variable, which | |
1787 | // can then be recursively resolved, hence the | |
1788 | // recursion. Note though that we prevent type | |
1789 | // variables from unifying to other type variables | |
1790 | // directly (though they may be embedded | |
1791 | // structurally), and we prevent cycles in any case, | |
1792 | // so this recursion should always be of very limited | |
1793 | // depth. | |
1794 | // | |
1795 | // Note: if these two lines are combined into one we get | |
1796 | // dynamic borrow errors on `self.inner`. | |
1797 | let known = self.infcx.inner.borrow_mut().type_variables().probe(v).known(); | |
9ffffee4 | 1798 | known.map(|t| self.fold_ty(t)) |
04454e1e FG |
1799 | } |
1800 | ||
9ffffee4 | 1801 | ty::IntVar(v) => self |
04454e1e FG |
1802 | .infcx |
1803 | .inner | |
1804 | .borrow_mut() | |
1805 | .int_unification_table() | |
1806 | .probe_value(v) | |
9ffffee4 | 1807 | .map(|v| v.to_type(self.infcx.tcx)), |
04454e1e | 1808 | |
9ffffee4 | 1809 | ty::FloatVar(v) => self |
04454e1e FG |
1810 | .infcx |
1811 | .inner | |
1812 | .borrow_mut() | |
1813 | .float_unification_table() | |
1814 | .probe_value(v) | |
9ffffee4 | 1815 | .map(|v| v.to_type(self.infcx.tcx)), |
74b04a01 | 1816 | |
9ffffee4 | 1817 | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => None, |
74b04a01 XL |
1818 | } |
1819 | } | |
1820 | } | |
1821 | ||
1822 | impl<'tcx> TypeTrace<'tcx> { | |
1823 | pub fn span(&self) -> Span { | |
1824 | self.cause.span | |
1825 | } | |
1826 | ||
1827 | pub fn types( | |
1828 | cause: &ObligationCause<'tcx>, | |
1829 | a_is_expected: bool, | |
1830 | a: Ty<'tcx>, | |
1831 | b: Ty<'tcx>, | |
1832 | ) -> TypeTrace<'tcx> { | |
5099ac24 FG |
1833 | TypeTrace { |
1834 | cause: cause.clone(), | |
1835 | values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())), | |
1836 | } | |
74b04a01 XL |
1837 | } |
1838 | ||
f2b60f7d FG |
1839 | pub fn poly_trait_refs( |
1840 | cause: &ObligationCause<'tcx>, | |
1841 | a_is_expected: bool, | |
1842 | a: ty::PolyTraitRef<'tcx>, | |
1843 | b: ty::PolyTraitRef<'tcx>, | |
1844 | ) -> TypeTrace<'tcx> { | |
1845 | TypeTrace { | |
1846 | cause: cause.clone(), | |
9c376795 | 1847 | values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b)), |
f2b60f7d FG |
1848 | } |
1849 | } | |
1850 | ||
f9f354fc XL |
1851 | pub fn consts( |
1852 | cause: &ObligationCause<'tcx>, | |
1853 | a_is_expected: bool, | |
5099ac24 FG |
1854 | a: ty::Const<'tcx>, |
1855 | b: ty::Const<'tcx>, | |
f9f354fc | 1856 | ) -> TypeTrace<'tcx> { |
5099ac24 FG |
1857 | TypeTrace { |
1858 | cause: cause.clone(), | |
1859 | values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())), | |
1860 | } | |
f9f354fc | 1861 | } |
74b04a01 XL |
1862 | } |
1863 | ||
1864 | impl<'tcx> SubregionOrigin<'tcx> { | |
1865 | pub fn span(&self) -> Span { | |
1866 | match *self { | |
1867 | Subtype(ref a) => a.span(), | |
74b04a01 | 1868 | RelateObjectBound(a) => a, |
94222f64 | 1869 | RelateParamBound(a, ..) => a, |
74b04a01 | 1870 | RelateRegionParamBound(a) => a, |
74b04a01 | 1871 | Reborrow(a) => a, |
74b04a01 | 1872 | ReferenceOutlivesReferent(_, a) => a, |
064997fb | 1873 | CompareImplItemObligation { span, .. } => span, |
f2b60f7d | 1874 | AscribeUserTypeProvePredicate(span) => span, |
5099ac24 | 1875 | CheckAssociatedTypeBounds { ref parent, .. } => parent.span(), |
74b04a01 XL |
1876 | } |
1877 | } | |
1878 | ||
1879 | pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self | |
1880 | where | |
1881 | F: FnOnce() -> Self, | |
1882 | { | |
a2a8927a | 1883 | match *cause.code() { |
74b04a01 XL |
1884 | traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { |
1885 | SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span) | |
1886 | } | |
1887 | ||
064997fb | 1888 | traits::ObligationCauseCode::CompareImplItemObligation { |
c295e0f8 XL |
1889 | impl_item_def_id, |
1890 | trait_item_def_id, | |
064997fb FG |
1891 | kind: _, |
1892 | } => SubregionOrigin::CompareImplItemObligation { | |
c295e0f8 | 1893 | span: cause.span, |
c295e0f8 XL |
1894 | impl_item_def_id, |
1895 | trait_item_def_id, | |
1896 | }, | |
1897 | ||
5099ac24 FG |
1898 | traits::ObligationCauseCode::CheckAssociatedTypeBounds { |
1899 | impl_item_def_id, | |
1900 | trait_item_def_id, | |
1901 | } => SubregionOrigin::CheckAssociatedTypeBounds { | |
1902 | impl_item_def_id, | |
1903 | trait_item_def_id, | |
1904 | parent: Box::new(default()), | |
1905 | }, | |
1906 | ||
f2b60f7d FG |
1907 | traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => { |
1908 | SubregionOrigin::AscribeUserTypeProvePredicate(span) | |
1909 | } | |
1910 | ||
74b04a01 XL |
1911 | _ => default(), |
1912 | } | |
1913 | } | |
1914 | } | |
1915 | ||
1916 | impl RegionVariableOrigin { | |
1917 | pub fn span(&self) -> Span { | |
1918 | match *self { | |
3dfed10e XL |
1919 | MiscVariable(a) |
1920 | | PatternRegion(a) | |
1921 | | AddrOfRegion(a) | |
3c0e092e | 1922 | | Autoref(a) |
3dfed10e XL |
1923 | | Coercion(a) |
1924 | | EarlyBoundRegion(a, ..) | |
1925 | | LateBoundRegion(a, ..) | |
1926 | | UpvarRegion(_, a) => a, | |
5869c6ff | 1927 | Nll(..) => bug!("NLL variable used with `span`"), |
74b04a01 XL |
1928 | } |
1929 | } | |
1930 | } | |
1931 | ||
064997fb FG |
1932 | /// Replaces substs that reference param or infer variables with suitable |
1933 | /// placeholders. This function is meant to remove these param and infer | |
1934 | /// substs when they're not actually needed to evaluate a constant. | |
1935 | fn replace_param_and_infer_substs_with_placeholder<'tcx>( | |
1936 | tcx: TyCtxt<'tcx>, | |
1937 | substs: SubstsRef<'tcx>, | |
1938 | ) -> SubstsRef<'tcx> { | |
9c376795 FG |
1939 | struct ReplaceParamAndInferWithPlaceholder<'tcx> { |
1940 | tcx: TyCtxt<'tcx>, | |
9ffffee4 | 1941 | idx: u32, |
9c376795 FG |
1942 | } |
1943 | ||
9ffffee4 FG |
1944 | impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceParamAndInferWithPlaceholder<'tcx> { |
1945 | fn interner(&self) -> TyCtxt<'tcx> { | |
9c376795 FG |
1946 | self.tcx |
1947 | } | |
1948 | ||
1949 | fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { | |
1950 | if let ty::Infer(_) = t.kind() { | |
353b0b11 FG |
1951 | let idx = { |
1952 | let idx = self.idx; | |
1953 | self.idx += 1; | |
1954 | idx | |
1955 | }; | |
9ffffee4 | 1956 | self.tcx.mk_placeholder(ty::PlaceholderType { |
064997fb | 1957 | universe: ty::UniverseIndex::ROOT, |
353b0b11 FG |
1958 | bound: ty::BoundTy { |
1959 | var: ty::BoundVar::from_u32(idx), | |
1960 | kind: ty::BoundTyKind::Anon, | |
1961 | }, | |
9ffffee4 | 1962 | }) |
9c376795 FG |
1963 | } else { |
1964 | t.super_fold_with(self) | |
064997fb | 1965 | } |
9c376795 FG |
1966 | } |
1967 | ||
1968 | fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> { | |
1969 | if let ty::ConstKind::Infer(_) = c.kind() { | |
1970 | let ty = c.ty(); | |
1971 | // If the type references param or infer then ICE ICE ICE | |
2b03887a | 1972 | if ty.has_non_region_param() || ty.has_non_region_infer() { |
9c376795 | 1973 | bug!("const `{c}`'s type should not reference params or types"); |
064997fb | 1974 | } |
9c376795 | 1975 | self.tcx.mk_const( |
487cf647 | 1976 | ty::PlaceholderConst { |
064997fb | 1977 | universe: ty::UniverseIndex::ROOT, |
353b0b11 | 1978 | bound: ty::BoundVar::from_u32({ |
9c376795 FG |
1979 | let idx = self.idx; |
1980 | self.idx += 1; | |
1981 | idx | |
1982 | }), | |
487cf647 FG |
1983 | }, |
1984 | ty, | |
1985 | ) | |
9c376795 FG |
1986 | } else { |
1987 | c.super_fold_with(self) | |
064997fb | 1988 | } |
064997fb | 1989 | } |
9c376795 FG |
1990 | } |
1991 | ||
1992 | substs.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: 0 }) | |
064997fb | 1993 | } |