9 #ifndef MLIR_BINDINGS_PYTHON_PYBINDUTILS_H
10 #define MLIR_BINDINGS_PYTHON_PYBINDUTILS_H
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/Support/DataTypes.h"
17 #include <pybind11/pybind11.h>
18 #include <pybind11/stl.h>
38 template <
typename DerivedTy,
typename T>
60 template <
typename DefaultingTy>
64 bool load(pybind11::handle src,
bool) {
68 value = DefaultingTy{DefaultingTy::resolve()};
79 pybind11::cast<typename DefaultingTy::ReferrentTy &>(src)};
81 }
catch (std::exception &) {
86 static handle
cast(DefaultingTy src, return_value_policy policy,
88 return pybind11::cast(src, policy);
111 pybind11::str pyPart(part.
data,
113 printAccum->
parts.append(std::move(pyPart));
118 pybind11::str delim(
"", 0);
119 return delim.attr(
"join")(
parts);
128 : pyWriteFunction(fileObject.attr(
"write")), binary(binary) {}
134 pybind11::gil_scoped_acquire acquire;
138 pybind11::bytes pyBytes(part.
data, part.
length);
139 accum->pyWriteFunction(pyBytes);
141 pybind11::str pyStr(part.
data,
143 accum->pyWriteFunction(pyStr);
149 pybind11::object pyWriteFunction;
163 assert(!accum->invoked &&
164 "PySinglePartStringAccumulator called back multiple times");
165 accum->invoked =
true;
166 accum->value = pybind11::str(part.
data, part.
length);
171 assert(invoked &&
"PySinglePartStringAccumulator not called back");
172 return std::move(value);
177 bool invoked =
false;
208 template <
typename Derived,
typename ElementTy>
217 index = length + index;
218 if (index < 0 || index >= length)
225 intptr_t linearIndex = index * step + startIndex;
226 assert(linearIndex >= 0 &&
227 linearIndex <
static_cast<Derived *
>(
this)->getRawNumElements() &&
228 "linear index out of bounds, the slice is ill-formed");
234 template <
typename T,
typename... Args>
244 PyErr_SetString(PyExc_IndexError,
"index out of range");
248 if constexpr (llvm::is_detected<has_maybe_downcast, ElementTy>::value)
249 return static_cast<Derived *
>(
this)
253 return pybind11::cast(
254 static_cast<Derived *
>(
this)->getRawElement(
linearizeIndex(index)));
260 ssize_t start, stop, extraStep, sliceLength;
261 if (PySlice_GetIndicesEx(slice, length, &start, &stop, &extraStep,
262 &sliceLength) != 0) {
263 PyErr_SetString(PyExc_IndexError,
"index out of range");
266 return pybind11::cast(
static_cast<Derived *
>(
this)->slice(
267 startIndex + start * step, sliceLength, step * extraStep));
271 explicit Sliceable(intptr_t startIndex, intptr_t length, intptr_t step)
272 : startIndex(startIndex), length(length), step(step) {
273 assert(length >= 0 &&
"expected non-negative slice length");
282 throw pybind11::index_error(
"index out of range");
285 return static_cast<Derived *
>(
this)->getRawElement(
linearizeIndex(index));
289 intptr_t
size() {
return length; }
295 std::vector<ElementTy> elements;
296 elements.reserve(length + other.length);
297 for (intptr_t i = 0; i < length; ++i) {
298 elements.push_back(
static_cast<Derived *
>(
this)->
getElement(i));
300 for (intptr_t i = 0; i < other.length; ++i) {
301 elements.push_back(
static_cast<Derived *
>(&other)->
getElement(i));
307 static void bind(pybind11::module &m) {
308 auto clazz = pybind11::class_<Derived>(m, Derived::pyClassName,
309 pybind11::module_local())
311 Derived::bindDerived(clazz);
322 auto heap_type =
reinterpret_cast<PyHeapTypeObject *
>(clazz.ptr());
323 assert(heap_type->ht_type.tp_flags & Py_TPFLAGS_HEAPTYPE &&
324 "must be heap type");
325 heap_type->as_sequence.sq_length = +[](PyObject *rawSelf) -> Py_ssize_t {
326 auto self = pybind11::cast<Derived *>(rawSelf);
331 heap_type->as_sequence.sq_item =
332 +[](PyObject *rawSelf, Py_ssize_t index) -> PyObject * {
333 auto self = pybind11::cast<Derived *>(rawSelf);
334 return self->getItem(index).release().ptr();
337 heap_type->as_mapping.mp_subscript =
338 +[](PyObject *rawSelf, PyObject *rawSubscript) -> PyObject * {
339 auto self = pybind11::cast<Derived *>(rawSelf);
340 Py_ssize_t index = PyNumber_AsSsize_t(rawSubscript, PyExc_IndexError);
341 if (!PyErr_Occurred()) {
343 return self->getItem(index).release().ptr();
348 if (PySlice_Check(rawSubscript)) {
349 return self->getItemSlice(rawSubscript).release().ptr();
352 PyErr_SetString(PyExc_ValueError,
"expected integer or slice");
383 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)
decltype(&T::maybeDownCast) has_maybe_downcast
Trait to check if T provides a maybeDownCast method.
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.
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,...
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))