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