incin-core 0.1.0

Core tensor operations and static shape checking for incin
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
use crate::shapes::{DimCons, NamedDim, Nil, Shape};
use alloc::vec::Vec;

/// A marker type indicating that a reshape dimension should be inferred from the remaining elements.
///
/// When used in an `idx![]` expression, this corresponds to `-1` in Python/NumPy semantics.
/// Only one inferred dimension is allowed per reshape expression.
pub struct InferDim;

/// A marker type indicating that a slice should span the entire extent of a dimension.
///
/// When used in an `idx![]` expression, `..` (or `Ellipsis`) means "take all elements along this axis".
/// This results in a dynamically-sized output dimension (`usize`).
pub struct Ellipsis;

/// A type-level slice spanning the half-open interval `[Start, End)` with known width `Diff`.
///
/// This is generated by the `idx![]` macro when a range literal like `2..5` is used.
/// All three parameters are `typenum::Unsigned` types so the width is a compile-time constant.
///
/// ## Type Parameters
/// * `Start` - The inclusive lower bound (a `typenum::Unsigned`).
/// * `End` - The exclusive upper bound (a `typenum::Unsigned`).
/// * `Diff` - The width of the slice, equal to `End - Start` (a `typenum::Unsigned`).
pub struct Slice<Start, End, Diff> {
    _marker: core::marker::PhantomData<(Start, End, Diff)>,
}

/// A trait for types that can be used as dimension specifiers in the `idx![]` macro for reshaping.
///
/// Implemented by:
/// * `typenum` types (e.g., `U128`) - The dimension is statically known.
/// * `InferDim` - The dimension is computed from the total element count divided by all other known dimensions.
pub trait DimIdx {
    /// The resolved [`Dim`] type in the output shape. `InferDim` resolves to `usize`.
    type Resolved: Dim;

    /// Returns the specified size if known, or `None` if it's `InferDim`.
    fn size() -> Option<usize>;
}

use super::dim::Dim;
use typenum::consts::*;
use typenum::{Bit, UInt, UTerm, Unsigned};

impl DimIdx for UTerm {
    /// `UTerm` (0) resolves to itself.
    type Resolved = UTerm;
    /// Always `Some(0)`.
    fn size() -> Option<usize> {
        Some(0)
    }
}

impl<U, B> DimIdx 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,
{
    /// A known `typenum` size resolves to itself.
    type Resolved = UInt<U, B>;
    /// The compile-time-known size.
    fn size() -> Option<usize> {
        Some(Self::USIZE)
    }
}

impl DimIdx for InferDim {
    /// Resolves to a runtime-computed `usize`.
    type Resolved = usize;
    /// Always `None` - the size is inferred from the other dimensions.
    fn size() -> Option<usize> {
        None
    }
}

// A named runtime extent is a normal canonical `NamedDim`; its semantic tag
// does not change reshape's runtime inference rules.
impl<Tag: crate::shapes::AxisTag> DimIdx for NamedDim<Tag, usize> {
    type Resolved = NamedDim<Tag, usize>;
    fn size() -> Option<usize> {
        None
    }
}

/// Computes the new shape resulting from a reshape.
#[diagnostic::on_unimplemented(
    message = "Cannot reshape dimension into `{Self}`",
    label = "Invalid dimension for reshape",
    note = "The element count must remain constant during reshape"
)]
pub trait ReshapeTarget<In: Shape> {
    /// The resolved output shape (each `DimIdx` entry resolved, with at
    /// most one `InferDim` inferred from the remaining element count).
    type Output: Shape;
    /// Computes the concrete output dimensions from the input's runtime shape.
    fn calculate_shape(
        in_shape_vec: &[usize],
    ) -> core::result::Result<Vec<usize>, crate::shapes::error::ShapeError>;
}

/// Internal recursive collector for structural reshape targets.
#[doc(hidden)]
pub trait ReshapeTargetSpec {
    type Output: Shape;

    fn collect(
        sizes: &mut Vec<usize>,
        inferred: &mut Option<usize>,
    ) -> core::result::Result<(), crate::shapes::error::ShapeError>;
}

impl ReshapeTargetSpec for Nil {
    type Output = Nil;

    fn collect(
        _sizes: &mut Vec<usize>,
        _inferred: &mut Option<usize>,
    ) -> core::result::Result<(), crate::shapes::error::ShapeError> {
        Ok(())
    }
}

