Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 33 additions & 16 deletions mlir/lib/Bindings/Python/IRCore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -361,37 +361,45 @@ class PyRegionIterator {

/// Regions of an op are fixed length and indexed numerically so are represented
/// with a sequence-like container.
class PyRegionList {
class PyRegionList : public Sliceable<PyRegionList, PyRegion> {
public:
PyRegionList(PyOperationRef operation) : operation(std::move(operation)) {}
static constexpr const char *pyClassName = "RegionSequence";

PyRegionList(PyOperationRef operation, intptr_t startIndex = 0,
intptr_t length = -1, intptr_t step = 1)
: Sliceable(startIndex,
length == -1 ? mlirOperationGetNumRegions(operation->get())
: length,
step),
operation(std::move(operation)) {}

PyRegionIterator dunderIter() {
operation->checkValid();
return PyRegionIterator(operation);
}

intptr_t dunderLen() {
static void bindDerived(ClassTy &c) {
c.def("__iter__", &PyRegionList::dunderIter);
}

private:
/// Give the parent CRTP class access to hook implementations below.
friend class Sliceable<PyRegionList, PyRegion>;

intptr_t getRawNumElements() {
operation->checkValid();
return mlirOperationGetNumRegions(operation->get());
}

PyRegion dunderGetItem(intptr_t index) {
// dunderLen checks validity.
if (index < 0 || index >= dunderLen()) {
throw nb::index_error("attempt to access out of bounds region");
}
MlirRegion region = mlirOperationGetRegion(operation->get(), index);
return PyRegion(operation, region);
PyRegion getRawElement(intptr_t pos) {
operation->checkValid();
return PyRegion(operation, mlirOperationGetRegion(operation->get(), pos));
}

static void bind(nb::module_ &m) {
nb::class_<PyRegionList>(m, "RegionSequence")
.def("__len__", &PyRegionList::dunderLen)
.def("__iter__", &PyRegionList::dunderIter)
.def("__getitem__", &PyRegionList::dunderGetItem);
PyRegionList slice(intptr_t startIndex, intptr_t length, intptr_t step) {
return PyRegionList(operation, startIndex, length, step);
}

private:
PyOperationRef operation;
};

Expand Down Expand Up @@ -450,6 +458,9 @@ class PyBlockList {

PyBlock dunderGetItem(intptr_t index) {
operation->checkValid();
if (index < 0) {
index += dunderLen();
}
if (index < 0) {
throw nb::index_error("attempt to access out of bounds block");
}
Comment on lines 464 to 466
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DCE?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It can still be negative, right?

xs = [1, 2, 3]
xs[-42]

Copy link
Contributor

@makslevental makslevental Mar 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh whoops duh. Ok ignore me then!

Copy link
Collaborator

@joker-eph joker-eph Mar 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

xs = [1, 2, 3]
xs[-42]

Do we have this already in the test suite?

Out-of-scope for your PR here, but could these exceptions be a bit more expressive by including the original index, the adjusted one, and the bounds in the error message?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test suite doesn't check OOB errors at the moment, I think.

Expand Down Expand Up @@ -546,6 +557,9 @@ class PyOperationList {

nb::object dunderGetItem(intptr_t index) {
parentOperation->checkValid();
if (index < 0) {
index += dunderLen();
}
if (index < 0) {
throw nb::index_error("attempt to access out of bounds operation");
}
Expand Down Expand Up @@ -2629,6 +2643,9 @@ class PyOpAttributeMap {
}

PyNamedAttribute dunderGetItemIndexed(intptr_t index) {
if (index < 0) {
index += dunderLen();
}
if (index < 0 || index >= dunderLen()) {
throw nb::index_error("attempt to access out of bounds attribute");
}
Expand Down
3 changes: 3 additions & 0 deletions mlir/python/mlir/_mlir_libs/_mlir/ir.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -2466,7 +2466,10 @@ class RegionIterator:
def __next__(self) -> Region: ...

class RegionSequence:
@overload
def __getitem__(self, arg0: int) -> Region: ...
@overload
def __getitem__(self, arg0: slice) -> Sequence[Region]: ...
def __iter__(self) -> RegionIterator: ...
def __len__(self) -> int: ...

Expand Down
22 changes: 19 additions & 3 deletions mlir/test/python/ir/operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def testTraverseOpRegionBlockIterators():
op = module.operation
assert op.context is ctx
# Get the block using iterators off of the named collections.
regions = list(op.regions)
regions = list(op.regions[:])
blocks = list(regions[0].blocks)
# CHECK: MODULE REGIONS=1 BLOCKS=1
print(f"MODULE REGIONS={len(regions)} BLOCKS={len(blocks)}")
Expand Down Expand Up @@ -86,8 +86,24 @@ def walk_operations(indent, op):
# CHECK: Block iter: <mlir.{{.+}}.BlockIterator
# CHECK: Operation iter: <mlir.{{.+}}.OperationIterator
print(" Region iter:", iter(op.regions))
print(" Block iter:", iter(op.regions[0]))
print("Operation iter:", iter(op.regions[0].blocks[0]))
print(" Block iter:", iter(op.regions[-1]))
print("Operation iter:", iter(op.regions[-1].blocks[-1]))

try:
op.regions[-42]
except IndexError as e:
# CHECK: Region OOB: index out of range
print("Region OOB:", e)
try:
op.regions[0].blocks[-42]
except IndexError as e:
# CHECK: attempt to access out of bounds block
print(e)
try:
op.regions[0].blocks[0].operations[-42]
except IndexError as e:
# CHECK: attempt to access out of bounds operation
print(e)


# Verify index based traversal of the op/region/block hierarchy.
Expand Down
Loading