9 #ifndef MLIR_BINDINGS_PYTHON_PYBINDUTILS_H
10 #define MLIR_BINDINGS_PYTHON_PYBINDUTILS_H
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/Support/DataTypes.h"
16 #include <pybind11/pybind11.h>
17 #include <pybind11/stl.h>
37 template <
typename DerivedTy,
typename T>
59 template <
typename DefaultingTy>
63 bool load(pybind11::handle src,
bool) {
67 value = DefaultingTy{DefaultingTy::resolve()};
78 pybind11::cast<typename DefaultingTy::ReferrentTy &>(src)};
80 }
catch (std::exception &) {
85 static handle
cast(DefaultingTy src, return_value_policy policy,
87 return pybind11::cast(src, policy);
110 pybind11::str pyPart(part.
data,
112 printAccum->
parts.append(std::move(pyPart));
117 pybind11::str delim(
"", 0);
118 return delim.attr(
"join")(
parts);
127 : pyWriteFunction(fileObject.attr(
"write")), binary(binary) {}
133 pybind11::gil_scoped_acquire acquire;
137 pybind11::bytes pyBytes(part.
data, part.
length);
138 accum->pyWriteFunction(pyBytes);
140 pybind11::str pyStr(part.
data,
142 accum->pyWriteFunction(pyStr);
148 pybind11::object pyWriteFunction;
162 assert(!accum->invoked &&
163 "PySinglePartStringAccumulator called back multiple times");
164 accum->invoked =
true;
165 accum->value = pybind11::str(part.
data, part.
length);
170 assert(invoked &&
"PySinglePartStringAccumulator not called back");
171 return std::move(value);
176 bool invoked =
false;
207 template <
typename Derived,
typename ElementTy>
216 index = length + index;
217 if (index < 0 || index >= length)
224 intptr_t linearIndex = index * step + startIndex;
225 assert(linearIndex >= 0 &&
226 linearIndex <
static_cast<Derived *
>(
this)->getRawNumElements() &&
227 "linear index out of bounds, the slice is ill-formed");
238 PyErr_SetString(PyExc_IndexError,
"index out of range");
242 return pybind11::cast(
243 static_cast<Derived *
>(
this)->getRawElement(
linearizeIndex(index)));
249 ssize_t start, stop, extraStep, sliceLength;
250 if (PySlice_GetIndicesEx(slice, length, &start, &stop, &extraStep,
251 &sliceLength) != 0) {
252 PyErr_SetString(PyExc_IndexError,
"index out of range");
255 return pybind11::cast(
static_cast<Derived *
>(
this)->slice(
256 startIndex + start * step, sliceLength, step * extraStep));
260 explicit Sliceable(intptr_t startIndex, intptr_t length, intptr_t step)
261 : startIndex(startIndex), length(length), step(step) {
262 assert(length >= 0 &&
"expected non-negative slice length");
271 throw pybind11::index_error(
"index out of range");
274 return static_cast<Derived *
>(
this)->getRawElement(
linearizeIndex(index));
278 intptr_t
size() {
return length; }
284 std::vector<ElementTy> elements;
285 elements.reserve(length + other.length);
286 for (intptr_t i = 0; i < length; ++i) {
287 elements.push_back(
static_cast<Derived *
>(
this)->
getElement(i));
289 for (intptr_t i = 0; i < other.length; ++i) {
290 elements.push_back(
static_cast<Derived *
>(&other)->
getElement(i));
296 static void bind(pybind11::module &m) {
297 auto clazz = pybind11::class_<Derived>(m, Derived::pyClassName,
298 pybind11::module_local())
300 Derived::bindDerived(clazz);
311 auto heap_type =
reinterpret_cast<PyHeapTypeObject *
>(clazz.ptr());
312 assert(heap_type->ht_type.tp_flags & Py_TPFLAGS_HEAPTYPE &&
313 "must be heap type");
314 heap_type->as_sequence.sq_length = +[](PyObject *rawSelf) -> Py_ssize_t {
315 auto self = pybind11::cast<Derived *>(rawSelf);
320 heap_type->as_sequence.sq_item =
321 +[](PyObject *rawSelf, Py_ssize_t index) -> PyObject * {
322 auto self = pybind11::cast<Derived *>(rawSelf);
323 return self->getItem(index).release().ptr();
326 heap_type->as_mapping.mp_subscript =
327 +[](PyObject *rawSelf, PyObject *rawSubscript) -> PyObject * {
328 auto self = pybind11::cast<Derived *>(rawSelf);
329 Py_ssize_t index = PyNumber_AsSsize_t(rawSubscript, PyExc_IndexError);
330 if (!PyErr_Occurred()) {
332 return self->getItem(index).release().ptr();
337 if (PySlice_Check(rawSubscript)) {
338 return self->getItemSlice(rawSubscript).release().ptr();
341 PyErr_SetString(PyExc_ValueError,
"expected integer or slice");
372 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 pybind11::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(pybind11::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.
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)
pybind11::object getItemSlice(PyObject *slice)
Returns a new instance of the pseudo-container restricted to the given slice.
pybind11::class_< Derived > ClassTy
intptr_t wrapIndex(intptr_t index)
Transforms index into a legal value to access the underlying sequence.
intptr_t size()
Returns the size of slice.
pybind11::object getItem(intptr_t index)
Returns the element at the given slice index.
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.
Include the generated interface declarations.
This header declares functions that assist transformations in the MemRef dialect.
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,...
pybind11::str takeValue()
MlirStringCallback getCallback()
bool load(pybind11::handle src, bool)
static handle cast(DefaultingTy src, return_value_policy policy, handle parent)
PYBIND11_TYPE_CASTER(DefaultingTy, _(DefaultingTy::kTypeDescription))