Skip to main content

hir_ty/next_solver/
consts.rs

1//! Things related to consts in the next-trait-solver.
2
3mod int;
4mod valtree;
5
6use std::hash::Hash;
7
8use hir_def::ConstParamId;
9use intern::{Interned, InternedRef, impl_internable};
10use macros::{GenericTypeVisitable, TypeFoldable, TypeVisitable};
11use rustc_abi::TargetDataLayout;
12use rustc_ast_ir::visit::VisitorResult;
13use rustc_type_ir::{
14    BoundVar, BoundVarIndexKind, ConstVid, DebruijnIndex, FlagComputation, Flags,
15    GenericTypeVisitable, InferConst, TypeFoldable, TypeSuperFoldable, TypeSuperVisitable,
16    TypeVisitable, TypeVisitableExt, WithCachedTypeInfo, inherent::IntoKind, relate::Relate,
17};
18
19use crate::{
20    ParamEnvAndCrate,
21    next_solver::{
22        AllocationData, ClauseKind, ParamEnv, impl_foldable_for_interned_slice,
23        impl_stored_interned, interned_slice,
24    },
25};
26
27use super::{DbInterner, ErrorGuaranteed, GenericArgs, Ty};
28
29pub use self::{int::*, valtree::*};
30
31pub type ConstKind<'db> = rustc_type_ir::ConstKind<DbInterner<'db>>;
32pub type UnevaluatedConst<'db> = rustc_type_ir::UnevaluatedConst<DbInterner<'db>>;
33
34#[derive(Clone, Copy, PartialEq, Eq, Hash)]
35pub struct Const<'db> {
36    pub(super) interned: InternedRef<'db, ConstInterned>,
37}
38
39#[derive(PartialEq, Eq, Hash, GenericTypeVisitable)]
40#[repr(align(4))] // Required for `GenericArg` bit-tagging.
41pub(super) struct ConstInterned(pub(super) WithCachedTypeInfo<ConstKind<'static>>);
42
43impl_internable!(gc; ConstInterned);
44impl_stored_interned!(ConstInterned, Const, StoredConst);
45
46const _: () = {
47    const fn is_copy<T: Copy>() {}
48    is_copy::<Const<'static>>();
49};
50
51impl<'db> Const<'db> {
52    /// You should avoid using this if you can, since we want `Const` to be defined in `rustc_type_ir` and then this method
53    /// will become more difficult to use.
54    #[inline]
55    pub fn new_without_interner(kind: ConstKind<'db>) -> Self {
56        let kind = unsafe { std::mem::transmute::<ConstKind<'db>, ConstKind<'static>>(kind) };
57        let flags = FlagComputation::for_const_kind(&kind);
58        let cached = WithCachedTypeInfo {
59            internee: kind,
60            flags: flags.flags,
61            outer_exclusive_binder: flags.outer_exclusive_binder,
62        };
63        Self { interned: Interned::new_gc(ConstInterned(cached)) }
64    }
65
66    pub fn new(_interner: DbInterner<'db>, kind: ConstKind<'db>) -> Self {
67        Self::new_without_interner(kind)
68    }
69
70    pub fn inner(&self) -> &WithCachedTypeInfo<ConstKind<'db>> {
71        let inner = &self.interned.0;
72        unsafe {
73            std::mem::transmute::<
74                &WithCachedTypeInfo<ConstKind<'static>>,
75                &WithCachedTypeInfo<ConstKind<'db>>,
76            >(inner)
77        }
78    }
79
80    pub fn error(interner: DbInterner<'db>) -> Self {
81        interner.default_types().consts.error
82    }
83
84    pub fn new_param(interner: DbInterner<'db>, param: ParamConst) -> Self {
85        Const::new(interner, ConstKind::Param(param))
86    }
87
88    pub fn new_placeholder(interner: DbInterner<'db>, placeholder: PlaceholderConst<'db>) -> Self {
89        Const::new(interner, ConstKind::Placeholder(placeholder))
90    }
91
92    pub fn new_bound(
93        interner: DbInterner<'db>,
94        index: DebruijnIndex,
95        bound: BoundConst<'db>,
96    ) -> Self {
97        Const::new(interner, ConstKind::Bound(BoundVarIndexKind::Bound(index), bound))
98    }
99
100    pub fn new_valtree(interner: DbInterner<'db>, ty: Ty<'db>, kind: ValTreeKind<'db>) -> Self {
101        Const::new(interner, ConstKind::Value(ValueConst { ty, value: ValTree::new(kind) }))
102    }
103
104    pub fn new_value(interner: DbInterner<'db>, valtree: ValTree<'db>, ty: Ty<'db>) -> Self {
105        Const::new(interner, ConstKind::Value(ValueConst { ty, value: valtree }))
106    }
107
108    pub fn new_from_allocation(
109        interner: DbInterner<'db>,
110        allocation: &AllocationData<'db>,
111        param_env: ParamEnvAndCrate<'db>,
112    ) -> Self {
113        allocation_to_const(
114            interner,
115            allocation.ty,
116            &allocation.memory,
117            &allocation.memory_map,
118            param_env,
119        )
120    }
121
122    #[inline]
123    /// Creates an interned usize constant.
124    pub fn from_target_usize(interner: DbInterner<'db>, n: u64) -> Self {
125        let usize_ty = interner.default_types().types.usize;
126        let data_layout = interner.db.target_data_layout_or_default(interner.expect_crate());
127        Const::new_value(
128            interner,
129            ValTree::from_scalar_int(
130                interner,
131                ScalarInt::try_from_target_usize(n, data_layout).unwrap(),
132            ),
133            usize_ty,
134        )
135    }
136
137    pub fn is_ct_infer(&self) -> bool {
138        matches!(self.kind(), ConstKind::Infer(_))
139    }
140
141    pub fn is_error(&self) -> bool {
142        matches!(self.kind(), ConstKind::Error(_))
143    }
144
145    pub fn is_trivially_wf(self) -> bool {
146        match self.kind() {
147            ConstKind::Param(_) | ConstKind::Placeholder(_) | ConstKind::Bound(..) => true,
148            ConstKind::Infer(_)
149            | ConstKind::Unevaluated(..)
150            | ConstKind::Value(_)
151            | ConstKind::Error(_)
152            | ConstKind::Expr(_) => false,
153        }
154    }
155
156    /// Attempts to convert to a value.
157    ///
158    /// Note that this does not normalize the constant.
159    pub fn try_to_value(self) -> Option<ValueConst<'db>> {
160        match self.kind() {
161            ConstKind::Value(cv) => Some(cv),
162            _ => None,
163        }
164    }
165
166    /// Convenience method to extract the value of a usize constant,
167    /// useful to get the length of an array type.
168    ///
169    /// Note that this does not evaluate the constant.
170    #[inline]
171    pub fn try_to_target_usize(self, data_layout: &TargetDataLayout) -> Option<u64> {
172        self.try_to_value()?.try_to_target_usize(data_layout)
173    }
174}
175
176impl<'db> std::fmt::Debug for Const<'db> {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        self.inner().internee.fmt(f)
179    }
180}
181
182pub type PlaceholderConst<'db> = rustc_type_ir::PlaceholderConst<DbInterner<'db>>;
183
184#[derive(Copy, Clone, Hash, Eq, PartialEq)]
185pub struct ParamConst {
186    // FIXME: See `ParamTy`.
187    pub id: ConstParamId,
188    pub index: u32,
189}
190
191impl std::fmt::Debug for ParamConst {
192    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193        write!(f, "#{}", self.index)
194    }
195}
196
197impl ParamConst {
198    pub fn find_const_ty_from_env<'db>(self, env: ParamEnv<'db>) -> Ty<'db> {
199        let mut candidates = env.clauses.iter().filter_map(|clause| {
200            // `ConstArgHasType` are never desugared to be higher ranked.
201            match clause.kind().skip_binder() {
202                ClauseKind::ConstArgHasType(param_ct, ty) => {
203                    assert!(!(param_ct, ty).has_escaping_bound_vars());
204
205                    match param_ct.kind() {
206                        ConstKind::Param(param_ct) if param_ct.index == self.index => Some(ty),
207                        _ => None,
208                    }
209                }
210                _ => None,
211            }
212        });
213
214        // N.B. it may be tempting to fix ICEs by making this function return
215        // `Option<Ty<'db>>` instead of `Ty<'db>`; however, this is generally
216        // considered to be a bandaid solution, since it hides more important
217        // underlying issues with how we construct generics and predicates of
218        // items. It's advised to fix the underlying issue rather than trying
219        // to modify this function.
220        let ty = candidates.next().unwrap_or_else(|| {
221            panic!("cannot find `{self:?}` in param-env: {env:#?}");
222        });
223        assert!(
224            candidates.next().is_none(),
225            "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}"
226        );
227        ty
228    }
229}
230
231#[derive(
232    Copy, Clone, Debug, Hash, PartialEq, Eq, TypeVisitable, TypeFoldable, GenericTypeVisitable,
233)]
234pub struct ExprConst;
235
236impl rustc_type_ir::inherent::ParamLike for ParamConst {
237    fn index(self) -> u32 {
238        self.index
239    }
240}
241
242impl<'db> IntoKind for Const<'db> {
243    type Kind = ConstKind<'db>;
244
245    fn kind(self) -> Self::Kind {
246        self.inner().internee
247    }
248}
249
250impl<'db, V: super::WorldExposer> GenericTypeVisitable<V> for Const<'db> {
251    fn generic_visit_with(&self, visitor: &mut V) {
252        if visitor.on_interned(self.interned).is_continue() {
253            self.kind().generic_visit_with(visitor);
254        }
255    }
256}
257
258impl<'db> TypeVisitable<DbInterner<'db>> for Const<'db> {
259    fn visit_with<V: rustc_type_ir::TypeVisitor<DbInterner<'db>>>(
260        &self,
261        visitor: &mut V,
262    ) -> V::Result {
263        visitor.visit_const(*self)
264    }
265}
266
267impl<'db> TypeSuperVisitable<DbInterner<'db>> for Const<'db> {
268    fn super_visit_with<V: rustc_type_ir::TypeVisitor<DbInterner<'db>>>(
269        &self,
270        visitor: &mut V,
271    ) -> V::Result {
272        match self.kind() {
273            ConstKind::Unevaluated(uv) => uv.visit_with(visitor),
274            ConstKind::Value(v) => v.visit_with(visitor),
275            ConstKind::Expr(e) => e.visit_with(visitor),
276            ConstKind::Error(e) => e.visit_with(visitor),
277
278            ConstKind::Param(_)
279            | ConstKind::Infer(_)
280            | ConstKind::Bound(..)
281            | ConstKind::Placeholder(_) => V::Result::output(),
282        }
283    }
284}
285
286impl<'db> TypeFoldable<DbInterner<'db>> for Const<'db> {
287    fn try_fold_with<F: rustc_type_ir::FallibleTypeFolder<DbInterner<'db>>>(
288        self,
289        folder: &mut F,
290    ) -> Result<Self, F::Error> {
291        folder.try_fold_const(self)
292    }
293    fn fold_with<F: rustc_type_ir::TypeFolder<DbInterner<'db>>>(self, folder: &mut F) -> Self {
294        folder.fold_const(self)
295    }
296}
297
298impl<'db> TypeSuperFoldable<DbInterner<'db>> for Const<'db> {
299    fn try_super_fold_with<F: rustc_type_ir::FallibleTypeFolder<DbInterner<'db>>>(
300        self,
301        folder: &mut F,
302    ) -> Result<Self, F::Error> {
303        let kind = match self.kind() {
304            ConstKind::Unevaluated(uv) => ConstKind::Unevaluated(uv.try_fold_with(folder)?),
305            ConstKind::Value(v) => ConstKind::Value(v.try_fold_with(folder)?),
306            ConstKind::Expr(e) => ConstKind::Expr(e.try_fold_with(folder)?),
307
308            ConstKind::Param(_)
309            | ConstKind::Infer(_)
310            | ConstKind::Bound(..)
311            | ConstKind::Placeholder(_)
312            | ConstKind::Error(_) => return Ok(self),
313        };
314        if kind != self.kind() { Ok(Const::new(folder.cx(), kind)) } else { Ok(self) }
315    }
316    fn super_fold_with<F: rustc_type_ir::TypeFolder<DbInterner<'db>>>(
317        self,
318        folder: &mut F,
319    ) -> Self {
320        let kind = match self.kind() {
321            ConstKind::Unevaluated(uv) => ConstKind::Unevaluated(uv.fold_with(folder)),
322            ConstKind::Value(v) => ConstKind::Value(v.fold_with(folder)),
323            ConstKind::Expr(e) => ConstKind::Expr(e.fold_with(folder)),
324
325            ConstKind::Param(_)
326            | ConstKind::Infer(_)
327            | ConstKind::Bound(..)
328            | ConstKind::Placeholder(_)
329            | ConstKind::Error(_) => return self,
330        };
331        if kind != self.kind() { Const::new(folder.cx(), kind) } else { self }
332    }
333}
334
335impl<'db> Relate<DbInterner<'db>> for Const<'db> {
336    fn relate<R: rustc_type_ir::relate::TypeRelation<DbInterner<'db>>>(
337        relation: &mut R,
338        a: Self,
339        b: Self,
340    ) -> rustc_type_ir::relate::RelateResult<DbInterner<'db>, Self> {
341        relation.consts(a, b)
342    }
343}
344
345impl<'db> Flags for Const<'db> {
346    fn flags(&self) -> rustc_type_ir::TypeFlags {
347        self.inner().flags
348    }
349
350    fn outer_exclusive_binder(&self) -> rustc_type_ir::DebruijnIndex {
351        self.inner().outer_exclusive_binder
352    }
353}
354
355impl<'db> rustc_type_ir::inherent::Const<DbInterner<'db>> for Const<'db> {
356    fn new_infer(interner: DbInterner<'db>, var: InferConst) -> Self {
357        Const::new(interner, ConstKind::Infer(var))
358    }
359
360    fn new_var(interner: DbInterner<'db>, var: ConstVid) -> Self {
361        Const::new(interner, ConstKind::Infer(InferConst::Var(var)))
362    }
363
364    fn new_bound(interner: DbInterner<'db>, debruijn: DebruijnIndex, var: BoundConst<'db>) -> Self {
365        Const::new(interner, ConstKind::Bound(BoundVarIndexKind::Bound(debruijn), var))
366    }
367
368    fn new_anon_bound(interner: DbInterner<'db>, debruijn: DebruijnIndex, var: BoundVar) -> Self {
369        Const::new(
370            interner,
371            ConstKind::Bound(BoundVarIndexKind::Bound(debruijn), BoundConst::new(var)),
372        )
373    }
374
375    fn new_canonical_bound(interner: DbInterner<'db>, var: BoundVar) -> Self {
376        Const::new(interner, ConstKind::Bound(BoundVarIndexKind::Canonical, BoundConst::new(var)))
377    }
378
379    fn new_placeholder(interner: DbInterner<'db>, param: PlaceholderConst<'db>) -> Self {
380        Const::new(interner, ConstKind::Placeholder(param))
381    }
382
383    fn new_unevaluated(
384        interner: DbInterner<'db>,
385        uv: rustc_type_ir::UnevaluatedConst<DbInterner<'db>>,
386    ) -> Self {
387        Const::new(interner, ConstKind::Unevaluated(uv))
388    }
389
390    fn new_expr(interner: DbInterner<'db>, expr: ExprConst) -> Self {
391        Const::new(interner, ConstKind::Expr(expr))
392    }
393
394    fn new_error(interner: DbInterner<'db>, _guar: ErrorGuaranteed) -> Self {
395        Const::error(interner)
396    }
397}
398
399pub type BoundConst<'db> = rustc_type_ir::BoundConst<DbInterner<'db>>;
400
401impl<'db> Relate<DbInterner<'db>> for ExprConst {
402    fn relate<R: rustc_type_ir::relate::TypeRelation<DbInterner<'db>>>(
403        _relation: &mut R,
404        a: Self,
405        b: Self,
406    ) -> rustc_type_ir::relate::RelateResult<DbInterner<'db>, Self> {
407        // Ensure we get back to this when we fill in the fields
408        let ExprConst = b;
409        Ok(a)
410    }
411}
412
413impl<'db> rustc_type_ir::inherent::ExprConst<DbInterner<'db>> for ExprConst {
414    fn args(self) -> <DbInterner<'db> as rustc_type_ir::Interner>::GenericArgs {
415        // Ensure we get back to this when we fill in the fields
416        let ExprConst = self;
417        GenericArgs::default()
418    }
419}
420
421interned_slice!(ConstsStorage, Consts, StoredConsts, consts, Const<'db>, Const<'static>);
422impl_foldable_for_interned_slice!(Consts);