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