impl<D: DimIdx, T: ReshapeTargetSpec> ReshapeTargetSpec for DimCons<D, T>
where
    D::Resolved: Dim,
{
    type Output = DimCons<D::Resolved, T::Output>;

    fn collect(
        sizes: &mut Vec<usize>,
        inferred: &mut Option<usize>,
    ) -> core::result::Result<(), crate::shapes::error::ShapeError> {
        let index = sizes.len();
        if let Some(size) = D::size() {
            sizes.push(size);
        } else {
            if inferred.is_some() {
                return Err(crate::shapes::error::ShapeError::InvalidParameter {
                    operation: crate::shapes::error::OperationKind::Reshape,
                    parameter: "inferred dimensions",
                    value: 2,
                });
            }
            *inferred = Some(index);
            sizes.push(0);
        }
        T::collect(sizes, inferred)
    }
}

impl<In: Shape, Target: ReshapeTargetSpec> ReshapeTarget<In> for Target {
    type Output = Target::Output;

    fn calculate_shape(
        in_shape_vec: &[usize],
    ) -> core::result::Result<Vec<usize>, crate::shapes::error::ShapeError> {
        let total_elements = crate::shapes::ShapeBuf::from_slice(in_shape_vec)
            .checked_numel(crate::shapes::error::OperationKind::Reshape)?;
        let mut sizes = Vec::new();
        let mut inferred = None;
        Target::collect(&mut sizes, &mut inferred)?;
        if let Some(index) = inferred {
            let known_product = sizes
                .iter()
                .enumerate()
                .filter(|(i, _)| *i != index)
                .try_fold(1usize, |product, (_, &size)| product.checked_mul(size))
                .ok_or(crate::shapes::error::ShapeError::ArithmeticOverflow {
                    operation: crate::shapes::error::OperationKind::Reshape,
                    expression: "product of specified reshape dimensions",
                })?;
            if known_product == 0 {
                sizes[index] = 0;
            } else if !total_elements.is_multiple_of(known_product) {
                return Err(crate::shapes::error::ShapeError::DimensionMismatch {
                    operation: crate::shapes::error::OperationKind::Reshape,
                    axis: crate::shapes::error::Axis::Index(index),
                    lhs: total_elements,
                    rhs: known_product,
                    constraint: crate::shapes::error::DimensionConstraint::DivisibleBy,
                });
            } else {
                sizes[index] = total_elements / known_product;
            }
        }
        Ok(sizes)
    }
}

/// A trait for types that describe a slicing operation along a single tensor axis in the `idx![]` macro.
///
/// Implementors include:
/// * [`Slice<Start, End, Diff<End, Start>>`] \u2014 A half-open range, e.g. `idx![1..3]` on an axis of size 10 yields 2 elements.
/// * `typenum` types \u2014 Selects a single index, reducing the rank by 1 in the output.
/// * [`Ellipsis`] \u2014 Selects the full axis extent; output dimension becomes `usize` (dynamic).
pub trait SliceIdx {
    /// The resolved [`Dim`] type in the output shape after this slice is applied.
    type Resolved: Dim;

    /// Computes the `(start, end)` indices for a dimension of the given `size`.
    fn bounds(size: usize) -> (usize, usize);
}

impl<Start: Unsigned, End: Unsigned, Diff: Dim> SliceIdx for Slice<Start, End, Diff> {
    /// The slice's known width.
    type Resolved = Diff;
    /// The compile-time-known `(Start, End)` bounds, ignoring the actual
    /// dimension size.
    fn bounds(_size: usize) -> (usize, usize) {
        (Start::USIZE, End::USIZE)
    }
}

impl SliceIdx for UTerm {
    /// A bare index selects a single element, reducing this axis to size 1.
    type Resolved = U1;
    /// Selects index `0`.
    fn bounds(_size: usize) -> (usize, usize) {
        (0, 1)
    }
}

impl<U, B> SliceIdx 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,
{
    /// A bare index selects a single element, reducing this axis to size 1.
    type Resolved = U1;
    /// Selects the index encoded by this `typenum` value.
    fn bounds(_size: usize) -> (usize, usize) {
        (Self::USIZE, Self::USIZE + 1)
    }
}

// Ellipsis represents taking the full dimension for all remaining dims.
// We can't easily implement a variadic Ellipsis in simple tuple traits without
// advanced macro work. For now, we assume `..` is a single full dimension slice.
impl SliceIdx for Ellipsis {
    /// Dynamic size, since it depends on the input.
    type Resolved = usize;
    /// Selects the entire axis, `[0, size)`.
    fn bounds(size: usize) -> (usize, usize) {
        (0, size)
    }
}

