Skip to main content

hir_ty/
next_solver.rs

1//! Things relevant to the next trait solver.
2
3// Note: in interned types defined in this module, we generally treat the lifetime as advisory
4// and transmute it as needed. This is because no real memory unsafety can be caused from an
5// incorrect lifetime here.
6
7pub mod abi;
8mod allocation;
9mod binder;
10mod consts;
11mod def_id;
12pub mod fold;
13pub mod format_proof_tree;
14pub mod fulfill;
15mod generic_arg;
16pub mod generics;
17pub mod infer;
18pub(crate) mod inspect;
19pub mod interner;
20mod ir_print;
21pub mod normalize;
22pub mod obligation_ctxt;
23mod opaques;
24pub mod predicate;
25mod region;
26mod solver;
27mod structural_normalize;
28mod ty;
29pub mod util;
30
31use std::{mem::ManuallyDrop, sync::OnceLock};
32
33use rustc_type_ir::{BoundVar, BoundVarIndexKind, InferTy, RegionVid, TyVid};
34
35pub use allocation::*;
36pub use binder::*;
37pub use consts::*;
38pub use def_id::*;
39pub use generic_arg::*;
40pub use interner::*;
41pub use opaques::*;
42pub use predicate::*;
43pub use region::*;
44use rustc_type_ir::MayBeErased;
45pub use solver::*;
46pub use ty::*;
47
48pub use crate::lower::ImplTraitIdx;
49pub use rustc_ast_ir::Mutability;
50
51pub type Binder<'db, T> = rustc_type_ir::Binder<DbInterner<'db>, T>;
52pub type EarlyBinder<'db, T> = rustc_type_ir::EarlyBinder<DbInterner<'db>, T>;
53pub type Unnormalized<'db, T> = rustc_type_ir::Unnormalized<DbInterner<'db>, T>;
54pub type Canonical<'db, T> = rustc_type_ir::Canonical<DbInterner<'db>, T>;
55pub type CanonicalVarValues<'db> = rustc_type_ir::CanonicalVarValues<DbInterner<'db>>;
56pub type CanonicalVarKind<'db> = rustc_type_ir::CanonicalVarKind<DbInterner<'db>>;
57pub type CanonicalQueryInput<'db, V> = rustc_type_ir::CanonicalQueryInput<DbInterner<'db>, V>;
58pub type AliasTy<'db> = rustc_type_ir::AliasTy<DbInterner<'db>>;
59pub type FnSig<'db> = rustc_type_ir::FnSig<DbInterner<'db>>;
60pub type PolyFnSig<'db> = Binder<'db, rustc_type_ir::FnSig<DbInterner<'db>>>;
61pub type TypingMode<'db, S = MayBeErased> = rustc_type_ir::TypingMode<DbInterner<'db>, S>;
62pub type TypeError<'db> = rustc_type_ir::error::TypeError<DbInterner<'db>>;
63pub type QueryResult<'db> = rustc_type_ir::solve::QueryResult<DbInterner<'db>>;
64pub type FxIndexMap<K, V> = rustc_type_ir::data_structures::IndexMap<K, V>;
65
66const NUM_PREINTERNED_TY_VARS: usize = 1024;
67const NUM_PREINTERNED_REGION_VARS: usize = 256;
68const NUM_PREINTERNED_CANONICAL_BOUNDS: usize = 128;
69
70pub struct DefaultTypes<'db> {
71    pub usize: Ty<'db>,
72    pub u8: Ty<'db>,
73    pub u16: Ty<'db>,
74    pub u32: Ty<'db>,
75    pub u64: Ty<'db>,
76    pub u128: Ty<'db>,
77    pub isize: Ty<'db>,
78    pub i8: Ty<'db>,
79    pub i16: Ty<'db>,
80    pub i32: Ty<'db>,
81    pub i64: Ty<'db>,
82    pub i128: Ty<'db>,
83    pub f16: Ty<'db>,
84    pub f32: Ty<'db>,
85    pub f64: Ty<'db>,
86    pub f128: Ty<'db>,
87    pub unit: Ty<'db>,
88    pub bool: Ty<'db>,
89    pub char: Ty<'db>,
90    pub str: Ty<'db>,
91    pub never: Ty<'db>,
92    pub error: Ty<'db>,
93    /// `&'static str`
94    pub static_str_ref: Ty<'db>,
95    /// `[u8]`
96    pub u8_slice: Ty<'db>,
97    /// `&'static [u8]`
98    pub static_u8_slice: Ty<'db>,
99    /// `*mut ()`
100    pub mut_unit_ptr: Ty<'db>,
101    pub dyn_trait_dummy_self: Ty<'db>,
102    ty_vars: [Ty<'db>; NUM_PREINTERNED_TY_VARS],
103    canonical_bound: [Ty<'db>; NUM_PREINTERNED_CANONICAL_BOUNDS],
104}
105
106pub struct DefaultConsts<'db> {
107    pub error: Const<'db>,
108    pub u8_values: [Const<'db>; 256],
109    pub unit: Const<'db>,
110    pub true_: Const<'db>,
111    pub false_: Const<'db>,
112    /// Use [`ValTree::zst`] instead.
113    pub valtree_zst: ValTree<'db>,
114}
115
116pub struct DefaultRegions<'db> {
117    pub error: Region<'db>,
118    pub statik: Region<'db>,
119    pub erased: Region<'db>,
120    re_vars: [Region<'db>; NUM_PREINTERNED_REGION_VARS],
121    canonical_bound: [Region<'db>; NUM_PREINTERNED_CANONICAL_BOUNDS],
122}
123
124pub struct DefaultEmpty<'db> {
125    pub tys: Tys<'db>,
126    pub generic_args: GenericArgs<'db>,
127    pub bound_var_kinds: BoundVarKinds<'db>,
128    pub canonical_vars: CanonicalVarKinds<'db>,
129    pub variances: VariancesOf<'db>,
130    pub pat_list: PatList<'db>,
131    pub predefined_opaques: PredefinedOpaques<'db>,
132    pub def_ids: SolverDefIds<'db>,
133    pub bound_existential_predicates: BoundExistentialPredicates<'db>,
134    pub clauses: Clauses<'db>,
135    pub region_assumptions: RegionAssumptions<'db>,
136    pub consts: Consts<'db>,
137    pub projection: crate::mir::Projection<'db>,
138}
139
140pub struct DefaultAny<'db> {
141    pub types: DefaultTypes<'db>,
142    pub consts: DefaultConsts<'db>,
143    pub regions: DefaultRegions<'db>,
144    pub empty: DefaultEmpty<'db>,
145    /// `[Invariant]`
146    pub one_invariant: VariancesOf<'db>,
147    /// `[Covariant]`
148    pub one_covariant: VariancesOf<'db>,
149    /// `for<'env>`
150    pub coroutine_captures_by_ref_bound_var_kinds: BoundVarKinds<'db>,
151}
152
153impl<'db> DbInterner<'db> {
154    #[inline]
155    fn preinterned_ty_var(&self, vid: TyVid) -> Option<Ty<'db>> {
156        let index = vid.as_usize();
157        (index < NUM_PREINTERNED_TY_VARS).then(|| self.default_types().types.ty_vars[index])
158    }
159
160    #[inline]
161    fn preinterned_region_var(&self, vid: RegionVid) -> Option<Region<'db>> {
162        let index = vid.as_usize();
163        (index < NUM_PREINTERNED_REGION_VARS).then(|| self.default_types().regions.re_vars[index])
164    }
165
166    #[inline]
167    fn preinterned_canonical_bound_ty(&self, var: BoundVar) -> Option<Ty<'db>> {
168        let index = var.as_usize();
169        (index < NUM_PREINTERNED_CANONICAL_BOUNDS)
170            .then(|| self.default_types().types.canonical_bound[index])
171    }
172
173    #[inline]
174    fn preinterned_canonical_bound_region(&self, var: BoundVar) -> Option<Region<'db>> {
175        let index = var.as_usize();
176        (index < NUM_PREINTERNED_CANONICAL_BOUNDS)
177            .then(|| self.default_types().regions.canonical_bound[index])
178    }
179}
180
181impl std::fmt::Debug for DefaultAny<'_> {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        f.debug_struct("DefaultAny").finish_non_exhaustive()
184    }
185}
186
187#[inline]
188pub fn default_types<'db>() -> &'db DefaultAny<'db> {
189    static TYPES: OnceLock<DefaultAny<'static>> = OnceLock::new();
190
191    TYPES.get_or_init(|| {
192        let create_ty = |kind| {
193            let ty = Ty::new_without_interner(kind);
194            // We need to increase the refcount (forever), so that the types won't be freed.
195            let ty = ManuallyDrop::new(ty.store());
196            ty.as_ref()
197        };
198        let create_const = |kind| {
199            let ty = Const::new_without_interner(kind);
200            // We need to increase the refcount (forever), so that the types won't be freed.
201            let ty = ManuallyDrop::new(ty.store());
202            ty.as_ref()
203        };
204        let create_valtree = |kind| {
205            let vt = ValTree::new(kind);
206            // We need to increase the refcount (forever), so that the types won't be freed.
207            let vt = ManuallyDrop::new(vt.store());
208            vt.as_ref()
209        };
210        let create_region = |kind| {
211            let ty = Region::new_without_interner(kind);
212            // We need to increase the refcount (forever), so that the types won't be freed.
213            let ty = ManuallyDrop::new(ty.store());
214            ty.as_ref()
215        };
216        let create_generic_args = |slice| {
217            let ty = GenericArgs::new_from_slice_no_empty_check(slice);
218            // We need to increase the refcount (forever), so that the types won't be freed.
219            let ty = ManuallyDrop::new(ty.store());
220            ty.as_ref()
221        };
222        let create_bound_var_kinds = |slice| {
223            let ty = BoundVarKinds::new_from_slice_no_empty_check(slice);
224            // We need to increase the refcount (forever), so that the types won't be freed.
225            let ty = ManuallyDrop::new(ty.store());
226            ty.as_ref()
227        };
228        let create_canonical_vars = |slice| {
229            let ty = CanonicalVarKinds::new_from_slice_no_empty_check(slice);
230            // We need to increase the refcount (forever), so that the types won't be freed.
231            let ty = ManuallyDrop::new(ty.store());
232            ty.as_ref()
233        };
234        let create_variances_of = |slice| {
235            let ty = VariancesOf::new_from_slice_no_empty_check(slice);
236            // We need to increase the refcount (forever), so that the types won't be freed.
237            let ty = ManuallyDrop::new(ty.store());
238            ty.as_ref()
239        };
240        let create_pat_list = |slice| {
241            let ty = PatList::new_from_slice_no_empty_check(slice);
242            // We need to increase the refcount (forever), so that the types won't be freed.
243            let ty = ManuallyDrop::new(ty.store());
244            ty.as_ref()
245        };
246        let create_predefined_opaques = |slice| {
247            let ty = PredefinedOpaques::new_from_slice_no_empty_check(slice);
248            // We need to increase the refcount (forever), so that the types won't be freed.
249            let ty = ManuallyDrop::new(ty.store());
250            ty.as_ref()
251        };
252        let create_solver_def_ids = |slice| {
253            let ty = SolverDefIds::new_from_slice_no_empty_check(slice);
254            // We need to increase the refcount (forever), so that the types won't be freed.
255            let ty = ManuallyDrop::new(ty.store());
256            ty.as_ref()
257        };
258        let create_bound_existential_predicates = |slice| {
259            let ty = BoundExistentialPredicates::new_from_slice_no_empty_check(slice);
260            // We need to increase the refcount (forever), so that the types won't be freed.
261            let ty = ManuallyDrop::new(ty.store());
262            ty.as_ref()
263        };
264        let create_clauses = |slice| {
265            let ty = Clauses::new_from_slice_no_empty_check(slice);
266            // We need to increase the refcount (forever), so that the types won't be freed.
267            let ty = ManuallyDrop::new(ty.store());
268            ty.as_ref()
269        };
270        let create_region_assumptions = |slice| {
271            let ty = RegionAssumptions::new_from_slice_no_empty_check(slice);
272            // We need to increase the refcount (forever), so that the types won't be freed.
273            let ty = ManuallyDrop::new(ty.store());
274            ty.as_ref()
275        };
276        let create_tys = |slice| {
277            let ty = Tys::new_from_slice_no_empty_check(slice);
278            // We need to increase the refcount (forever), so that the types won't be freed.
279            let ty = ManuallyDrop::new(ty.store());
280            ty.as_ref()
281        };
282        let create_consts = |slice| {
283            let ty = Consts::new_from_slice_no_empty_check(slice);
284            // We need to increase the refcount (forever), so that the types won't be freed.
285            let ty = ManuallyDrop::new(ty.store());
286            ty.as_ref()
287        };
288        let create_projection = |slice| {
289            let it = crate::mir::Projection::new_from_slice_no_empty_check(slice);
290            // We need to increase the refcount (forever), so that the types won't be freed.
291            let it = ManuallyDrop::new(it.store());
292            it.as_ref()
293        };
294
295        let str = create_ty(TyKind::Str);
296        let statik = create_region(RegionKind::ReStatic);
297        let empty_tys = create_tys(&[]);
298        let unit = create_ty(TyKind::Tuple(empty_tys));
299        let bool = create_ty(TyKind::Bool);
300        let u8 = create_ty(TyKind::Uint(rustc_ast_ir::UintTy::U8));
301        let u8_slice = create_ty(TyKind::Slice(u8));
302        let static_u8_slice = create_ty(TyKind::Ref(statik, u8_slice, Mutability::Not));
303        let empty_consts = create_consts(&[]);
304        let valtree_zst = create_valtree(ValTreeKind::Branch(empty_consts));
305        DefaultAny {
306            types: DefaultTypes {
307                usize: create_ty(TyKind::Uint(rustc_ast_ir::UintTy::Usize)),
308                u8,
309                u16: create_ty(TyKind::Uint(rustc_ast_ir::UintTy::U16)),
310                u32: create_ty(TyKind::Uint(rustc_ast_ir::UintTy::U32)),
311                u64: create_ty(TyKind::Uint(rustc_ast_ir::UintTy::U64)),
312                u128: create_ty(TyKind::Uint(rustc_ast_ir::UintTy::U128)),
313                isize: create_ty(TyKind::Int(rustc_ast_ir::IntTy::Isize)),
314                i8: create_ty(TyKind::Int(rustc_ast_ir::IntTy::I8)),
315                i16: create_ty(TyKind::Int(rustc_ast_ir::IntTy::I16)),
316                i32: create_ty(TyKind::Int(rustc_ast_ir::IntTy::I32)),
317                i64: create_ty(TyKind::Int(rustc_ast_ir::IntTy::I64)),
318                i128: create_ty(TyKind::Int(rustc_ast_ir::IntTy::I128)),
319                f16: create_ty(TyKind::Float(rustc_ast_ir::FloatTy::F16)),
320                f32: create_ty(TyKind::Float(rustc_ast_ir::FloatTy::F32)),
321                f64: create_ty(TyKind::Float(rustc_ast_ir::FloatTy::F64)),
322                f128: create_ty(TyKind::Float(rustc_ast_ir::FloatTy::F128)),
323                unit,
324                bool,
325                char: create_ty(TyKind::Char),
326                str,
327                never: create_ty(TyKind::Never),
328                error: create_ty(TyKind::Error(ErrorGuaranteed)),
329                static_str_ref: create_ty(TyKind::Ref(statik, str, rustc_ast_ir::Mutability::Not)),
330                u8_slice,
331                static_u8_slice,
332                mut_unit_ptr: create_ty(TyKind::RawPtr(unit, rustc_ast_ir::Mutability::Mut)),
333                // This type must not appear anywhere except here.
334                dyn_trait_dummy_self: create_ty(TyKind::Infer(InferTy::FreshTy(0))),
335                ty_vars: std::array::from_fn(|vid| {
336                    create_ty(TyKind::Infer(InferTy::TyVar(TyVid::from_usize(vid))))
337                }),
338                canonical_bound: std::array::from_fn(|var| {
339                    create_ty(TyKind::Bound(
340                        BoundVarIndexKind::Canonical,
341                        BoundTy { var: BoundVar::from_usize(var), kind: BoundTyKind::Anon },
342                    ))
343                }),
344            },
345            consts: DefaultConsts {
346                error: create_const(ConstKind::Error(ErrorGuaranteed)),
347                u8_values: std::array::from_fn(|u8_value| {
348                    create_const(ConstKind::Value(ValueConst {
349                        ty: u8,
350                        value: ValTree::new(ValTreeKind::Leaf(ScalarInt::from(u8_value as u8))),
351                    }))
352                }),
353                unit: create_const(ConstKind::Value(ValueConst { ty: unit, value: valtree_zst })),
354                true_: create_const(ConstKind::Value(ValueConst {
355                    ty: bool,
356                    value: create_valtree(ValTreeKind::Leaf(ScalarInt::TRUE)),
357                })),
358                false_: create_const(ConstKind::Value(ValueConst {
359                    ty: bool,
360                    value: create_valtree(ValTreeKind::Leaf(ScalarInt::FALSE)),
361                })),
362                valtree_zst,
363            },
364            regions: DefaultRegions {
365                error: create_region(RegionKind::ReError(ErrorGuaranteed)),
366                statik,
367                erased: create_region(RegionKind::ReErased),
368                re_vars: std::array::from_fn(|vid| {
369                    create_region(RegionKind::ReVar(RegionVid::from_usize(vid)))
370                }),
371                canonical_bound: std::array::from_fn(|var| {
372                    create_region(RegionKind::ReBound(
373                        BoundVarIndexKind::Canonical,
374                        BoundRegion { var: BoundVar::from_usize(var), kind: BoundRegionKind::Anon },
375                    ))
376                }),
377            },
378            empty: DefaultEmpty {
379                tys: empty_tys,
380                generic_args: create_generic_args(&[]),
381                bound_var_kinds: create_bound_var_kinds(&[]),
382                canonical_vars: create_canonical_vars(&[]),
383                variances: create_variances_of(&[]),
384                pat_list: create_pat_list(&[]),
385                predefined_opaques: create_predefined_opaques(&[]),
386                def_ids: create_solver_def_ids(&[]),
387                bound_existential_predicates: create_bound_existential_predicates(&[]),
388                clauses: create_clauses(&[]),
389                region_assumptions: create_region_assumptions(&[]),
390                consts: empty_consts,
391                projection: create_projection(&[]),
392            },
393            one_invariant: create_variances_of(&[rustc_type_ir::Variance::Invariant]),
394            one_covariant: create_variances_of(&[rustc_type_ir::Variance::Covariant]),
395            coroutine_captures_by_ref_bound_var_kinds: create_bound_var_kinds(&[
396                BoundVariableKind::Region(BoundRegionKind::ClosureEnv),
397            ]),
398        }
399    })
400}