Skip to content
Open
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
70 changes: 70 additions & 0 deletions tests/irdl/test_attr_declarative_assembly_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,76 @@ class ParamsOptType(ParametrizedAttribute, TypeAttribute):
check_roundtrip(ParamsOptType, "i32", ctx)


# ============================================================================
# Integration tests — struct directive
# ============================================================================


def test_struct_all_params():
"""struct(params) prints all params as key=value pairs."""

@irdl_attr_definition
class StructAllType(ParametrizedAttribute, TypeAttribute):
name = "test_af.struct_all"
x: IntegerType = param_def()
y: IntegerType = param_def()
assembly_format = "struct(params)"

ctx = Context(allow_unregistered=True)
ctx.load_attr_or_type(StructAllType)
check_roundtrip(StructAllType, "x = i32, y = i64", ctx)


def test_struct_subset():
"""struct($a, $b) with a subset of parameters."""

@irdl_attr_definition
class StructSubType(ParametrizedAttribute, TypeAttribute):
name = "test_af.struct_sub"
a: IntegerType = param_def()
b: IntegerType = param_def()
c: IntegerType = param_def()
assembly_format = "struct($a, $b) `,` $c"

ctx = Context(allow_unregistered=True)
ctx.load_attr_or_type(StructSubType)
check_roundtrip(StructSubType, "a = i32, b = i64, i1", ctx)


def test_struct_reordered_parse():
"""Struct fields can be parsed in any order."""

@irdl_attr_definition
class StructReorderType(ParametrizedAttribute, TypeAttribute):
name = "test_af.struct_reorder"
a: IntegerType = param_def()
b: IntegerType = param_def()
assembly_format = "struct(params)"

ctx = Context(allow_unregistered=True)
ctx.load_attr_or_type(StructReorderType)
parsed = parse_type("!test_af.struct_reorder<b = i64, a = i32>", ctx)
assert isinstance(parsed, StructReorderType)
assert parsed.a == i32
assert parsed.b == i64


def test_struct_optional_param():
"""Struct with optional parameter omitted."""

@irdl_attr_definition
class StructOptType(ParametrizedAttribute, TypeAttribute):
name = "test_af.struct_opt"
req: IntegerType = param_def()
opt: IntegerType | NoneAttr = param_def()
assembly_format = "struct(params)"

ctx = Context(allow_unregistered=True)
ctx.load_attr_or_type(StructOptType)
check_roundtrip(StructOptType, "req = i32, opt = i64", ctx)
check_roundtrip(StructOptType, "req = i32", ctx)


# ============================================================================
# Integration tests — printing correctness
# ============================================================================
Expand Down
50 changes: 50 additions & 0 deletions xdsl/irdl/declarative_assembly_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -1733,6 +1733,56 @@ def print(
pv.print(printer, state, attr)


@dataclass(frozen=True)
class StructDirective(AttrFormatDirective):
"""Prints parameters as key = value pairs, parseable in any order."""

params: tuple[ParameterVariable, ...]

def parse(self, parser: AttrParser, state: AttrParsingState) -> bool:
remaining = {pv.name: pv for pv in self.params}
first = True
while remaining:
if not first:
if not parser.parse_optional_punctuation(","):
break
name = parser.parse_optional_identifier()
if name is None:
if first:
break
parser.raise_error("expected parameter name in struct")
first = False
if name not in remaining:
parser.raise_error(
f"unexpected parameter '{name}', "
f"expected one of {list(remaining.keys())}"
)
parser.parse_punctuation("=")
remaining[name].parse(parser, state)
del remaining[name]
for pv in remaining.values():
if pv.is_optional:
pv.set_empty(state)
else:
parser.raise_error(f"missing required parameter '{pv.name}' in struct")
return True

def print(
self, printer: Printer, state: PrintingState, attr: ParametrizedAttribute, /
) -> None:
first = True
for pv in self.params:
if not pv.is_present(attr):
continue
if not first:
printer.print_string(", ")
first = False
printer.print_string(f"{pv.name} = ")
state.should_emit_space = False
state.last_was_punctuation = True
pv.print(printer, state, attr)


@dataclass(frozen=True)
class AttrOptionalGroupDirective(AttrFormatDirective):
"""An optional group in attribute assembly format."""
Expand Down
17 changes: 17 additions & 0 deletions xdsl/irdl/declarative_assembly_format_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
RegionVariable,
ResultsDirective,
ResultVariable,
StructDirective,
SuccessorDirective,
SuccessorVariable,
SymbolNameAttributeVariable,
Expand Down Expand Up @@ -951,6 +952,8 @@ def parse_format_directive(self) -> AttrFormatDirective:
return self.parse_qualified_directive()
if self.parse_optional_keyword("params"):
return self.parse_params_directive()
if self.parse_optional_keyword("struct"):
return self.parse_struct_directive()
self.raise_error(f"unexpected token '{self._current_token.text}'")

def parse_variable(self, inside_ref: bool = False) -> ParameterVariable:
Expand Down Expand Up @@ -1078,3 +1081,17 @@ def _all_param_variables(self) -> tuple[ParameterVariable, ...]:

def parse_params_directive(self) -> ParamsDirective:
return ParamsDirective(self._all_param_variables())

def _parse_struct_variables(self) -> tuple[ParameterVariable, ...]:
"""Parse the argument list for struct(): either `params` or `$a, $b, ...`."""
with self.in_parens():
if self.parse_optional_keyword("params"):
return self._all_param_variables()
params: list[ParameterVariable] = []
params.append(self.parse_variable())
while self.parse_optional_punctuation(","):
params.append(self.parse_variable())
return tuple(params)

def parse_struct_directive(self) -> StructDirective:
return StructDirective(self._parse_struct_variables())
Loading