#[diagnostic::on_unimplemented(
    message = "Cannot slice dimension with `{Self}`",
    label = "Invalid slice target",
    note = "The slice range must be within the bounds of the original dimension"
)]
/// Computes the output shape resulting from an `idx![]` slice expression.
pub trait SliceTarget<In: Shape> {
    /// The resolved output shape after applying each dimension's `SliceIdx`.
    type Output: Shape;
    /// Returns the bounds (start, end) for each dimension in `in_shape_vec`
    fn calculate_bounds(in_shape_vec: &[usize]) -> Vec<(usize, usize)>;
}

#[doc(hidden)]
pub trait SliceSpec {
    type Output: Shape;
    fn collect(input: &[usize], axis: &mut usize, output: &mut Vec<(usize, usize)>);
}

impl SliceSpec for Nil {
    type Output = Nil;
    fn collect(_input: &[usize], _axis: &mut usize, _output: &mut Vec<(usize, usize)>) {}
}

impl<D: SliceIdx, T: SliceSpec> SliceSpec for DimCons<D, T>
where
    D::Resolved: Dim,
{
    type Output = DimCons<D::Resolved, T::Output>;
    fn collect(input: &[usize], axis: &mut usize, output: &mut Vec<(usize, usize)>) {
        let size = input.get(*axis).copied().unwrap_or(0);
        output.push(D::bounds(size));
        *axis += 1;
        T::collect(input, axis, output);
    }
}

impl<In: Shape, Target: SliceSpec> SliceTarget<In> for Target {
    type Output = Target::Output;
    fn calculate_bounds(in_shape_vec: &[usize]) -> Vec<(usize, usize)> {
        let mut bounds = Vec::new();
        let mut axis = 0;
        Target::collect(in_shape_vec, &mut axis, &mut bounds);
        bounds
    }
}

/// Structural cursor for axis 0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct Here;

impl Here {
    /// Resolves this selector against a concrete rank.
    pub fn normalize(&self, rank: usize) -> crate::err::Result<Vec<usize>> {
        AxisSelector::new(&[0]).normalize(rank)
    }
}

/// Structural cursor for axis `I + 1`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct Next<I>(pub core::marker::PhantomData<I>);

impl<I> Next<I> {
    /// Default next-position selector.
    pub const DEFAULT: Self = Next(core::marker::PhantomData);

    /// Resolves this selector against a concrete rank.
    pub fn normalize(&self, rank: usize) -> crate::err::Result<Vec<usize>>
    where
        Self: StaticCursor,
    {
        AxisSelector::new(&[<Next<I> as StaticCursor>::INDEX]).normalize(rank)
    }
}

/// Structural cursor for axis counting from end `-(I + 1)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct FromEnd<I>(pub core::marker::PhantomData<I>);

impl<I> FromEnd<I> {
    /// Default from-end selector instance.
    pub const DEFAULT: Self = FromEnd(core::marker::PhantomData);
}

impl<I: StaticCursor> FromEnd<I> {
    /// Next-from-end signed index.
    pub const INDEX: isize = -(1 + I::INDEX);

    /// Resolves this selector against a concrete rank.
    pub fn normalize(&self, rank: usize) -> crate::err::Result<Vec<usize>> {
        AxisSelector::new(&[Self::INDEX]).normalize(rank)
    }
}

/// Trait for static axis cursors with compile-time evaluated signed index.
pub trait StaticCursor:
    'static + Copy + Clone + core::fmt::Debug + Send + Sync + Eq + PartialEq
{
    /// Signed index this cursor contributes.
    const INDEX: isize;
}

/// Compile-time axis cursor accepted by structural reduction helpers.
/// Unlike `StaticCursor`, this also includes cursors counted from the end.
pub trait AxisCursor:
    'static + Copy + Clone + core::fmt::Debug + Send + Sync + Eq + PartialEq
{
    /// Signed index this cursor contributes.
    const INDEX: isize;
}

impl<I: StaticCursor> AxisCursor for I {
    const INDEX: isize = I::INDEX;
}

impl<I: StaticCursor> AxisCursor for FromEnd<I> {
    const INDEX: isize = FromEnd::<I>::INDEX;
}

impl StaticCursor for Here {
    const INDEX: isize = 0;
}

impl<I: StaticCursor> StaticCursor for Next<I> {
    const INDEX: isize = 1 + I::INDEX;
}

