Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core: Implement HasAncestor. #2514

Merged
merged 5 commits into from
Apr 30, 2024
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
2 changes: 1 addition & 1 deletion tests/filecheck/dialects/stencil/invalid.mlir
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ builtin.module {
}
}

// CHECK: 'stencil.access' expects parent op 'stencil.apply'
// CHECK: 'stencil.access' expects ancestor op 'stencil.apply'

// -----

Expand Down
20 changes: 20 additions & 0 deletions tests/test_traits.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
traits_def,
)
from xdsl.traits import (
HasAncestor,
HasParent,
OptionalSymbolOpInterface,
SymbolOpInterface,
Expand Down Expand Up @@ -449,6 +450,25 @@ def test_lazy_parent():
assert op.traits == frozenset([HasParent(TestOp)])


@irdl_op_definition
class AncestorOp(IRDLOperation):
name = "test.ancestor"

traits = frozenset((HasAncestor(TestOp),))


def test_has_ancestor():
op = AncestorOp()

assert op.get_traits_of_type(HasAncestor) == [HasAncestor(TestOp)]
assert op.has_trait(HasAncestor, (TestOp,))

with pytest.raises(
VerifyException, match="'test.ancestor' expects ancestor op 'test.test'"
):
op.verify()


def test_insert_or_update():
@irdl_op_definition
class SymbolTableOp(IRDLOperation):
Expand Down
12 changes: 7 additions & 5 deletions xdsl/dialects/stencil.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
)
from xdsl.parser import AttrParser, Parser
from xdsl.printer import Printer
from xdsl.traits import HasParent, IsolatedFromAbove, IsTerminator
from xdsl.traits import HasAncestor, HasParent, IsolatedFromAbove, IsTerminator
from xdsl.utils.exceptions import VerifyException
from xdsl.utils.hints import isa

Expand Down Expand Up @@ -728,7 +728,7 @@ class AccessOp(IRDLOperation):
)
)

traits = frozenset([HasParent(ApplyOp)])
traits = frozenset([HasAncestor(ApplyOp)])

def print(self, printer: Printer):
printer.print(" ")
Expand All @@ -740,7 +740,8 @@ def print(self, printer: Printer):
)

# IRDL-enforced, not supposed to use custom syntax if not veriied
apply = cast(ApplyOp, self.parent_op())
trait = cast(HasAncestor, AccessOp.get_trait(HasAncestor, (ApplyOp,)))
apply = cast(ApplyOp, trait.get_ancestor(self))

mapping = self.offset_mapping
if mapping is None:
Expand Down Expand Up @@ -825,8 +826,9 @@ def get(
)

def verify_(self) -> None:
apply = self.parent_op()
# As promised by HasParent(ApplyOp)
# As promised by HasAncestor(ApplyOp)
trait = cast(HasAncestor, AccessOp.get_trait(HasAncestor, (ApplyOp,)))
apply = trait.get_ancestor(self)
assert isinstance(apply, ApplyOp)

# TODO This should be handled by infra, having a way to verify things on ApplyOp
Expand Down
37 changes: 37 additions & 0 deletions xdsl/traits.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import abc
from collections.abc import Iterator
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, TypeVar

Expand Down Expand Up @@ -68,6 +69,42 @@ def verify(self, op: Operation) -> None:
raise VerifyException(f"'{op.name}' expects parent op to be one of {names}")


@dataclass(frozen=True)
class HasAncestor(OpTrait):
"""
Constraint the operation to have a specific operation as ancestor, i.e. transitive
parent.
"""

parameters: tuple[type[Operation], ...]

def __init__(self, head_param: type[Operation], *tail_params: type[Operation]):
super().__init__((head_param, *tail_params))

def verify(self, op: Operation) -> None:
if self.get_ancestor(op) is None:
if len(self.parameters) == 1:
raise VerifyException(
f"'{op.name}' expects ancestor op '{self.parameters[0].name}'"
)
names = ", ".join(f"'{p.name}'" for p in self.parameters)
raise VerifyException(
f"'{op.name}' expects ancestor op to be one of {names}"
)

def walk_ancestors(self, op: Operation) -> Iterator[Operation]:
"""Iterates over the ancestors of an operation, including the input"""
curr = op
yield curr
while (curr := curr.parent_op()) is not None:
yield curr

def get_ancestor(self, op: Operation) -> Operation | None:
ancestors = self.walk_ancestors(op)
matching_ancestors = (a for a in ancestors if isinstance(a, self.parameters))
return next(matching_ancestors, None)


class IsTerminator(OpTrait):
"""
This trait provides verification and functionality for operations that are
Expand Down
Loading