|
| 1 | +# TODO: Integrate this as a runtime test |
| 2 | + |
| 3 | +# Simulate array broadcasting |
| 4 | + |
| 5 | +from typing import Literal as L |
| 6 | + |
| 7 | +from typing import ( |
| 8 | + Literal, |
| 9 | + Never, |
| 10 | + GetArg, |
| 11 | + Bool, |
| 12 | + Matches, |
| 13 | + Iter, |
| 14 | + Slice, |
| 15 | + Length, |
| 16 | + IsSub, |
| 17 | + RaiseError, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +class Array[DType, *Shape]: |
| 22 | + def __add__[*Shape2]( |
| 23 | + self, |
| 24 | + other: Array[DType, *Shape2] |
| 25 | + ) -> Array[DType, *Merge[tuple[*Shape], tuple[*Shape2]]]: |
| 26 | + raise BaseException |
| 27 | + |
| 28 | + |
| 29 | +type AppendTuple[A, B] = tuple[ |
| 30 | + *[x for x in Iter[A]], |
| 31 | + B, |
| 32 | +] |
| 33 | + |
| 34 | +type MergeOne[T, S] = ( |
| 35 | + T |
| 36 | + if Matches[T, S] or Matches[S, Literal[1]] |
| 37 | + else S if Matches[T, Literal[1]] |
| 38 | + else RaiseError[Literal["Broadcast mismatch"], T, S] |
| 39 | +) |
| 40 | + |
| 41 | +type DropLast[T] = Slice[T, Literal[0], Literal[-1]] |
| 42 | +type Last[T] = GetArg[T, tuple, Literal[-1]] |
| 43 | + |
| 44 | +# Matching on Never here is intentional; it prevents stupid |
| 45 | +# infinite recursions. |
| 46 | +type Empty[T] = IsSub[Length[T], Literal[0]] |
| 47 | + |
| 48 | +type Merge[T, S] = ( |
| 49 | + S if Bool[Empty[T]] else T if Bool[Empty[S]] |
| 50 | + else |
| 51 | + AppendTuple[ |
| 52 | + Merge[DropLast[T], DropLast[S]], |
| 53 | + MergeOne[Last[T], Last[S]] |
| 54 | + ] |
| 55 | +) |
| 56 | + |
| 57 | +a1: Array[float, L[4], L[1]] |
| 58 | +a2: Array[float, L[3]] |
| 59 | +ar = a1 + a2 |
| 60 | +reveal_type(ar) # N: Revealed type is "__main__.Array[builtins.float, Literal[4], Literal[3]]" |
| 61 | +checkr: Array[float, L[4], L[3]] = ar |
| 62 | + |
| 63 | + |
| 64 | +b1: Array[float, int, int] |
| 65 | +b2: Array[float, int] |
| 66 | +reveal_type(b1 + b2) # N: Revealed type is "__main__.Array[builtins.float, builtins.int, builtins.int]" |
| 67 | + |
| 68 | + |
| 69 | +c1: Array[float, L[4], L[1], L[5]] |
| 70 | +c2: Array[float, L[4], L[3], L[1]] |
| 71 | +reveal_type(c1 + c2) # N: Revealed type is "__main__.Array[builtins.float, Literal[4], Literal[3], Literal[5]]" |
| 72 | + |
| 73 | +# |
| 74 | + |
| 75 | +err1: Array[float, L[4], L[2]] |
| 76 | +err2: Array[float, L[3]] |
| 77 | +err1 + err2 # E: Broadcast mismatch: Literal[2], Literal[3] |
0 commit comments