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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
use crate::shapes::ShapeBuf;
use crate::shapes::broadcast::ReverseShape;
use crate::shapes::idx::{FromEnd, Here, Next};
pub use crate::shapes::rank::{AddOneRank, PreserveRank, Ranked, RemoveOneRank};
use crate::shapes::{Dim, Dyn};
use alloc::vec::Vec;
use core::fmt::Debug;
use typenum::Unsigned;

/// Forward structural cursors.  Keeping reverse cursors out of the recursive
/// `FromEnd` adapters prevents the trait solver from exploring an infinite
/// reverse-of-reverse candidate chain.
#[doc(hidden)]
pub trait ForwardCursor: crate::shapes::idx::StaticCursor {}
impl ForwardCursor for Here {}
impl<I: ForwardCursor> ForwardCursor for Next<I> {}

mod sealed {
    pub trait Shape {}
}

/// The fundamental trait for all tensor shape types.
///
/// A `Shape` encodes the rank (number of dimensions) and, optionally, the static size of each
/// dimension into the type system. The three primary implementors are:
///
/// * **`DimCons`/`Nil`** (e.g., `s![2, 3]`) - Fully static or mixed.
/// * **`Dyn`** - Fully dynamic. Shape and rank are determined at runtime.
/// * **`Ranked<R>`** - Runtime extents with a typenum-known rank.
///
/// In practice, shapes are most often constructed via the `s![]` macro.
pub trait Shape: sealed::Shape + 'static + Clone + Debug + Send + Sync + Eq + PartialEq {
    /// Compile-time validity gate for exact structural shape expressions.
    ///
    /// The default is intentionally permissive for dynamic and legacy input
    /// adapters.  `DimCons` recursively specializes it so canonical
    /// structural operations reject invalid static extent arithmetic.
    const STATIC_VALID: () = ();
    /// Compile-time rank when this shape representation preserves it.
    /// `None` denotes a runtime-rank shape such as [`Dyn`].
    const RANK: Option<usize> = None;
    /// How much of this shape the compiler settled, as opposed to the runtime.
    ///
    /// This is the shape-level lift of `Dim::STATIC_SIZE`: rank and every
    /// axis size known from the type gives
    /// [`ProofLevel::Static`](crate::shapes::ProofLevel::Static); a known rank
    /// with at least one runtime or named axis gives
    /// [`Mixed`](crate::shapes::ProofLevel::Mixed); a runtime rank gives
    /// [`Dynamic`](crate::shapes::ProofLevel::Dynamic).
    ///
    /// A lowering rule reads this to stamp the `Validated<O>` it produces
    /// without knowing which concrete shape it was handed. It defaults to
    /// `Dynamic` so a `Shape` implemented outside this crate is credited with
    /// no proof it has not shown.
    const PROOF: crate::shapes::ProofLevel = crate::shapes::ProofLevel::Dynamic;

    /// This shape's element count, when the type alone settles it.
    ///
    /// The same trick as [`PROOF`](Shape::PROOF), for the same reason. A
    /// backend's `execute_shaped<S>` is generic over `S: Shape`. Restating the
    /// count here as an `Option` lets any
    /// `S` be asked, and because `S` is a type parameter the answer is a
    /// constant: `if let Some(n) = S::STATIC_NUMEL` collapses to one arm at
    /// monomorphization rather than branching at run time.
    ///
    /// `None` is the honest default. A shape with any runtime axis has no
    /// element count until its field exists, and one implemented outside this
    /// crate is credited with nothing it has not shown - the same rule `PROOF`
    /// follows.
    const STATIC_NUMEL: Option<usize> = None;

    /// The user-facing constructor argument type (e.g. a tuple of
    /// `usize`/`typenum` values, or `Vec<usize>` for `Dyn`).
    type Arg;
    /// Resolves a user-facing argument into canonical runtime dimensions.
    fn resolve(arg: Self::Arg) -> core::result::Result<ShapeBuf, crate::shapes::error::ShapeError>;
    /// Fallible raw-dimension boundary for callers that need a typed shape
    /// error.
    #[inline]
    fn try_from_dims(
        dims: &[usize],
    ) -> core::result::Result<ShapeBuf, crate::shapes::error::ShapeError> {
        Self::STATIC_VALID;
        Self::validate_dims(dims)?;
        Ok(crate::shapes::ShapeBuf::from_slice(dims))
    }

    /// Validates raw runtime dimensions against this shape's static contract.
    /// Implementors must define this proof obligation explicitly.
    fn validate_dims(dims: &[usize]) -> core::result::Result<(), crate::shapes::error::ShapeError>;
}

impl sealed::Shape for Nil {}
impl<H: Dim, T: Shape> sealed::Shape for DimCons<H, T> {}
impl<R: Unsigned + core::fmt::Debug + Eq + Send + Sync + 'static> sealed::Shape for Ranked<R> {}
impl sealed::Shape for Dyn {}

/// Terminator node for canonical recursive fixed-rank shapes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct Nil;

impl Shape for Nil {
    const RANK: Option<usize> = Some(0);
    const PROOF: crate::shapes::ProofLevel = crate::shapes::ProofLevel::Static;
    const STATIC_NUMEL: Option<usize> = Some(1);
    type Arg = ();
    #[inline(always)]
    fn resolve(_: Self::Arg) -> core::result::Result<ShapeBuf, crate::shapes::error::ShapeError> {
        Self::try_from_dims(&[])
    }

    fn validate_dims(dims: &[usize]) -> core::result::Result<(), crate::shapes::error::ShapeError> {
        if dims.is_empty() {
            Ok(())
        } else {
            Err(crate::shapes::error::ShapeError::TargetShapeRejected {
                operation: crate::shapes::error::OperationKind::Storage,
                rank: dims.len(),
            })
        }
    }
}

