Skip to main content

incin_core/shapes/
reshape.rs

1//! Compile-time shape reshaping and element count verification.
2use crate::shapes::shape::{ShapeArgs, ShapeSpec};
3use crate::shapes::{DynShape, Shape, ShapeValue};
4use core::ops::Mul;
5use typenum::{Prod, U1, Unsigned};
6
7/// Computes the total number of elements in a static shape.
8pub trait ElementCount {
9    /// `Count`.
10    type Count: typenum::Unsigned;
11}
12
13impl ElementCount for crate::shapes::Nil {
14    type Count = U1;
15}
16
17/// Type-level product fold for the canonical recursive shape representation.
18/// This is the arbitrary-rank counterpart of the old tuple ladder.
19impl<H, T> ElementCount for crate::shapes::DimCons<H, T>
20where
21    H: crate::shapes::ConcreteStaticExtent,
22    T: crate::shapes::Shape + ElementCount,
23    H::Nat: Mul<<T as ElementCount>::Count>,
24    Prod<H::Nat, <T as ElementCount>::Count>: Unsigned,
25{
26    type Count = Prod<H::Nat, <T as ElementCount>::Count>;
27}
28
29/// Witness that two type-level element counts are identical. Implemented
30/// reflexively - only `SameCount<N>` for the *same* `N` exists - so
31/// requiring `A: SameCount<B>` is a compile-time assertion that `A == B`,
32/// but one that fails as an unsatisfied trait bound (E0277) rather than an
33/// associated-type projection mismatch (E0271). `#[diagnostic::
34/// on_unimplemented]` can only decorate E0277; routing the comparison
35/// through this bound (instead of `ElementCount<Count = ...>` equality
36/// directly) is what makes the reshape mismatch below render as a labeled,
37/// call-site-anchored message instead of a raw `UInt<...>` projection wall.
38#[diagnostic::on_unimplemented(
39    message = "Cannot reshape: source has {Self} elements but the target shape has {Rhs} elements",
40    label = "element count changes here",
41    note = "reshape must preserve the total number of elements"
42)]
43pub trait SameCount<Rhs> {}
44impl<N> SameCount<N> for N {}
45
46/// A trait that guarantees two shapes have the exact same number of elements at compile-time.
47#[diagnostic::on_unimplemented(
48    message = "Cannot reshape from `{Self}` to `{Target}`",
49    label = "element count mismatch for reshape",
50    note = "reshape requires the total number of elements to remain constant"
51)]
52/// `ReshapeShape`.
53pub trait ReshapeShape<Target: Shape>: Shape {}
54
55// Blanket implementation for any two static shapes that share the exact same ElementCount.
56impl<S1, S2> ReshapeShape<S2> for S1
57where
58    S1: Shape + ElementCount,
59    S2: Shape + ElementCount,
60    <S1 as ElementCount>::Count: SameCount<<S2 as ElementCount>::Count>,
61{
62}
63
64/// A hybrid trait for dynamic and partial dynamic reshaping.
65pub trait TryReshape<Target: Shape>: Shape {}
66
67// Any pair of dynamic shapes can attempt to reshape at runtime.
68impl<S1: DynShape, S2: DynShape> TryReshape<S2> for S1 {}
69
70/// Shape specifications accepted by the ergonomic `Tensor::reshape` API.
71///
72/// Fully static [`ShapeValue`] inputs retain the compile-time element-count
73/// proof. Runtime [`ShapeArgs`], arrays, and vectors use the checked runtime
74/// path because their dimensions are not known to the type system.
75pub trait ReshapeSpec<Source: Shape>: ShapeSpec {}
76
77impl<Source, Target> ReshapeSpec<Source> for ShapeValue<Target>
78where
79    Source: Shape + ReshapeShape<Target>,
80    Target: Shape + DynShape,
81{
82}
83
84impl<Source, Target> ReshapeSpec<Source> for ShapeArgs<Target>
85where
86    Source: DynShape,
87    Target: Shape + DynShape,
88{
89}
90
91impl<Source, const N: usize> ReshapeSpec<Source> for [usize; N] where Source: DynShape {}
92
93impl<Source> ReshapeSpec<Source> for alloc::vec::Vec<usize> where Source: DynShape {}
94
95impl<Source> ReshapeSpec<Source> for &[usize] where Source: DynShape {}
96
97#[cfg(test)]
98/// `tests`.
99mod tests {
100    use super::*;
101    use typenum::{U2, U4, U8};
102
103    /// `assert_reshape_eq`.
104    fn assert_reshape_eq<S1, S2: Shape>()
105    where
106        S1: Shape + ReshapeShape<S2>,
107    {
108    }
109
110    #[test]
111    /// `reshape_same_rank_same_numel`.
112    fn reshape_same_rank_same_numel() {
113        /// `S1`.
114        type S1 = crate::shapes::DimCons<U2, crate::shapes::DimCons<U8, crate::shapes::Nil>>;
115        /// `S2`.
116        type S2 = crate::shapes::DimCons<U4, crate::shapes::DimCons<U4, crate::shapes::Nil>>;
117        assert_reshape_eq::<S1, S2>();
118    }
119
120    #[test]
121    /// `reshape_different_rank_same_numel`.
122    fn reshape_different_rank_same_numel() {
123        /// `S1`.
124        type S1 = crate::shapes::DimCons<
125            U2,
126            crate::shapes::DimCons<U2, crate::shapes::DimCons<U4, crate::shapes::Nil>>,
127        >;
128        /// `S2`.
129        type S2 = crate::shapes::DimCons<U4, crate::shapes::DimCons<U4, crate::shapes::Nil>>;
130        assert_reshape_eq::<S1, S2>();
131    }
132}