/// Value-level spelling of a compile-time axis cursor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct StaticAxis<I: StaticCursor>(core::marker::PhantomData<I>);

impl<I: StaticCursor> StaticAxis<I> {
    /// Default selector instance.
    pub const DEFAULT: Self = Self(core::marker::PhantomData);

    /// Resolves this selector against a concrete rank.
    pub fn normalize(&self, rank: usize) -> crate::err::Result<Vec<usize>> {
        AxisSelector::new(&[I::INDEX]).normalize(rank)
    }
}

/// A forward static axis value emitted by `axis!`.  The distinct wrapper keeps
/// forward and from-end selector dispatch disjoint for the trait solver.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct ForwardAxis<I: crate::shapes::shape::ForwardCursor>(core::marker::PhantomData<I>);

impl<I: crate::shapes::shape::ForwardCursor> ForwardAxis<I> {
    /// Default forward selector instance.
    pub const DEFAULT: Self = ForwardAxis(core::marker::PhantomData);

    /// Resolves this selector against a concrete rank.
    pub fn normalize(&self, rank: usize) -> crate::err::Result<Vec<usize>> {
        AxisSelector::new(&[I::INDEX]).normalize(rank)
    }
}

/// A from-end static axis value emitted by `axis!`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct ReverseAxis<I: StaticCursor>(core::marker::PhantomData<I>);

impl<I: StaticCursor> ReverseAxis<I> {
    /// Default reverse selector instance.
    pub const DEFAULT: Self = ReverseAxis(core::marker::PhantomData);

    /// Resolves this selector against a concrete rank.
    pub fn normalize(&self, rank: usize) -> crate::err::Result<Vec<usize>> {
        AxisSelector::new(&[FromEnd::<I>::INDEX]).normalize(rank)
    }
}

/// A semantic named-axis selector. It carries only the tag and never stores a
/// structural position.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NamedAxisSelector<Tag: crate::shapes::AxisTag>(core::marker::PhantomData<Tag>);

impl<Tag: crate::shapes::AxisTag> Default for NamedAxisSelector<Tag> {
    fn default() -> Self {
        Self(core::marker::PhantomData)
    }
}

impl<Tag: crate::shapes::AxisTag> NamedAxisSelector<Tag> {
    /// Resolves this selector against the current exact shape.
    pub fn resolve<S>(&self) -> crate::err::Result<usize>
    where
        S: NamedAxisLookup<Tag>,
    {
        S::lookup_named().map_err(crate::err::Error::Shape)
    }
}

/// Runtime fallback for named lookup when Stable Rust cannot prove a unique
/// recursive type-level match without overlapping implementations.
pub trait NamedAxisLookup<Tag: crate::shapes::AxisTag>: Shape {
    /// Resolves the semantic name against the current structural shape.
    fn lookup_named() -> core::result::Result<usize, crate::shapes::ShapeError>;
}

trait NamedAxisMetadata {
    fn collect_named<Tag: crate::shapes::AxisTag>(offset: usize, matches: &mut Vec<usize>);
}

impl NamedAxisMetadata for Nil {
    fn collect_named<Tag: crate::shapes::AxisTag>(_: usize, _: &mut Vec<usize>) {}
}

impl<H: Dim, T: Shape + NamedAxisMetadata> NamedAxisMetadata for DimCons<H, T> {
    fn collect_named<Tag: crate::shapes::AxisTag>(offset: usize, matches: &mut Vec<usize>) {
        if H::matches_tag::<Tag>() {
            matches.push(offset);
        }
        T::collect_named::<Tag>(offset + 1, matches);
    }
}

impl<Tag: crate::shapes::AxisTag, S: Shape + NamedAxisMetadata> NamedAxisLookup<Tag> for S {
    fn lookup_named() -> core::result::Result<usize, crate::shapes::ShapeError> {
        let mut matches = Vec::new();
        S::collect_named::<Tag>(0, &mut matches);
        match matches.as_slice() {
            [] => Err(crate::shapes::ShapeError::MissingNamedAxis { name: Tag::NAME }),
            [index] => Ok(*index),
            _ => Err(crate::shapes::ShapeError::AmbiguousNamedAxis { name: Tag::NAME }),
        }
    }
}

/// Canonical runtime/static axis selector sequence.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AxisSelector {
    /// Raw signed axes as supplied.
    pub raw_axes: Vec<isize>,
}