/// Cons-cell node for canonical recursive fixed-rank shapes (`DimCons<Head, Tail>`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct DimCons<H, T> {
    /// First dimension of the pair.
    pub head: H,
    /// Remaining dimensions.
    pub tail: T,
}

impl<H: Dim, T: Shape> Shape for DimCons<H, T> {
    const STATIC_VALID: () = {
        H::STATIC_VALID;
        T::STATIC_VALID;
    };
    const RANK: Option<usize> = match T::RANK {
        Some(rank) => Some(rank + 1),
        None => None,
    };
    const PROOF: crate::shapes::ProofLevel = match (H::STATIC_SIZE, T::PROOF) {
        (true, crate::shapes::ProofLevel::Static) => crate::shapes::ProofLevel::Static,
        _ => crate::shapes::ProofLevel::Mixed,
    };

    const STATIC_NUMEL: Option<usize> = match (H::STATIC, T::STATIC_NUMEL) {
        (crate::shapes::StaticExtent::Value(h), Some(t)) => h.checked_mul(t),
        _ => None,
    };

    type Arg = (H::Arg, T::Arg);
    #[inline]
    fn resolve(arg: Self::Arg) -> core::result::Result<ShapeBuf, crate::shapes::error::ShapeError> {
        let head_size = H::resolve_arg(arg.0)?;
        let tail_dims = T::resolve(arg.1)?;
        let mut buf = crate::shapes::ShapeBuf::from_slice(&[head_size]);
        for &d in tail_dims.as_ref() {
            buf.push(d);
        }
        Ok(buf)
    }

    fn validate_dims(dims: &[usize]) -> core::result::Result<(), crate::shapes::error::ShapeError> {
        if dims.is_empty() {
            return Err(crate::shapes::error::ShapeError::TargetShapeRejected {
                operation: crate::shapes::error::OperationKind::Storage,
                rank: 0,
            });
        }
        H::validate_size(dims[0]).then_some(()).ok_or(
            crate::shapes::error::ShapeError::TargetShapeRejected {
                operation: crate::shapes::error::OperationKind::Storage,
                rank: dims.len(),
            },
        )?;
        T::validate_dims(&dims[1..]).map_err(|error| match error {
            crate::shapes::error::ShapeError::TargetShapeRejected { operation, .. } => {
                crate::shapes::error::ShapeError::TargetShapeRejected {
                    operation,
                    rank: dims.len(),
                }
            }
            other => other,
        })
    }
}

impl DynShape for Nil {
    fn rank(_: &ShapeBuf) -> usize {
        0
    }
}

impl<H: Dim, T: Shape + DynShape> DynShape for DimCons<H, T> {
    fn rank(_: &ShapeBuf) -> usize {
        T::RANK.map_or(1, |rank| rank + 1)
    }
}

/// Prepends a dimension to a structural shape.
pub trait PrependDim<D: Dim>: Shape {
    /// The resulting shape of [`PrependDim`].
    type Output: Shape;
}

impl<D: Dim> PrependDim<D> for Nil {
    type Output = DimCons<D, Nil>;
}

impl<D: Dim, H: Dim, T: Shape> PrependDim<D> for DimCons<H, T> {
    type Output = DimCons<D, DimCons<H, T>>;
}

impl<D: Dim> AppendDim<D> for Nil {
    type Output = DimCons<D, Nil>;
}

impl<D: Dim, H: Dim, T: Shape> AppendDim<D> for DimCons<H, T>
where
    T: AppendDim<D>,
{
    type Output = DimCons<H, <T as AppendDim<D>>::Output>;
}

/// Concatenates two structural shapes.
pub trait StructuralConcatShape<Rhs: Shape>: Shape {
    /// The resulting shape of [`StructuralConcatShape`].
    type Output: Shape;
}

impl<Rhs: Shape> StructuralConcatShape<Rhs> for Nil {
    type Output = Rhs;
}

impl<H: Dim, T: Shape, Rhs: Shape> StructuralConcatShape<Rhs> for DimCons<H, T>
where
    T: StructuralConcatShape<Rhs>,
{
    type Output = DimCons<H, <T as StructuralConcatShape<Rhs>>::Output>;
}

/// Accesses the dimension at structural cursor `Cursor`.
pub trait At<Cursor>: Shape {
    /// The dimension at the resolved position.
    type Output: Dim;
}

impl<H: Dim, T: Shape> At<crate::shapes::idx::Here> for DimCons<H, T> {
    type Output = H;
}

impl<H: Dim, T: Shape, SubCursor> At<crate::shapes::idx::Next<SubCursor>> for DimCons<H, T>
where
    T: At<SubCursor>,
{
    type Output = <T as At<SubCursor>>::Output;
}

/// Positional access counting from the end.
pub trait AtFromEnd<Cursor>: Shape {
    /// The dimension at the from-end position.
    type Output: Dim;
}

#[doc(hidden)]
pub trait LastDim: Shape {
    type Output: Dim;
}

impl<H: Dim> LastDim for DimCons<H, Nil> {
    type Output = H;
}

impl<H: Dim, T: Shape> LastDim for DimCons<H, T>
where
    T: LastDim,
{
    type Output = <T as LastDim>::Output;
}

impl<H: Dim, T: Shape> AtFromEnd<Here> for DimCons<H, T>
where
    DimCons<H, T>: LastDim,
{
    type Output = <DimCons<H, T> as LastDim>::Output;
}

impl<H: Dim, T: Shape, Cursor: ForwardCursor> AtFromEnd<Next<Cursor>> for DimCons<H, T>
where
    DimCons<H, T>: RemoveLastDim,
    <DimCons<H, T> as RemoveLastDim>::Output: AtFromEnd<Cursor>,
{
    type Output = <<DimCons<H, T> as RemoveLastDim>::Output as AtFromEnd<Cursor>>::Output;
}

