| 273 | |
| 274 | template <typename T> |
| 275 | PyScalarT validate_shape( |
| 276 | T list, |
| 277 | const mx::Shape& shape, |
| 278 | int idx, |
| 279 | bool& all_python_primitive_elements) { |
| 280 | if (idx >= shape.size()) { |
| 281 | throw std::invalid_argument("Initialization encountered extra dimension."); |
| 282 | } |
| 283 | auto s = shape[idx]; |
| 284 | if (nb::len(list) != s) { |
| 285 | throw std::invalid_argument( |
| 286 | "Initialization encountered non-uniform length."); |
| 287 | } |
| 288 | |
| 289 | if (s == 0) { |
| 290 | return pyfloat; |
| 291 | } |
| 292 | |
| 293 | PyScalarT type = pybool; |
| 294 | for (auto l : list) { |
| 295 | PyScalarT t; |
| 296 | if (nb::isinstance<nb::list>(l)) { |
| 297 | t = validate_shape( |
| 298 | nb::cast<nb::list>(l), shape, idx + 1, all_python_primitive_elements); |
| 299 | } else if (nb::isinstance<nb::tuple>(*list.begin())) { |
| 300 | t = validate_shape( |
| 301 | nb::cast<nb::tuple>(l), |
| 302 | shape, |
| 303 | idx + 1, |
| 304 | all_python_primitive_elements); |
| 305 | } else if (nb::isinstance<mx::array>(l)) { |
| 306 | all_python_primitive_elements = false; |
| 307 | auto arr = nb::cast<mx::array>(l); |
| 308 | if (arr.ndim() + idx + 1 == shape.size() && |
| 309 | std::equal( |
| 310 | arr.shape().cbegin(), |
| 311 | arr.shape().cend(), |
| 312 | shape.cbegin() + idx + 1)) { |
| 313 | t = pybool; |
| 314 | } else { |
| 315 | throw std::invalid_argument( |
| 316 | "Initialization encountered non-uniform length."); |
| 317 | } |
| 318 | } else { |
| 319 | if (nb::isinstance<nb::bool_>(l)) { |
| 320 | t = pybool; |
| 321 | } else if (nb::isinstance<nb::int_>(l)) { |
| 322 | t = pyint; |
| 323 | } else if (nb::isinstance<nb::float_>(l)) { |
| 324 | t = pyfloat; |
| 325 | } else if (PyComplex_Check(l.ptr())) { |
| 326 | t = pycomplex; |
| 327 | } else { |
| 328 | std::ostringstream msg; |
| 329 | msg << "Invalid type " << nb::type_name(l.type()).c_str() |
| 330 | << " received in array initialization."; |
| 331 | throw std::invalid_argument(msg.str()); |
| 332 | } |