10 #ifndef MLIR_BINDINGS_PYTHON_PYBINDUTILS_H
11 #define MLIR_BINDINGS_PYTHON_PYBINDUTILS_H
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/Support/DataTypes.h"
20 struct std::iterator_traits<
nanobind::detail::fast_iterator> {
46 template <
typename DerivedTy,
typename T>
68 template <
typename DefaultingTy>
70 NB_TYPE_CASTER(DefaultingTy, const_name(DefaultingTy::kTypeDescription))
72 bool
from_python(handle src, uint8_t flags, cleanup_list *cleanup) {
76 value = DefaultingTy{DefaultingTy::resolve()};
87 nanobind::cast<typename DefaultingTy::ReferrentTy &>(src)};
89 }
catch (std::exception &) {
94 static handle
from_cpp(DefaultingTy src, rv_policy policy,
95 cleanup_list *cleanup) noexcept {
96 return nanobind::cast(src, policy);
119 nanobind::str pyPart(part.
data,
121 printAccum->
parts.append(std::move(pyPart));
126 nanobind::str delim(
"", 0);
127 return nanobind::cast<nanobind::str>(delim.attr(
"join")(
parts));
136 : pyWriteFunction(fileObject.attr(
"write")), binary(binary) {}
142 nanobind::gil_scoped_acquire acquire;
146 nanobind::bytes pyBytes(part.
data, part.
length);
147 accum->pyWriteFunction(pyBytes);
149 nanobind::str pyStr(part.
data,
151 accum->pyWriteFunction(pyStr);
157 nanobind::object pyWriteFunction;
171 assert(!accum->invoked &&
172 "PySinglePartStringAccumulator called back multiple times");
173 accum->invoked =
true;
174 accum->value = nanobind::str(part.
data, part.
length);
179 assert(invoked &&
"PySinglePartStringAccumulator not called back");
180 return std::move(value);
185 bool invoked =
false;
216 template <
typename Derived,
typename ElementTy>
225 index = length + index;
226 if (index < 0 || index >= length)
233 intptr_t linearIndex = index * step + startIndex;
234 assert(linearIndex >= 0 &&
235 linearIndex <
static_cast<Derived *
>(
this)->getRawNumElements() &&
236 "linear index out of bounds, the slice is ill-formed");
242 template <
typename T,
typename... Args>
252 PyErr_SetString(PyExc_IndexError,
"index out of range");
256 if constexpr (llvm::is_detected<has_maybe_downcast, ElementTy>::value)
257 return static_cast<Derived *
>(
this)
261 return nanobind::cast(
262 static_cast<Derived *
>(
this)->getRawElement(
linearizeIndex(index)));
268 ssize_t start, stop, extraStep, sliceLength;
269 if (PySlice_GetIndicesEx(slice, length, &start, &stop, &extraStep,
270 &sliceLength) != 0) {
271 PyErr_SetString(PyExc_IndexError,
"index out of range");
274 return nanobind::cast(
static_cast<Derived *
>(
this)->slice(
275 startIndex + start * step, sliceLength, step * extraStep));
279 explicit Sliceable(intptr_t startIndex, intptr_t length, intptr_t step)
280 : startIndex(startIndex), length(length), step(step) {
281 assert(length >= 0 &&
"expected non-negative slice length");
290 throw nanobind::index_error(
"index out of range");
293 return static_cast<Derived *
>(
this)->getRawElement(
linearizeIndex(index));
297 intptr_t
size() {
return length; }
303 std::vector<ElementTy> elements;
304 elements.reserve(length + other.length);
305 for (intptr_t i = 0; i < length; ++i) {
306 elements.push_back(
static_cast<Derived *
>(
this)->
getElement(i));
308 for (intptr_t i = 0; i < other.length; ++i) {
309 elements.push_back(
static_cast<Derived *
>(&other)->
getElement(i));
315 static void bind(nanobind::module_ &m) {
316 auto clazz = nanobind::class_<Derived>(m, Derived::pyClassName)
318 Derived::bindDerived(clazz);
329 auto heap_type =
reinterpret_cast<PyHeapTypeObject *
>(clazz.ptr());
330 assert(heap_type->ht_type.tp_flags & Py_TPFLAGS_HEAPTYPE &&
331 "must be heap type");
332 heap_type->as_sequence.sq_length = +[](PyObject *rawSelf) -> Py_ssize_t {
333 auto self = nanobind::cast<Derived *>(nanobind::handle(rawSelf));
338 heap_type->as_sequence.sq_item =
339 +[](PyObject *rawSelf, Py_ssize_t index) -> PyObject * {
340 auto self = nanobind::cast<Derived *>(nanobind::handle(rawSelf));
341 return self->getItem(index).release().ptr();
344 heap_type->as_mapping.mp_subscript =
345 +[](PyObject *rawSelf, PyObject *rawSubscript) -> PyObject * {
346 auto self = nanobind::cast<Derived *>(nanobind::handle(rawSelf));
347 Py_ssize_t index = PyNumber_AsSsize_t(rawSubscript, PyExc_IndexError);
348 if (!PyErr_Occurred()) {
350 return self->getItem(index).release().ptr();
355 if (PySlice_Check(rawSubscript)) {
356 return self->getItemSlice(rawSubscript).release().ptr();
359 PyErr_SetString(PyExc_ValueError,
"expected integer or slice");
390 static inline bool isEqual(
const MlirTypeID &lhs,
const MlirTypeID &rhs) {
Accumulates int a python file-like object, either writing text (default) or binary.
PyFileAccumulator(const nanobind::object &fileObject, bool binary)
MlirStringCallback getCallback()
A CRTP base class for pseudo-containers willing to support Python-type slicing access on top of index...
intptr_t linearizeIndex(intptr_t index)
Computes the linear index given the current slice properties.
static void bind(nanobind::module_ &m)
Binds the indexing and length methods in the Python class.
ElementTy getElement(intptr_t index)
Returns the index-th element in the slice, supports negative indices.
nanobind::object getItemSlice(PyObject *slice)
Returns a new instance of the pseudo-container restricted to the given slice.
nanobind::class_< Derived > ClassTy
std::vector< ElementTy > dunderAdd(Derived &other)
Returns a new vector (mapped to Python list) containing elements from two slices.
static void bindDerived(ClassTy &)
Hook for derived classes willing to bind more methods.
Sliceable(intptr_t startIndex, intptr_t length, intptr_t step)
decltype(&T::maybeDownCast) has_maybe_downcast
Trait to check if T provides a maybeDownCast method.
intptr_t wrapIndex(intptr_t index)
Transforms index into a legal value to access the underlying sequence.
nanobind::object getItem(intptr_t index)
Returns the element at the given slice index.
intptr_t size()
Returns the size of slice.
CRTP template for special wrapper types that are allowed to be passed in as 'None' function arguments...
ReferrentTy * get() const
Defaulting(ReferrentTy &referrent)
Defaulting()=default
Type casters require the type to be default constructible, but using such an instance is illegal.
ReferrentTy * operator->()
MLIR_CAPI_EXPORTED MlirTypeID mlirTypeIDCreate(const void *ptr)
ptr must be 8 byte aligned and unique to a type valid for the duration of the returned type id's usag...
MLIR_CAPI_EXPORTED size_t mlirTypeIDHashValue(MlirTypeID typeID)
Returns the hash value of the type id.
MLIR_CAPI_EXPORTED bool mlirTypeIDEqual(MlirTypeID typeID1, MlirTypeID typeID2)
Checks if two type ids are equal.
void(* MlirStringCallback)(MlirStringRef, void *)
A callback for returning string references.
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Include the generated interface declarations.
A pointer to a sized fragment of a string, not necessarily null-terminated.
const char * data
Pointer to the first symbol.
size_t length
Length of the fragment.
static MlirTypeID getTombstoneKey()
static MlirTypeID getEmptyKey()
static bool isEqual(const MlirTypeID &lhs, const MlirTypeID &rhs)
static unsigned getHashValue(const MlirTypeID &val)
Accumulates into a python string from a method that accepts an MlirStringCallback.
MlirStringCallback getCallback()
Accumulates into a python string from a method that is expected to make one (no more,...
nanobind::str takeValue()
MlirStringCallback getCallback()
bool from_python(handle src, uint8_t flags, cleanup_list *cleanup)
static handle from_cpp(DefaultingTy src, rv_policy policy, cleanup_list *cleanup) noexcept
const value_type reference
std::ptrdiff_t difference_type
std::forward_iterator_tag iterator_category
nanobind::handle value_type