/// Removes the dimension at structural cursor `Cursor`.
pub trait RemoveAt<Cursor>: Shape {
    /// The resulting shape of [`RemoveAt`].
    type Output: Shape;
}

impl<H: Dim, T: Shape> RemoveAt<crate::shapes::idx::Here> for DimCons<H, T> {
    type Output = T;
}

impl<H: Dim, T: Shape, SubCursor> RemoveAt<crate::shapes::idx::Next<SubCursor>> for DimCons<H, T>
where
    T: RemoveAt<SubCursor>,
{
    type Output = DimCons<H, <T as RemoveAt<SubCursor>>::Output>;
}

impl RemoveAt<crate::shapes::idx::Here> for Dyn {
    type Output = Dyn;
}

impl<SubCursor> RemoveAt<crate::shapes::idx::Next<SubCursor>> for Dyn {
    type Output = Dyn;
}

/// Removal counting from the end.
pub trait RemoveFromEnd<Cursor>: Shape {
    /// The resulting shape of [`RemoveFromEnd`].
    type Output: Shape;
}

#[doc(hidden)]
pub trait RemoveLastDim: Shape {
    type Output: Shape;
}

impl<H: Dim> RemoveLastDim for DimCons<H, Nil> {
    type Output = Nil;
}

impl<H: Dim, H2: Dim, T: Shape> RemoveLastDim for DimCons<H, DimCons<H2, T>>
where
    DimCons<H2, T>: RemoveLastDim,
{
    type Output = DimCons<H, <DimCons<H2, T> as RemoveLastDim>::Output>;
}

impl<H: Dim, T: Shape> RemoveFromEnd<Here> for DimCons<H, T>
where
    DimCons<H, T>: RemoveLastDim,
{
    type Output = <DimCons<H, T> as RemoveLastDim>::Output;
}

impl<H: Dim, T: Shape, Cursor: ForwardCursor> RemoveFromEnd<Next<Cursor>> for DimCons<H, T>
where
    T: RemoveFromEnd<Cursor>,
{
    type Output = DimCons<H, <T as RemoveFromEnd<Cursor>>::Output>;
}

/// Replaces the dimension at structural cursor `Cursor` with `NewDim`.
pub trait ReplaceAt<Cursor, NewDim: Dim>: Shape {
    /// The resulting shape of [`ReplaceAt`].
    type Output: Shape;
}

impl<S, Cursor, NewDim> ReplaceAt<crate::shapes::idx::FromEnd<Cursor>, NewDim> for S
where
    Cursor: ForwardCursor,
    NewDim: Dim,
    S: ReplaceFromEnd<Cursor, NewDim>,
{
    type Output = <S as ReplaceFromEnd<Cursor, NewDim>>::Output;
}

impl<H: Dim, T: Shape, NewDim: Dim> ReplaceAt<crate::shapes::idx::Here, NewDim> for DimCons<H, T> {
    type Output = DimCons<NewDim, T>;
}

impl<H: Dim, T: Shape, SubCursor, NewDim: Dim>
    ReplaceAt<crate::shapes::idx::Next<SubCursor>, NewDim> for DimCons<H, T>
where
    T: ReplaceAt<SubCursor, NewDim>,
{
    type Output = DimCons<H, <T as ReplaceAt<SubCursor, NewDim>>::Output>;
}

/// Replacement counting from the end.
pub trait ReplaceFromEnd<Cursor, NewDim: Dim>: Shape {
    /// The resulting shape of [`ReplaceFromEnd`].
    type Output: Shape;
}

impl<H: Dim, T: Shape, NewDim: Dim> ReplaceFromEnd<Here, NewDim> for DimCons<H, T>
where
    DimCons<H, T>: ReplaceLastDim<NewDim>,
{
    type Output = <DimCons<H, T> as ReplaceLastDim<NewDim>>::Output;
}

impl<H: Dim, T: Shape, Cursor: ForwardCursor, NewDim: Dim> ReplaceFromEnd<Next<Cursor>, NewDim>
    for DimCons<H, T>
where
    T: ReplaceFromEnd<Cursor, NewDim>,
{
    type Output = DimCons<H, <T as ReplaceFromEnd<Cursor, NewDim>>::Output>;
}

/// Inserts `NewDim` before structural cursor `Cursor`.
pub trait InsertAt<Cursor, NewDim: Dim>: Shape {
    /// The resulting shape of [`InsertAt`].
    type Output: Shape;
}

impl<NewDim: Dim> InsertAt<crate::shapes::idx::Here, NewDim> for Nil {
    type Output = DimCons<NewDim, Nil>;
}

impl<H: Dim, T: Shape, NewDim: Dim> InsertAt<crate::shapes::idx::Here, NewDim> for DimCons<H, T> {
    type Output = DimCons<NewDim, DimCons<H, T>>;
}

impl<H: Dim, T: Shape, SubCursor, NewDim: Dim> InsertAt<crate::shapes::idx::Next<SubCursor>, NewDim>
    for DimCons<H, T>
where
    T: InsertAt<SubCursor, NewDim>,
{
    type Output = DimCons<H, <T as InsertAt<SubCursor, NewDim>>::Output>;
}

/// Inserts a dimension at a static axis, including from-end cursors.
pub trait InsertAxis<Cursor, NewDim: Dim>: Shape {
    /// The resulting shape of [`InsertAxis`].
    type Output: Shape;
}

impl<S, Cursor, NewDim> InsertAxis<Cursor, NewDim> for S
where
    Cursor: ForwardCursor,
    S: InsertAt<Cursor, NewDim>,
    <S as InsertAt<Cursor, NewDim>>::Output: Shape,
    NewDim: Dim,
{
    type Output = <S as InsertAt<Cursor, NewDim>>::Output;
}

