Skip to main content

hir_ty/next_solver/
region.rs

1//! Things related to regions.
2
3use hir_def::LifetimeParamId;
4use intern::{Interned, InternedRef, impl_internable};
5use macros::GenericTypeVisitable;
6use rustc_type_ir::{
7    BoundVarIndexKind, DebruijnIndex, Flags, GenericTypeVisitable, INNERMOST, RegionVid, TypeFlags,
8    TypeFoldable, TypeVisitable,
9    inherent::{IntoKind, SliceLike},
10    relate::Relate,
11};
12
13use crate::next_solver::{
14    GenericArg, OutlivesPredicate, impl_foldable_for_interned_slice, impl_stored_interned,
15    interned_slice,
16};
17
18use super::{SolverDefId, interner::DbInterner};
19
20pub type RegionKind<'db> = rustc_type_ir::RegionKind<DbInterner<'db>>;
21pub type RegionConstraint<'db> = rustc_type_ir::RegionConstraint<DbInterner<'db>>;
22
23#[derive(Clone, Copy, PartialEq, Eq, Hash)]
24pub struct Region<'db> {
25    pub(super) interned: InternedRef<'db, RegionInterned>,
26}
27
28#[derive(PartialEq, Eq, Hash, GenericTypeVisitable)]
29#[repr(align(4))] // Required for `GenericArg` bit-tagging.
30pub(super) struct RegionInterned(RegionKind<'static>);
31
32impl_internable!(gc; RegionInterned);
33impl_stored_interned!(RegionInterned, Region, StoredRegion);
34
35const _: () = {
36    const fn is_copy<T: Copy>() {}
37    is_copy::<Region<'static>>();
38};
39
40impl<'db> Region<'db> {
41    /// You should avoid using this if you can, since we want `Region` to be defined in `rustc_type_ir` and then this method
42    /// will become more difficult to use.
43    pub fn new_without_interner(kind: RegionKind<'db>) -> Self {
44        let kind = unsafe { std::mem::transmute::<RegionKind<'db>, RegionKind<'static>>(kind) };
45        Self { interned: Interned::new_gc(RegionInterned(kind)) }
46    }
47
48    pub fn new(_interner: DbInterner<'db>, kind: RegionKind<'db>) -> Self {
49        Self::new_without_interner(kind)
50    }
51
52    pub fn inner(&self) -> &RegionKind<'db> {
53        let inner = &self.interned.0;
54        unsafe { std::mem::transmute::<&RegionKind<'static>, &RegionKind<'db>>(inner) }
55    }
56
57    pub fn new_early_param(
58        interner: DbInterner<'db>,
59        early_bound_region: EarlyParamRegion,
60    ) -> Self {
61        Region::new(interner, RegionKind::ReEarlyParam(early_bound_region))
62    }
63
64    pub fn new_placeholder(interner: DbInterner<'db>, placeholder: PlaceholderRegion<'db>) -> Self {
65        Region::new(interner, RegionKind::RePlaceholder(placeholder))
66    }
67
68    pub fn new_var(interner: DbInterner<'db>, v: RegionVid) -> Region<'db> {
69        let Some(region) = interner.preinterned_region_var(v) else {
70            return Region::new(interner, RegionKind::ReVar(v));
71        };
72        region
73    }
74
75    pub fn new_erased(interner: DbInterner<'db>) -> Region<'db> {
76        interner.default_types().regions.erased
77    }
78
79    pub fn new_bound(
80        interner: DbInterner<'db>,
81        index: DebruijnIndex,
82        bound: BoundRegion<'db>,
83    ) -> Region<'db> {
84        Region::new(interner, RegionKind::ReBound(BoundVarIndexKind::Bound(index), bound))
85    }
86
87    pub fn new_late_param(
88        interner: DbInterner<'db>,
89        scope: SolverDefId<'db>,
90        bound_region: BoundRegion<'db>,
91    ) -> Region<'db> {
92        let late_bound_region = LateParamRegion { scope, bound_region };
93        Region::new(interner, RegionKind::ReLateParam(late_bound_region))
94    }
95
96    pub fn is_placeholder(&self) -> bool {
97        matches!(self.inner(), RegionKind::RePlaceholder(..))
98    }
99
100    pub fn is_static(&self) -> bool {
101        matches!(self.inner(), RegionKind::ReStatic)
102    }
103
104    pub fn is_erased(&self) -> bool {
105        matches!(self.inner(), RegionKind::ReErased)
106    }
107
108    pub fn is_var(&self) -> bool {
109        matches!(self.inner(), RegionKind::ReVar(_))
110    }
111
112    pub fn is_error(&self) -> bool {
113        matches!(self.inner(), RegionKind::ReError(_))
114    }
115
116    pub fn error(interner: DbInterner<'db>) -> Self {
117        interner.default_types().regions.error
118    }
119
120    pub fn type_flags(&self) -> TypeFlags {
121        let mut flags = TypeFlags::empty();
122
123        match &self.inner() {
124            RegionKind::ReVar(..) => {
125                flags |= TypeFlags::HAS_FREE_REGIONS;
126                flags |= TypeFlags::HAS_FREE_LOCAL_REGIONS;
127                flags |= TypeFlags::HAS_RE_INFER;
128            }
129            RegionKind::RePlaceholder(..) => {
130                flags |= TypeFlags::HAS_FREE_REGIONS;
131                flags |= TypeFlags::HAS_FREE_LOCAL_REGIONS;
132                flags |= TypeFlags::HAS_RE_PLACEHOLDER;
133            }
134            RegionKind::ReEarlyParam(..) => {
135                flags |= TypeFlags::HAS_FREE_REGIONS;
136                flags |= TypeFlags::HAS_FREE_LOCAL_REGIONS;
137                flags |= TypeFlags::HAS_RE_PARAM;
138            }
139            RegionKind::ReLateParam(..) => {
140                flags |= TypeFlags::HAS_FREE_REGIONS;
141                flags |= TypeFlags::HAS_FREE_LOCAL_REGIONS;
142            }
143            RegionKind::ReStatic => {
144                flags |= TypeFlags::HAS_FREE_REGIONS;
145            }
146            RegionKind::ReBound(BoundVarIndexKind::Canonical, ..) => {
147                flags |= TypeFlags::HAS_RE_BOUND;
148                flags |= TypeFlags::HAS_CANONICAL_BOUND;
149            }
150            RegionKind::ReBound(BoundVarIndexKind::Bound(..), ..) => {
151                flags |= TypeFlags::HAS_RE_BOUND;
152            }
153            RegionKind::ReErased => {
154                flags |= TypeFlags::HAS_RE_ERASED;
155            }
156            RegionKind::ReError(..) => {
157                flags |= TypeFlags::HAS_FREE_REGIONS;
158                flags |= TypeFlags::HAS_RE_ERROR;
159            }
160        }
161
162        flags
163    }
164}
165
166pub type PlaceholderRegion<'db> = rustc_type_ir::PlaceholderRegion<DbInterner<'db>>;
167
168#[derive(Copy, Clone, PartialEq, Eq, Hash)]
169pub struct EarlyParamRegion {
170    // FIXME: See `ParamTy`.
171    pub id: LifetimeParamId,
172    pub index: u32,
173}
174
175#[derive(Copy, Clone, PartialEq, Eq, Hash, GenericTypeVisitable)]
176/// Represents a liberated late-bound function lifetime parameter.
177///
178/// This denotes some region at least as big as `scope`. It is similar to a placeholder region
179/// created when entering a binder, except it always lives in the root universe.
180pub struct LateParamRegion<'db> {
181    pub scope: SolverDefId<'db>,
182    pub bound_region: BoundRegion<'db>,
183}
184
185impl std::fmt::Debug for LateParamRegion<'_> {
186    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187        write!(f, "ReLateParam({:?}, {:?})", self.scope, self.bound_region)
188    }
189}
190
191pub type BoundRegion<'db> = rustc_type_ir::BoundRegion<DbInterner<'db>>;
192pub type BoundRegionKind<'db> = rustc_type_ir::BoundRegionKind<DbInterner<'db>>;
193
194impl rustc_type_ir::inherent::ParamLike for EarlyParamRegion {
195    fn index(self) -> u32 {
196        self.index
197    }
198}
199
200impl std::fmt::Debug for EarlyParamRegion {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        write!(f, "#{}", self.index)
203        // write!(f, "{}/#{}", self.name, self.index)
204    }
205}
206
207impl std::fmt::Debug for Region<'_> {
208    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
209        self.kind().fmt(f)
210    }
211}
212
213impl<'db> IntoKind for Region<'db> {
214    type Kind = RegionKind<'db>;
215
216    fn kind(self) -> Self::Kind {
217        *self.inner()
218    }
219}
220
221impl<'db> TypeVisitable<DbInterner<'db>> for Region<'db> {
222    fn visit_with<V: rustc_type_ir::TypeVisitor<DbInterner<'db>>>(
223        &self,
224        visitor: &mut V,
225    ) -> V::Result {
226        visitor.visit_region(*self)
227    }
228}
229
230impl<'db> TypeFoldable<DbInterner<'db>> for Region<'db> {
231    fn try_fold_with<F: rustc_type_ir::FallibleTypeFolder<DbInterner<'db>>>(
232        self,
233        folder: &mut F,
234    ) -> Result<Self, F::Error> {
235        folder.try_fold_region(self)
236    }
237    fn fold_with<F: rustc_type_ir::TypeFolder<DbInterner<'db>>>(self, folder: &mut F) -> Self {
238        folder.fold_region(self)
239    }
240}
241
242impl<'db> Relate<DbInterner<'db>> for Region<'db> {
243    fn relate<R: rustc_type_ir::relate::TypeRelation<DbInterner<'db>>>(
244        relation: &mut R,
245        a: Self,
246        b: Self,
247    ) -> rustc_type_ir::relate::RelateResult<DbInterner<'db>, Self> {
248        relation.regions(a, b)
249    }
250}
251
252impl<'db> Flags for Region<'db> {
253    fn flags(&self) -> rustc_type_ir::TypeFlags {
254        self.type_flags()
255    }
256
257    fn outer_exclusive_binder(&self) -> rustc_type_ir::DebruijnIndex {
258        match &self.inner() {
259            RegionKind::ReBound(BoundVarIndexKind::Bound(debruijn), _) => debruijn.shifted_in(1),
260            _ => INNERMOST,
261        }
262    }
263}
264
265impl<'db> rustc_type_ir::inherent::Region<DbInterner<'db>> for Region<'db> {
266    fn new_bound(
267        interner: DbInterner<'db>,
268        debruijn: DebruijnIndex,
269        var: BoundRegion<'db>,
270    ) -> Self {
271        Region::new(interner, RegionKind::ReBound(BoundVarIndexKind::Bound(debruijn), var))
272    }
273
274    fn new_anon_bound(
275        interner: DbInterner<'db>,
276        debruijn: DebruijnIndex,
277        var: rustc_type_ir::BoundVar,
278    ) -> Self {
279        Region::new(
280            interner,
281            RegionKind::ReBound(
282                BoundVarIndexKind::Bound(debruijn),
283                BoundRegion { var, kind: BoundRegionKind::Anon },
284            ),
285        )
286    }
287
288    fn new_canonical_bound(interner: DbInterner<'db>, var: rustc_type_ir::BoundVar) -> Self {
289        let Some(region) = interner.preinterned_canonical_bound_region(var) else {
290            return Region::new(
291                interner,
292                RegionKind::ReBound(
293                    BoundVarIndexKind::Canonical,
294                    BoundRegion { var, kind: BoundRegionKind::Anon },
295                ),
296            );
297        };
298        region
299    }
300
301    fn new_static(interner: DbInterner<'db>) -> Self {
302        interner.default_types().regions.statik
303    }
304
305    fn new_placeholder(interner: DbInterner<'db>, var: PlaceholderRegion<'db>) -> Self {
306        Region::new(interner, RegionKind::RePlaceholder(var))
307    }
308}
309
310impl<'db, V: super::WorldExposer> GenericTypeVisitable<V> for Region<'db> {
311    fn generic_visit_with(&self, visitor: &mut V) {
312        if visitor.on_interned(self.interned).is_continue() {
313            self.kind().generic_visit_with(visitor);
314        }
315    }
316}
317
318type GenericArgOutlivesPredicate<'db> = OutlivesPredicate<'db, GenericArg<'db>>;
319
320interned_slice!(
321    RegionAssumptionsStorage,
322    RegionAssumptions,
323    StoredRegionAssumptions,
324    region_assumptions,
325    GenericArgOutlivesPredicate<'db>,
326    GenericArgOutlivesPredicate<'static>,
327);
328impl_foldable_for_interned_slice!(RegionAssumptions);