use typenum::{Bit, UInt, UTerm, Unsigned};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StaticExtent {
RuntimeUnknown,
Value(usize),
Invalid,
}
impl StaticExtent {
#[inline(always)]
pub const fn value(self) -> Option<usize> {
match self {
StaticExtent::Value(value) => Some(value),
StaticExtent::RuntimeUnknown | StaticExtent::Invalid => None,
}
}
#[inline(always)]
pub const fn validate_size(self, size: usize) -> bool {
match self {
StaticExtent::Value(val) => size == val,
StaticExtent::RuntimeUnknown => true,
StaticExtent::Invalid => false,
}
}
}
mod sealed {
pub trait Dim {}
pub trait ConcreteStaticExtent {}
}
pub trait Dim:
sealed::Dim + 'static + Copy + Clone + core::fmt::Debug + Send + Sync + Eq + PartialEq
{
type KeepDim: Dim;
const STATIC_SIZE: bool = matches!(Self::STATIC, StaticExtent::Value(_));
const STATIC_VALID: () = {
if matches!(Self::STATIC, StaticExtent::Invalid) {
panic!("invalid static dimension expression");
}
};
const STATIC: StaticExtent = StaticExtent::RuntimeUnknown;
const NAME: Option<&'static str> = None;
#[inline]
fn matches_tag<Tag: AxisTag>() -> bool {
false
}
#[inline]
fn static_extent(&self) -> StaticExtent {
Self::STATIC
}
#[inline]
fn static_size() -> Result<usize, crate::shapes::error::ShapeError> {
Self::STATIC
.value()
.ok_or(crate::shapes::error::ShapeError::TargetShapeRejected {
operation: crate::shapes::error::OperationKind::Storage,
rank: 1,
})
}
type Arg: Clone + Default + core::fmt::Debug;
#[inline]
fn resolve_arg(
_arg: Self::Arg,
) -> core::result::Result<usize, crate::shapes::error::ShapeError> {
match Self::STATIC {
StaticExtent::Invalid => Err(crate::shapes::error::ShapeError::TargetShapeRejected {
operation: crate::shapes::error::OperationKind::Storage,
rank: 1,
}),
StaticExtent::Value(value) => {
if Self::validate_size(value) {
Ok(value)
} else {
Err(crate::shapes::error::ShapeError::TargetShapeRejected {
operation: crate::shapes::error::OperationKind::Storage,
rank: 1,
})
}
}
StaticExtent::RuntimeUnknown => {
Err(crate::shapes::error::ShapeError::TargetShapeRejected {
operation: crate::shapes::error::OperationKind::Storage,
rank: 1,
})
}
}
}
#[inline]
fn validate_size(size: usize) -> bool {
Self::STATIC.validate_size(size)
}
}
pub trait ConcreteStaticExtent: Dim + sealed::ConcreteStaticExtent {
type Nat: typenum::Unsigned;
}
impl<L: Dim, R: Dim> sealed::Dim for BroadcastExtent<L, R> {}
impl sealed::Dim for usize {}
impl<const N: usize> sealed::Dim for ConstDim<N> {}
impl<Tag: AxisTag, Extent: Dim> sealed::Dim for NamedDim<Tag, Extent> {}
impl<A: Dim, B: Dim> sealed::Dim for AddDim<A, B> {}
impl<A: Dim, B: Dim> sealed::Dim for CheckedSubDim<A, B> {}
impl<A: Dim, B: Dim> sealed::Dim for ExactDivDim<A, B> {}
impl<A: Dim, B: Dim> sealed::Dim for MulDim<A, B> {}
impl sealed::Dim for UTerm {}
impl<U, B> sealed::Dim for UInt<U, B>
where
U: Unsigned + Dim,
B: Bit + Default + Copy + Clone + core::fmt::Debug + Send + Sync + Eq + PartialEq + 'static,
UInt<U, B>: Unsigned
+ Default
+ Copy
+ Clone
+ core::fmt::Debug
+ Send
+ Sync
+ Eq
+ PartialEq
+ 'static,
{
}
impl<T> sealed::ConcreteStaticExtent for T where T: Dim + typenum::Unsigned {}
impl<Tag: AxisTag, Extent: ConcreteStaticExtent> sealed::ConcreteStaticExtent
for NamedDim<Tag, Extent>
{
}
impl<L, R> sealed::ConcreteStaticExtent for BroadcastExtent<L, R>
where
L: Dim + ConcreteStaticExtent,
R: Dim + ConcreteStaticExtent,
{
}
#[doc(hidden)]
pub trait BroadcastChoice<WhenOne, WhenZero> {
type Output;
}
impl<WhenOne, WhenZero> BroadcastChoice<WhenOne, WhenZero> for typenum::B1 {
type Output = WhenOne;
}
impl<WhenOne, WhenZero> BroadcastChoice<WhenOne, WhenZero> for typenum::B0 {
type Output = WhenZero;
}
#[doc(hidden)]
pub type BroadcastSameNat<L, R> =
<<L as typenum::IsEqual<R>>::Output as BroadcastChoice<L, ()>>::Output;
#[doc(hidden)]
pub type BroadcastRightNat<L, R> =
<<R as typenum::IsEqual<typenum::U1>>::Output as BroadcastChoice<L, BroadcastSameNat<L, R>>>::Output;
#[doc(hidden)]
pub type BroadcastStaticNat<L, R> =
<<L as typenum::IsEqual<typenum::U1>>::Output as BroadcastChoice<R, BroadcastRightNat<L, R>>>::Output;
impl<L, R> ConcreteStaticExtent for BroadcastExtent<L, R>
where
L: Dim + ConcreteStaticExtent,
R: Dim + ConcreteStaticExtent,
L::Nat: typenum::Unsigned + typenum::IsEqual<typenum::U1> + typenum::IsEqual<R::Nat>,
R::Nat: typenum::Unsigned + typenum::IsEqual<typenum::U1>,
<L::Nat as typenum::IsEqual<typenum::U1>>::Output:
BroadcastChoice<R::Nat, BroadcastRightNat<L::Nat, R::Nat>>,
<R::Nat as typenum::IsEqual<typenum::U1>>::Output:
BroadcastChoice<L::Nat, BroadcastSameNat<L::Nat, R::Nat>>,
<L::Nat as typenum::IsEqual<R::Nat>>::Output: BroadcastChoice<L::Nat, ()>,
BroadcastStaticNat<L::Nat, R::Nat>: typenum::Unsigned,
{
type Nat = BroadcastStaticNat<L::Nat, R::Nat>;
}
impl<T> ConcreteStaticExtent for T
where
T: Dim + typenum::Unsigned,
{
type Nat = T;
}
pub trait AxisTag:
'static + Copy + Clone + core::fmt::Debug + Send + Sync + Eq + PartialEq
{
const NAME: &'static str;
fn key() -> AxisKey;
#[inline]
fn selector() -> crate::shapes::idx::NamedAxisSelector<Self>
where
Self: Sized,
{
crate::shapes::idx::NamedAxisSelector::default()
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct AxisKey {
schema: &'static str,
name: &'static str,
}
impl AxisKey {
pub const fn new(schema: &'static str, name: &'static str) -> Self {
Self { schema, name }
}
pub const fn schema(self) -> &'static str {
self.schema
}
pub const fn name(self) -> &'static str {
self.name
}
pub fn qualified(self) -> alloc::string::String {
alloc::format!("{}::{}", self.schema, self.name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct AxisSchema<Root>(core::marker::PhantomData<Root>);
pub trait AxisIdentity: AxisTag {
type Schema: 'static;
type Id: typenum::Unsigned;
}
pub trait DimCompatible<Rhs: Dim>: Dim {
const STATIC_ASSERT: () = match (Self::STATIC, Rhs::STATIC) {
(StaticExtent::Invalid, _) | (_, StaticExtent::Invalid) => {
panic!("Invalid static dimension expression");
}
(StaticExtent::Value(lhs), StaticExtent::Value(rhs)) => {
assert!(lhs == rhs, "Statically incompatible dimensions");
}
_ => (),
};
fn check_compatible(&self, _rhs: &Rhs) -> Result<(), crate::shapes::error::ShapeError> {
Self::STATIC_ASSERT;
Ok(())
}
}
impl<L: Dim, R: Dim> DimCompatible<R> for L {}
const fn broadcast_static(lhs: StaticExtent, rhs: StaticExtent) -> StaticExtent {
match (lhs, rhs) {
(StaticExtent::Invalid, _) | (_, StaticExtent::Invalid) => StaticExtent::Invalid,
(StaticExtent::Value(lhs), StaticExtent::Value(rhs)) => {
if lhs == rhs {
StaticExtent::Value(lhs)
} else if lhs == 1 {
StaticExtent::Value(rhs)
} else if rhs == 1 {
StaticExtent::Value(lhs)
} else {
StaticExtent::Invalid
}
}
(StaticExtent::Value(1), other) | (other, StaticExtent::Value(1)) => other,
(StaticExtent::Value(value), StaticExtent::RuntimeUnknown)
| (StaticExtent::RuntimeUnknown, StaticExtent::Value(value)) => {
if value == 1 {
StaticExtent::RuntimeUnknown
} else {
StaticExtent::Value(value)
}
}
_ => StaticExtent::RuntimeUnknown,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct BroadcastExtent<L, R>(pub core::marker::PhantomData<(L, R)>);
impl<L: Dim, R: Dim> Dim for BroadcastExtent<L, R> {
type KeepDim = typenum::U1;
const STATIC: StaticExtent = broadcast_static(L::STATIC, R::STATIC);
type Arg = usize;
fn resolve_arg(
arg: Self::Arg,
) -> core::result::Result<usize, crate::shapes::error::ShapeError> {
match Self::STATIC {
StaticExtent::Invalid => Err(crate::shapes::error::ShapeError::TargetShapeRejected {
operation: crate::shapes::error::OperationKind::Storage,
rank: 1,
}),
StaticExtent::Value(value) if value == arg => Ok(value),
StaticExtent::Value(_) => Err(crate::shapes::error::ShapeError::TargetShapeRejected {
operation: crate::shapes::error::OperationKind::Storage,
rank: 1,
}),
StaticExtent::RuntimeUnknown => Ok(arg),
}
}
}
impl Dim for usize {
type KeepDim = typenum::U1;
type Arg = Self;
fn resolve_arg(
arg: Self::Arg,
) -> core::result::Result<usize, crate::shapes::error::ShapeError> {
Ok(arg)
}
}
#[macro_export]
macro_rules! dim {
($( $(#[$meta:meta])* $name:ident ),+ $(,)?) => {
$crate::__incin_dim_declare!(@first $( $(#[$meta])* $name ),+ );
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __incin_dim_declare {
(@first $(#[$first_meta:meta])* $first:ident $(, $(#[$rest_meta:meta])* $rest:ident)* ) => {
$(#[$first_meta])*
#[doc = concat!("Named dimension `", stringify!($first), "`.")]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct $first;
impl $crate::shapes::AxisTag for $first {
const NAME: &'static str = stringify!($first);
fn key() -> $crate::shapes::AxisKey {
$crate::shapes::AxisKey::new(stringify!($first), stringify!($first))
}
}
impl $crate::shapes::AxisIdentity for $first {
type Schema = $crate::shapes::AxisSchema<$first>;
type Id = $crate::typenum::U0;
}
$crate::__incin_dim_declare!(@rest $crate::shapes::AxisSchema<$first>; stringify!($first); $crate::typenum::U1; $( $(#[$rest_meta])* $rest ),* );
};
(@rest $schema:ty; $schema_name:expr; $id:ty; ) => {};
(@rest $schema:ty; $schema_name:expr; $id:ty; $(#[$meta:meta])* $name:ident $(, $(#[$rest_meta:meta])* $rest:ident)* ) => {
$(#[$meta])*
#[doc = concat!("Named dimension `", stringify!($name), "`.")]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct $name;
impl $crate::shapes::AxisTag for $name {
const NAME: &'static str = stringify!($name);
fn key() -> $crate::shapes::AxisKey {
$crate::shapes::AxisKey::new($schema_name, stringify!($name))
}
}
impl $crate::shapes::AxisIdentity for $name {
type Schema = $schema;
type Id = $id;
}
$crate::__incin_dim_declare!(@rest $schema; $schema_name; $crate::typenum::Sum<$id, $crate::typenum::U1>; $( $(#[$rest_meta])* $rest ),* );
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct ConstDim<const N: usize>;
impl<const N: usize> Dim for ConstDim<N> {
type KeepDim = typenum::U1;
const STATIC: StaticExtent = StaticExtent::Value(N);
type Arg = ();
}
macro_rules! static_op {
($( $id1:ident $id2:ident )+) => {
$(
const fn $id1(lhs: StaticExtent, rhs: StaticExtent) -> StaticExtent {
match (lhs, rhs) {
(StaticExtent::Invalid, _) | (_, StaticExtent::Invalid) => StaticExtent::Invalid,
(StaticExtent::Value(lhs), StaticExtent::Value(rhs)) => match lhs.$id2(rhs) {
Some(v) => StaticExtent::Value(v),
None => StaticExtent::Invalid,
},
_ => StaticExtent::RuntimeUnknown,
}
}
)+
};
}
static_op! {
static_add checked_add
static_sub checked_sub
}
const fn static_exact_div(lhs: StaticExtent, rhs: StaticExtent) -> StaticExtent {
match (lhs, rhs) {
(StaticExtent::Invalid, _)
| (_, StaticExtent::Invalid)
| (StaticExtent::Value(_), StaticExtent::Value(0)) => StaticExtent::Invalid,
(StaticExtent::Value(lhs), StaticExtent::Value(rhs)) => {
if lhs % rhs == 0 {
StaticExtent::Value(lhs / rhs)
} else {
StaticExtent::Invalid
}
}
_ => StaticExtent::RuntimeUnknown,
}
}
macro_rules! static_op_dim {
( $name:ident $op:ident $symbolic:ident) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct $name<A, B>(pub core::marker::PhantomData<(A, B)>);
impl<A: Dim, B: Dim> Dim for $name<A, B> {
type KeepDim = typenum::U1;
const STATIC: StaticExtent = $op(A::STATIC, B::STATIC);
type Arg = usize;
fn resolve_arg(
arg: Self::Arg,
) -> core::result::Result<usize, crate::shapes::error::ShapeError> {
match Self::STATIC {
StaticExtent::Invalid => {
Err(crate::shapes::error::ShapeError::TargetShapeRejected {
operation: crate::shapes::error::OperationKind::Storage,
rank: 1,
})
}
StaticExtent::Value(value) if value == arg => Ok(value),
StaticExtent::Value(_) => {
Err(crate::shapes::error::ShapeError::TargetShapeRejected {
operation: crate::shapes::error::OperationKind::Storage,
rank: 1,
})
}
StaticExtent::RuntimeUnknown => Ok(arg),
}
}
}
};
}
static_op_dim!( AddDim static_add Add );
static_op_dim!( CheckedSubDim static_sub Sub );
static_op_dim!( ExactDivDim static_exact_div ExactDiv);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct NamedDim<Tag, Extent> {
_tag: core::marker::PhantomData<(Tag, Extent)>,
}
impl<Tag, Extent> ConcreteStaticExtent for NamedDim<Tag, Extent>
where
Tag: AxisTag,
Extent: ConcreteStaticExtent,
{
type Nat = Extent::Nat;
}
impl<Tag: AxisTag, Extent: Dim> NamedDim<Tag, Extent> {
pub const fn new() -> Self {
Self {
_tag: core::marker::PhantomData,
}
}
}
impl<Tag: AxisTag, Extent: Dim> Dim for NamedDim<Tag, Extent> {
type KeepDim = NamedDim<Tag, typenum::U1>;
const STATIC: StaticExtent = Extent::STATIC;
const NAME: Option<&'static str> = Some(Tag::NAME);
type Arg = Extent::Arg;
#[inline]
fn matches_tag<Other: AxisTag>() -> bool {
core::any::TypeId::of::<Tag>() == core::any::TypeId::of::<Other>()
}
fn resolve_arg(
arg: Self::Arg,
) -> core::result::Result<usize, crate::shapes::error::ShapeError> {
Extent::resolve_arg(arg)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct MulDim<A, B>(pub core::marker::PhantomData<(A, B)>);
impl<A: Dim, B: Dim> Dim for MulDim<A, B> {
type KeepDim = typenum::U1;
const STATIC: StaticExtent = match (A::STATIC, B::STATIC) {
(StaticExtent::Value(a), StaticExtent::Value(b)) => match a.checked_mul(b) {
Some(value) => StaticExtent::Value(value),
None => StaticExtent::Invalid,
},
(StaticExtent::Invalid, _) | (_, StaticExtent::Invalid) => StaticExtent::Invalid,
_ => StaticExtent::RuntimeUnknown,
};
type Arg = usize;
fn resolve_arg(
arg: Self::Arg,
) -> core::result::Result<usize, crate::shapes::error::ShapeError> {
match Self::STATIC {
StaticExtent::Invalid => Err(crate::shapes::error::ShapeError::TargetShapeRejected {
operation: crate::shapes::error::OperationKind::Storage,
rank: 1,
}),
StaticExtent::Value(value) if value == arg => Ok(value),
StaticExtent::Value(_) => Err(crate::shapes::error::ShapeError::TargetShapeRejected {
operation: crate::shapes::error::OperationKind::Storage,
rank: 1,
}),
StaticExtent::RuntimeUnknown => Ok(arg),
}
}
}
impl Dim for UTerm {
type KeepDim = typenum::U1;
const STATIC: StaticExtent = StaticExtent::Value(0);
type Arg = ();
}
impl<U, B> Dim for UInt<U, B>
where
U: Unsigned + Dim,
B: Bit + Default + Copy + Clone + core::fmt::Debug + Send + Sync + Eq + PartialEq + 'static,
UInt<U, B>: Unsigned
+ Default
+ Copy
+ Clone
+ core::fmt::Debug
+ Send
+ Sync
+ Eq
+ PartialEq
+ 'static,
{
type KeepDim = typenum::U1;
const STATIC: StaticExtent = StaticExtent::Value(<Self as Unsigned>::USIZE);
type Arg = ();
}