impl<S, Cursor, NewDim> InsertAxis<crate::shapes::idx::FromEnd<Cursor>, NewDim> for S
where
    Cursor: ForwardCursor,
    S: ReverseShape,
    S::Output: InsertAt<Cursor, NewDim>,
    <S::Output as InsertAt<Cursor, NewDim>>::Output: ReverseShape,
    NewDim: Dim,
{
    type Output = <<S::Output as InsertAt<Cursor, NewDim>>::Output as ReverseShape>::Output;
}

/// Swaps two dimensions in a structural shape.
///
/// This is deliberately expressed in terms of the generic cursor operations
/// above.  It therefore works for arbitrary structural ranks without a
/// generated rank ladder, and moves each complete dimension type (including
/// any semantic name metadata) rather than reconstructing it from a size.
pub trait SwapAt<Left, Right>: Shape {
    /// The resulting shape of [`SwapAt`].
    type Output: Shape;
}

impl<H: Dim, T: Shape> SwapAt<Here, Here> for DimCons<H, T> {
    type Output = DimCons<H, T>;
}

impl<H: Dim, T: Shape, R, RD> SwapAt<Here, Next<R>> for DimCons<H, T>
where
    R: ForwardCursor,
    T: At<R, Output = RD> + ReplaceAt<R, H>,
    RD: Dim,
{
    type Output = DimCons<RD, <T as ReplaceAt<R, H>>::Output>;
}

impl<H: Dim, T: Shape, L, LD> SwapAt<Next<L>, Here> for DimCons<H, T>
where
    L: ForwardCursor,
    T: At<L, Output = LD> + ReplaceAt<L, H>,
    LD: Dim,
{
    type Output = DimCons<LD, <T as ReplaceAt<L, H>>::Output>;
}

impl<H: Dim, T: Shape, L, R> SwapAt<Next<L>, Next<R>> for DimCons<H, T>
where
    L: ForwardCursor,
    R: ForwardCursor,
    T: SwapAt<L, R>,
{
    type Output = DimCons<H, <T as SwapAt<L, R>>::Output>;
}

// From-end selectors use a separate algebra.  The helper traits below make
// the two edge cases explicit, so a proof of a forward cursor never explores
// an unconstrained reverse cursor candidate.
/// Swap counting both positions from the end.
pub trait SwapFromEndAt<Left, Right>: Shape {
    /// The resulting shape of [`SwapFromEndAt`].
    type Output: Shape;
}

#[doc(hidden)]
pub trait SwapLastWith<Cursor>: Shape {
    type Output: Shape;
}

impl<H: Dim, T: Shape, Last> SwapLastWith<Here> for DimCons<H, T>
where
    DimCons<H, T>: AtFromEnd<Here, Output = Last> + ReplaceAt<FromEnd<Here>, H>,
    <DimCons<H, T> as ReplaceAt<FromEnd<Here>, H>>::Output: ReplaceAt<Here, Last>,
    Last: Dim,
{
    type Output =
        <<DimCons<H, T> as ReplaceAt<FromEnd<Here>, H>>::Output as ReplaceAt<Here, Last>>::Output;
}

impl<H: Dim, T: Shape, R> SwapLastWith<Next<R>> for DimCons<H, T>
where
    T: SwapLastWith<R>,
{
    type Output = DimCons<H, <T as SwapLastWith<R>>::Output>;
}

#[doc(hidden)]
pub trait SwapFirstWith<Cursor>: Shape {
    type Output: Shape;
}

impl<S: Shape> SwapFirstWith<Here> for S {
    type Output = S;
}

impl<H: Dim, T: Shape, R, Other> SwapFirstWith<Next<R>> for DimCons<H, T>
where
    T: At<R, Output = Other> + ReplaceAt<R, H>,
    Other: Dim,
{
    type Output = DimCons<Other, <T as ReplaceAt<R, H>>::Output>;
}

impl<S, R> SwapFromEndAt<Here, FromEnd<R>> for S
where
    R: ForwardCursor,
    S: ReverseShape,
    S::Output: SwapLastWith<R>,
    <S::Output as SwapLastWith<R>>::Output: ReverseShape,
{
    type Output = <<S::Output as SwapLastWith<R>>::Output as ReverseShape>::Output;
}

impl<H: Dim, T: Shape, L, R> SwapFromEndAt<Next<L>, FromEnd<R>> for DimCons<H, T>
where
    L: ForwardCursor,
    R: ForwardCursor,
    T: SwapFromEndAt<L, FromEnd<R>>,
{
    type Output = DimCons<H, <T as SwapFromEndAt<L, FromEnd<R>>>::Output>;
}

impl<S, L, R> SwapFromEndAt<FromEnd<L>, FromEnd<R>> for S
where
    L: ForwardCursor,
    R: ForwardCursor,
    S: ReverseShape,
    S::Output: SwapAt<L, R>,
    <S::Output as SwapAt<L, R>>::Output: ReverseShape,
{
    type Output = <<S::Output as SwapAt<L, R>>::Output as ReverseShape>::Output;
}

impl<H: Dim, T: Shape, L, R> SwapFromEndAt<FromEnd<L>, Next<R>> for DimCons<H, T>
where
    L: ForwardCursor,
    R: ForwardCursor,
    T: SwapFromEndAt<FromEnd<L>, R>,
{
    type Output = DimCons<H, <T as SwapFromEndAt<FromEnd<L>, R>>::Output>;
}

/// Multiplies all dimensions in a structural shape into a single product dimension.
pub trait ProductDims: Shape {
    /// The dimension resulting from the product.
    type Output: Dim;
}

/// Collapses an inclusive structural cursor range into one extent.
///
/// The recursion consumes the selected prefix and then rebuilds the untouched
/// suffix, so this operation has no rank-specific implementations.
pub trait FlattenAt<Start, End>: Shape {
    /// The resulting shape of [`FlattenAt`].
    type Output: Shape;
}

/// From-end flattening has separate dispatch to keep reverse recursion out of
/// the positive-axis implementation.
pub trait FlattenFromEndAt<Start, End>: Shape {
    /// The resulting shape of [`FlattenFromEndAt`].
    type Output: Shape;
}