impl AxisSelector {
    /// Collects signed axes into a selector list.
    pub fn new(axes: &[isize]) -> Self {
        Self {
            raw_axes: axes.to_vec(),
        }
    }

    /// Normalizes signed relative axis indices against input `rank`, rejecting out-of-range or duplicate indices.
    pub fn normalize(&self, rank: usize) -> crate::err::Result<Vec<usize>> {
        let mut normalized = Vec::with_capacity(self.raw_axes.len());
        for &raw in &self.raw_axes {
            let norm = if raw >= 0 {
                let u = raw as usize;
                if u >= rank {
                    return Err(crate::err::Error::Shape(
                        crate::shapes::error::ShapeError::InvalidAxis { axis: u, rank },
                    ));
                }
                u
            } else {
                let neg = raw.unsigned_abs();
                if neg > rank {
                    return Err(crate::err::Error::Shape(
                        crate::shapes::error::ShapeError::InvalidAxis { axis: rank, rank },
                    ));
                }
                rank - neg
            };
            if normalized.contains(&norm) {
                return Err(crate::err::Error::Shape(
                    crate::shapes::error::ShapeError::DuplicateAxis { axis: norm },
                ));
            }
            normalized.push(norm);
        }
        Ok(normalized)
    }

    /// Normalize a nonnegative axis without converting it through `isize`.
    pub fn normalize_unsigned(axis: usize, rank: usize) -> crate::err::Result<usize> {
        if axis >= rank {
            return Err(crate::err::Error::Shape(
                crate::shapes::error::ShapeError::InvalidAxis { axis, rank },
            ));
        }
        Ok(axis)
    }
}

/// Trait allowing numbers and static cursors to be converted to signed axis indices.
pub trait ToAxisIndex {
    /// Signed axis position after resolution.
    fn to_axis_index(&self) -> isize;
}

impl ToAxisIndex for isize {
    fn to_axis_index(&self) -> isize {
        *self
    }
}

impl ToAxisIndex for i32 {
    fn to_axis_index(&self) -> isize {
        *self as isize
    }
}

impl ToAxisIndex for Here {
    fn to_axis_index(&self) -> isize {
        <Here as StaticCursor>::INDEX
    }
}

impl<I: StaticCursor> ToAxisIndex for Next<I> {
    fn to_axis_index(&self) -> isize {
        <Next<I> as StaticCursor>::INDEX
    }
}

impl<I: StaticCursor> ToAxisIndex for FromEnd<I> {
    fn to_axis_index(&self) -> isize {
        FromEnd::<I>::INDEX
    }
}

impl<I: StaticCursor> ToAxisIndex for StaticAxis<I> {
    fn to_axis_index(&self) -> isize {
        I::INDEX
    }
}

impl<I: crate::shapes::shape::ForwardCursor> ToAxisIndex for ForwardAxis<I> {
    fn to_axis_index(&self) -> isize {
        I::INDEX
    }
}

impl<I: StaticCursor> ToAxisIndex for ReverseAxis<I> {
    fn to_axis_index(&self) -> isize {
        FromEnd::<I>::INDEX
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::shapes::{DimCons, Nil, Shape};
    use typenum::{U0, U1, U2, U3, U4};

    trait Same<T> {}
    impl<T> Same<T> for T {}

    fn assert_shape_eq<S1: Shape, S2: Shape>()
    where
        S1: Same<S2>,
    {
    }

    #[test]
    fn slice_range_output_shape() {
        // idx![1..3, .., 0..2] on [4, 4, 3] → [2, runtime, 2].
        type Input = DimCons<U4, DimCons<U4, DimCons<U3, Nil>>>;
        type IdxT = DimCons<Slice<U1, U3, U2>, DimCons<Ellipsis, DimCons<Slice<U0, U2, U2>, Nil>>>;
        type Expected = DimCons<U2, DimCons<usize, DimCons<U2, Nil>>>;
        assert_shape_eq::<<IdxT as SliceTarget<Input>>::Output, Expected>();
    }

    #[test]
    fn slice_full_passthrough() {
        // idx![.., .., ..] on [4, 4, 3] → [runtime, runtime, runtime].
        type Input = DimCons<U4, DimCons<U4, DimCons<U3, Nil>>>;
        type IdxT = DimCons<Ellipsis, DimCons<Ellipsis, DimCons<Ellipsis, Nil>>>;
        type Expected = DimCons<usize, DimCons<usize, DimCons<usize, Nil>>>;
        assert_shape_eq::<<IdxT as SliceTarget<Input>>::Output, Expected>();
    }
}