#[doc(hidden)]
pub trait FlattenPrefix<End>: Shape {
    type Product: Dim;
    type Suffix: Shape;
}

impl<H: Dim, T: Shape> FlattenPrefix<crate::shapes::idx::Here> for DimCons<H, T> {
    type Product = H;
    type Suffix = T;
}

impl<H: Dim, T: Shape, End> FlattenPrefix<crate::shapes::idx::Next<End>> for DimCons<H, T>
where
    T: FlattenPrefix<End>,
    <T as FlattenPrefix<End>>::Product: Dim,
{
    type Product = crate::shapes::dim::MulDim<H, <T as FlattenPrefix<End>>::Product>;
    type Suffix = <T as FlattenPrefix<End>>::Suffix;
}

impl<S: Shape> FlattenAt<crate::shapes::idx::Here, crate::shapes::idx::Here> for S
where
    S: FlattenPrefix<crate::shapes::idx::Here>,
{
    type Output = DimCons<
        <S as FlattenPrefix<crate::shapes::idx::Here>>::Product,
        <S as FlattenPrefix<crate::shapes::idx::Here>>::Suffix,
    >;
}

impl<End, S: Shape> FlattenAt<crate::shapes::idx::Here, crate::shapes::idx::Next<End>> for S
where
    End: ForwardCursor,
    S: FlattenPrefix<crate::shapes::idx::Next<End>>,
{
    type Output = DimCons<
        <S as FlattenPrefix<crate::shapes::idx::Next<End>>>::Product,
        <S as FlattenPrefix<crate::shapes::idx::Next<End>>>::Suffix,
    >;
}

impl<H: Dim, T: Shape, Start, End>
    FlattenAt<crate::shapes::idx::Next<Start>, crate::shapes::idx::Next<End>> for DimCons<H, T>
where
    Start: ForwardCursor,
    End: ForwardCursor,
    T: FlattenAt<Start, End>,
{
    type Output = DimCons<H, <T as FlattenAt<Start, End>>::Output>;
}

/// A forward start with a from-end end is handled by reversing the shape,
/// flattening the corresponding forward prefix, and reversing the result.
/// This keeps the range algebra rank-independent and preserves static proof.
#[doc(hidden)]
pub trait FlattenSuffix<Start>: Shape {
    type Output: Shape;
}

impl<S: Shape> FlattenSuffix<Here> for S
where
    S: ProductDims,
{
    type Output = DimCons<<S as ProductDims>::Output, Nil>;
}

impl<H: Dim, T: Shape, Start> FlattenSuffix<Next<Start>> for DimCons<H, T>
where
    Start: ForwardCursor,
    T: FlattenSuffix<Start>,
{
    type Output = DimCons<H, <T as FlattenSuffix<Start>>::Output>;
}

impl<End, S> FlattenFromEndAt<Here, FromEnd<End>> for S
where
    End: ForwardCursor,
    S: ReverseShape,
    S::Output: FlattenSuffix<End>,
    <S::Output as FlattenSuffix<End>>::Output: ReverseShape,
{
    type Output = <<S::Output as FlattenSuffix<End>>::Output as ReverseShape>::Output;
}

impl<Start, End, H: Dim, T: Shape>
    FlattenFromEndAt<crate::shapes::idx::Next<Start>, crate::shapes::idx::FromEnd<End>>
    for DimCons<H, T>
where
    T: FlattenFromEndAt<Start, crate::shapes::idx::FromEnd<End>>,
{
    type Output =
        DimCons<H, <T as FlattenFromEndAt<Start, crate::shapes::idx::FromEnd<End>>>::Output>;
}

/// A range with both endpoints counted from the end is mapped through the
/// existing reverse-shape algebra. Reversing the endpoint order is necessary
/// because the source range's start becomes the reversed range's end.
impl<Start, End, H: Dim, T: Shape>
    FlattenFromEndAt<crate::shapes::idx::FromEnd<Start>, crate::shapes::idx::FromEnd<End>>
    for DimCons<H, T>
where
    DimCons<H, T>: ReverseShape,
    <DimCons<H, T> as ReverseShape>::Output: FlattenAt<End, Start>,
    <<DimCons<H, T> as ReverseShape>::Output as FlattenAt<End, Start>>::Output: ReverseShape,
{
    type Output =
        <<<DimCons<H, T> as ReverseShape>::Output as FlattenAt<End, Start>>::Output as ReverseShape>::Output;
}

impl ProductDims for Nil {
    type Output = typenum::U1;
}

impl<H: Dim, T: Shape> ProductDims for DimCons<H, T>
where
    T: ProductDims,
{
    type Output = crate::shapes::dim::MulDim<H, <T as ProductDims>::Output>;
}

/// Structural suffix decomposition for the last 2 dimensions.
pub trait SplitLast2: Shape {
    /// All dimensions before the final two.
    type Prefix: Shape;
    /// Second-to-last dimension.
    type Penultimate: Dim;
    /// Final dimension.
    type Last: Dim;
}

impl<D1: Dim, D2: Dim> SplitLast2 for DimCons<D1, DimCons<D2, Nil>> {
    type Prefix = Nil;
    type Penultimate = D1;
    type Last = D2;
}

impl<H: Dim, T: Shape> SplitLast2 for DimCons<H, T>
where
    T: SplitLast2,
{
    type Prefix = DimCons<H, <T as SplitLast2>::Prefix>;
    type Penultimate = <T as SplitLast2>::Penultimate;
    type Last = <T as SplitLast2>::Last;
}

/// Structural suffix decomposition for the last 3 dimensions.
pub trait SplitLast3: Shape {
    /// All dimensions before the final three.
    type Prefix: Shape;
    /// Third-from-last dimension.
    type ThirdLast: Dim;
    /// Second-from-last dimension.
    type SecondLast: Dim;
    /// Final dimension.
    type Last: Dim;
}

impl<D1: Dim, D2: Dim, D3: Dim> SplitLast3 for DimCons<D1, DimCons<D2, DimCons<D3, Nil>>> {
    type Prefix = Nil;
    type ThirdLast = D1;
    type SecondLast = D2;
    type Last = D3;
}

impl<H: Dim, T: Shape> SplitLast3 for DimCons<H, T>
where
    T: SplitLast3,
{
    type Prefix = DimCons<H, <T as SplitLast3>::Prefix>;
    type ThirdLast = <T as SplitLast3>::ThirdLast;
    type SecondLast = <T as SplitLast3>::SecondLast;
    type Last = <T as SplitLast3>::Last;
}

/// Rebuild a typed shape buffer from computed dimensions, reporting instead of
/// panicking.
///
/// This is the checked replacement for the old optional raw-dimension chain
/// that `SHP-001` inventoried across 39 sites. The unwrap was a proof
/// obligation that no type stated and no test covered: the caller had already
/// erased a known-rank shape to a `Vec<usize>`, and then asserted the
/// round-trip back would succeed.
///
/// Prefer building the field axis by axis where the arity is known - that
/// avoids the erasure entirely and yields a
/// [`DimensionMismatch`](crate::shapes::error::ShapeError::DimensionMismatch)
/// naming the offending axis. Use this where the shape is only available
/// generically.
pub fn shape_buf_from_dims<S: Shape>(
    operation: crate::shapes::error::OperationKind,
    dims: &[usize],
) -> Result<ShapeBuf, crate::shapes::error::ShapeError> {
    S::STATIC_VALID;
    S::try_from_dims(dims).map_err(|error| match error {
        crate::shapes::error::ShapeError::TargetShapeRejected { .. } => {
            crate::shapes::error::ShapeError::TargetShapeRejected {
                operation,
                rank: dims.len(),
            }
        }
        other => other,
    })
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// Bounded and verified element count (`SEC-011`).
pub struct CheckedNumel(usize);

impl CheckedNumel {
    /// Computes and validates an element count for `dims`.
    pub fn from_dims(
        operation: crate::shapes::error::OperationKind,
        dims: &[usize],
        limits: &crate::resource::ResourceLimits,
    ) -> Result<Self, crate::shapes::error::ShapeError> {
        if dims.len() > limits.max_rank {
            return Err(crate::shapes::error::ShapeError::RankMismatch {
                operation,
                expected: crate::shapes::error::RankExpectation::AtMost(limits.max_rank),
                actual: dims.len(),
            });
        }
        if let Some(&dimension) = dims.iter().find(|&&dimension| {
            u64::try_from(dimension).map_or(true, |value| value > limits.max_dimension)
        }) {
            return Err(crate::shapes::error::ShapeError::InvalidParameter {
                operation,
                parameter: "dimension",
                value: dimension,
            });
        }
        crate::shapes::ShapeBuf::from_slice(dims)
            .checked_numel(operation)
            .map(Self)
    }

    #[inline]
    /// Concrete extent value.
    pub fn get(self) -> usize {
        self.0
    }
}

/// Safely computes shape element count using checked multiplication and limits (`SEC-011`).
pub fn checked_numel_from_dims(
    dims: &[usize],
    limits: &crate::resource::ResourceLimits,
) -> Result<CheckedNumel, crate::shapes::error::ShapeError> {
    CheckedNumel::from_dims(crate::shapes::error::OperationKind::Reshape, dims, limits)
}

/// A shape with runtime-accessible dimension information (rank, total elements, per-axis sizes).
///
/// All implementors of `Shape` that support dynamic rank queries also implement `DynShape`.
/// This includes both `Dyn` and fully static structural shapes. Operations that need to introspect
/// the shape at runtime (e.g., computing strides) require a `DynShape` bound.
pub trait DynShape: Shape {
    /// Returns the number of dimensions.
    fn rank(shape: &ShapeBuf) -> usize;
    /// Returns the total element count (product of all dimension sizes) after
    /// checking for arithmetic overflow.
    fn checked_numel(
        shape: &ShapeBuf,
        operation: crate::shapes::error::OperationKind,
    ) -> Result<usize, crate::shapes::error::ShapeError> {
        shape.checked_numel(operation)
    }

    /// Returns the total element count for shape metadata that has already
    /// crossed a checked tensor-construction boundary.
    fn numel(shape: &ShapeBuf) -> usize {
        Self::checked_numel(shape, crate::shapes::error::OperationKind::Storage)
            .expect("validated tensor shape must have a representable element count")
    }
}

/// The single authoritative relationship between type-level shape information
/// (`S`) and runtime extents.
///
/// Runtime dimensions are stored only in [`ShapeBuf`]. The type parameter
/// carries compile-time knowledge; it is not a second runtime representation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ShapeValue<S: Shape> {
    dims: crate::shapes::ShapeBuf,
    marker: core::marker::PhantomData<fn() -> S>,
}

impl<S: Shape> ShapeValue<S> {
    /// Constructs a validated relationship between `S` and runtime dimensions.
    #[inline]
    pub fn try_new(dims: ShapeBuf) -> Result<Self, crate::shapes::error::ShapeError> {
        S::STATIC_VALID;
        S::validate_dims(dims.as_ref())?;
        Ok(Self::from_validated(dims))
    }

    /// Constructs a ShapeValue after an internal caller has already validated
    /// the dimensions through a shape rule or tensor construction boundary.
    /// This constructor is crate-private so downstream code cannot forge the
    /// relationship between a shape type and incompatible dimensions.
    #[inline]
    pub(crate) fn from_validated(dims: ShapeBuf) -> Self {
        S::STATIC_VALID;
        debug_assert!(S::validate_dims(dims.as_ref()).is_ok());
        Self {
            dims,
            marker: core::marker::PhantomData,
        }
    }

    /// Builds the canonical runtime shape value from already validated
    /// dimensions. Operation rules use this when their output shape is
    /// computed structurally and therefore starts directly from canonical
    /// runtime dimensions rather than a constructor adapter.
    #[inline]
    pub(crate) fn from_validated_buf(dims: crate::shapes::ShapeBuf) -> Self {
        S::STATIC_VALID;
        debug_assert!(S::validate_dims(dims.as_ref()).is_ok());
        Self {
            dims,
            marker: core::marker::PhantomData,
        }
    }

    #[inline]
    /// Borrows the shape buffer.
    pub fn shape_buf(&self) -> &crate::shapes::ShapeBuf {
        &self.dims
    }

    #[inline]
    /// Copies extents as a vector.
    pub fn dims(&self) -> Vec<usize> {
        self.dims.as_ref().to_vec()
    }

    #[inline]
    /// Proof level proven for this shape.
    pub fn proof_level(&self) -> crate::shapes::ProofLevel {
        S::PROOF
    }

    #[inline]
    /// Checked element count over possibly symbolic extents.
    pub fn checked_numel(
        &self,
        op: crate::shapes::error::OperationKind,
        limits: &crate::resource::ResourceLimits,
    ) -> Result<CheckedNumel, crate::shapes::error::ShapeError> {
        CheckedNumel::from_dims(op, &self.dims(), limits)
    }
}

/// Resolution specification for shape parameters.
pub trait ShapeSpec {
    /// The shape type the resulting tensor carries.
    type Shape: Shape + DynShape;

    /// Resolves to the single authoritative `ShapeValue<Self::Shape>`.
    fn resolve(self) -> Result<ShapeValue<Self::Shape>, crate::err::Error>;
}

/// Runtime reshape specification with one inferred extent.
///
/// This value-level type keeps reshape inference separate from indexing. It
/// is produced by `shape![..., infer]` and resolved only when a source tensor
/// supplies its element count.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InferShape<S: Shape + DynShape = Dyn> {
    extents: alloc::vec::Vec<Option<usize>>,
    marker: core::marker::PhantomData<fn() -> S>,
}

impl<S: Shape + DynShape> InferShape<S> {
    /// Creates an inference specification. Exactly one extent must be `None`.
    #[must_use]
    pub fn new(extents: alloc::vec::Vec<Option<usize>>) -> Self {
        Self {
            extents,
            marker: core::marker::PhantomData,
        }
    }

    /// Resolves the inferred extent against a source element count.
    pub fn resolve(self, source_numel: usize) -> crate::err::Result<ShapeBuf> {
        let missing = self
            .extents
            .iter()
            .filter(|extent| extent.is_none())
            .count();
        if missing != 1 || self.extents.is_empty() {
            return Err(crate::err::Error::Msg(
                "reshape inference requires exactly one `infer` extent".into(),
            ));
        }
        let known_numel = self
            .extents
            .iter()
            .flatten()
            .try_fold(1usize, |acc, &extent| acc.checked_mul(extent))
            .ok_or_else(|| crate::err::Error::Msg("reshape extent product overflowed".into()))?;
        if known_numel == 0 || !source_numel.is_multiple_of(known_numel) {
            return Err(crate::err::Error::Msg(
                "inferred reshape extent is not integral".into(),
            ));
        }
        let inferred = source_numel / known_numel;
        Ok(ShapeBuf::from_slice(
            &self
                .extents
                .into_iter()
                .map(|extent| extent.unwrap_or(inferred))
                .collect::<alloc::vec::Vec<_>>(),
        ))
    }
}

/// Unvalidated shape constructor input produced by the `shape!` macro.
///
/// This is deliberately a specification, not a `ShapeValue`: dimensions are
/// checked only when [`ShapeSpec::resolve`] joins them to the canonical
/// `ShapeBuf` representation.
#[derive(Debug, Clone)]
pub struct ShapeArgs<S: Shape + DynShape> {
    args: S::Arg,
    marker: core::marker::PhantomData<fn() -> S>,
}

impl<S: Shape + DynShape> ShapeArgs<S> {
    /// Creates constructor input without claiming that its runtime values
    /// satisfy the type-level shape specification.
    #[inline]
    pub fn new(args: S::Arg) -> Self {
        Self {
            args,
            marker: core::marker::PhantomData,
        }
    }
}

impl<S: Shape + DynShape> ShapeSpec for ShapeArgs<S> {
    type Shape = S;

    fn resolve(self) -> Result<ShapeValue<S>, crate::err::Error> {
        S::resolve(self.args)
            .map_err(crate::err::Error::Shape)
            .and_then(|dims| ShapeValue::try_new(dims).map_err(crate::err::Error::Shape))
    }
}

impl<S: Shape + DynShape> ShapeSpec for ShapeValue<S> {
    type Shape = S;

    fn resolve(self) -> Result<ShapeValue<S>, crate::err::Error> {
        Ok(self)
    }
}

impl<const N: usize> ShapeSpec for [usize; N] {
    type Shape = Dyn;

    fn resolve(self) -> Result<ShapeValue<Self::Shape>, crate::err::Error> {
        ShapeValue::try_new(crate::shapes::ShapeBuf::from_slice(&self))
            .map_err(crate::err::Error::Shape)
    }
}

impl ShapeSpec for Vec<usize> {
    type Shape = Dyn;

    fn resolve(self) -> Result<ShapeValue<Dyn>, crate::err::Error> {
        ShapeValue::try_new(crate::shapes::ShapeBuf::from_slice(&self))
            .map_err(crate::err::Error::Shape)
    }
}

impl ShapeSpec for &[usize] {
    type Shape = Dyn;

    fn resolve(self) -> Result<ShapeValue<Dyn>, crate::err::Error> {
        ShapeValue::try_new(crate::shapes::ShapeBuf::from_slice(self))
            .map_err(crate::err::Error::Shape)
    }
}

/// Appends dimension `D` to the end of `Self`'s shape.
pub trait AppendDim<D: Dim> {
    /// `Self`'s dimensions with `D` appended at the end.
    type Output: Shape;
}

/// Replaces `Self`'s last dimension with `NewDim`.
pub trait ReplaceLastDim<NewDim: Dim> {
    /// `Self`'s dimensions with the last one replaced by `NewDim`.
    type Output: Shape;
}

/// Marker: `Self`'s last dimension is `D` - used to bound layer
/// `forward` impls (e.g. `Linear`) to inputs whose trailing feature
/// dimension matches the layer's expected input size.
#[diagnostic::on_unimplemented(
    message = "Cannot use shape `{Self}` here: its last dimension must be `{D}`",
    label = "wrong trailing dimension",
    note = "the input's last dimension must match this layer's expected input size"
)]
pub trait EndsWith<D: Dim>: Shape {}
/// Marker: `Self` has `D` channels at the `Conv1d`-expected channel
/// position (second-to-last dimension, `[.., C, L]`).
#[diagnostic::on_unimplemented(
    message = "Cannot use shape `{Self}` here: it must have `{D}` channels",
    label = "wrong channel count",
    note = "Conv1d/BatchNorm1d expect channels at the second-to-last dimension: [.., C, L]"
)]
pub trait HasChannels1D<D: Dim>: Shape {}
/// Marker: `Self` has `D` channels at the `Conv2d`/`BatchNorm2d`-expected
/// channel position (third-to-last dimension, `[.., C, H, W]`).
#[diagnostic::on_unimplemented(
    message = "Cannot use shape `{Self}` here: it must have `{D}` channels",
    label = "wrong channel count",
    note = "Conv2d/BatchNorm2d expect channels at the third-to-last dimension: [.., C, H, W]"
)]
pub trait HasChannels2D<D: Dim>: Shape {}

impl<D: Dim> EndsWith<D> for Dyn {}
impl<D: Dim> HasChannels1D<D> for Dyn {}
impl<D: Dim> HasChannels2D<D> for Dyn {}

impl<NewDim: Dim> ReplaceLastDim<NewDim> for Nil {
    type Output = Nil;
}
/// Replaces only the trailing dimension.
pub trait ReplaceLastTail<NewDim: Dim>: Shape {
    /// The resulting shape of [`ReplaceLastTail`].
    type Output: Shape;
}
impl<NewDim: Dim> ReplaceLastTail<NewDim> for Nil {
    type Output = DimCons<NewDim, Nil>;
}
impl<H: Dim, NewDim: Dim> ReplaceLastTail<NewDim> for DimCons<H, Nil> {
    type Output = DimCons<NewDim, Nil>;
}
impl<H: Dim, H2: Dim, T: Shape, NewDim: Dim> ReplaceLastTail<NewDim> for DimCons<H, DimCons<H2, T>>
where
    DimCons<H2, T>: ReplaceLastTail<NewDim>,
{
    type Output = DimCons<H, <DimCons<H2, T> as ReplaceLastTail<NewDim>>::Output>;
}
impl<H: Dim, T: Shape, NewDim: Dim> ReplaceLastDim<NewDim> for DimCons<H, T>
where
    T: ReplaceLastTail<NewDim>,
{
    type Output = DimCons<H, <T as ReplaceLastTail<NewDim>>::Output>;
}

impl<D: Dim> EndsWith<D> for DimCons<D, Nil> {}
impl<H: Dim, H2: Dim, T: Shape, D: Dim> EndsWith<D> for DimCons<H, DimCons<H2, T>> where
    DimCons<H2, T>: EndsWith<D>
{
}

impl<H: Dim, T: Shape, D: Dim> HasChannels1D<D> for DimCons<H, T> where
    DimCons<H, T>: AtFromEnd<crate::shapes::idx::Next<crate::shapes::idx::Here>, Output = D>
{
}

impl<H: Dim, T: Shape, D: Dim> HasChannels2D<D> for DimCons<H, T> where
    DimCons<H, T>: AtFromEnd<
            crate::shapes::idx::Next<crate::shapes::idx::Next<crate::shapes::idx::Here>>,
            Output = D,
        >
{
}

///
/// --- Dyn ---
///
impl Shape for Dyn {
    const RANK: Option<usize> = None;
    /// Not even the rank is known until the shape exists, which is the whole
    /// point of `Dyn`. Stated rather than inherited from the default so that
    /// changing the default cannot silently upgrade it.
    const PROOF: crate::shapes::ProofLevel = crate::shapes::ProofLevel::Dynamic;

    /// The user-facing constructor argument type for this concrete shape.
    type Arg = Vec<usize>;
    /// Runtime values for this shape are held in `ShapeBuf`.
    /// Converts a user-facing argument into canonical `ShapeBuf` storage.
    fn resolve(arg: Self::Arg) -> core::result::Result<ShapeBuf, crate::shapes::error::ShapeError> {
        Self::try_from_dims(&arg).map(|_| arg.into_iter().collect())
    }
    fn validate_dims(_: &[usize]) -> core::result::Result<(), crate::shapes::error::ShapeError> {
        Ok(())
    }
}

impl DynShape for Dyn {
    #[inline(always)]
    /// Returns the number of dimensions.
    fn rank(shape: &ShapeBuf) -> usize {
        shape.len()
    }
}

impl<D: Dim> AppendDim<D> for Dyn {
    /// `Self`'s dimensions with `D` appended at the end.
    type Output = Dyn;
}

impl<NewDim: Dim> ReplaceLastDim<NewDim> for Dyn {
    /// `Self`'s dimensions with the last one replaced by `NewDim`.
    type Output = Dyn;
}

#[cfg(test)]
mod tests;