-
Notifications
You must be signed in to change notification settings - Fork 57
/
attribute_definition_test.py
615 lines (462 loc) · 18.6 KB
/
attribute_definition_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
"""
Test the definition of attributes and their constraints.
"""
from __future__ import annotations
from dataclasses import dataclass
from io import StringIO
from typing import Any, TypeVar, cast, Annotated, Generic, TypeAlias
import pytest
from xdsl.ir import Attribute, Data, ParametrizedAttribute
from xdsl.irdl import (AttrConstraint, GenericData, ParameterDef,
VerifyException, irdl_attr_definition, builder,
irdl_to_attr_constraint, AnyAttr, BaseAttr,
ParamAttrDef)
from xdsl.parser import Parser
from xdsl.printer import Printer
# ____ _
# | _ \ __ _| |_ __ _
# | | | |/ _` | __/ _` |
# | |_| | (_| | || (_| |
# |____/ \__,_|\__\__,_|
#
@irdl_attr_definition
class BoolData(Data[bool]):
"""An attribute holding a boolean value."""
name = "bool"
@staticmethod
def parse_parameter(parser: Parser) -> bool:
val = parser.parse_optional_ident()
if val == "True":
return True
elif val == "False":
return False
else:
raise Exception("Wrong argument passed to BoolAttr.")
@staticmethod
def print_parameter(data: bool, printer: Printer):
printer.print_string(str(data))
@irdl_attr_definition
class IntData(Data[int]):
"""An attribute holding an integer value."""
name = "int"
@staticmethod
def parse_parameter(parser: Parser) -> int:
return parser.parse_int_literal()
@staticmethod
def print_parameter(data: int, printer: Printer):
printer.print_string(str(data))
@irdl_attr_definition
class StringData(Data[str]):
"""An attribute holding a string value."""
name = "str"
@staticmethod
def parse_parameter(parser: Parser) -> str:
return parser.parse_str_literal()
@staticmethod
def print_parameter(data: str, printer: Printer):
printer.print_string(data)
def test_simple_data():
"""Test that the definition of a data with a class parameter."""
b = BoolData(True)
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(b)
assert stream.getvalue() == "!bool<True>"
def test_simple_data_verifier_failure():
"""
Test that the verifier of a data with a class parameter fails when given
a parameter of the wrong type.
"""
with pytest.raises(VerifyException) as e:
BoolData(2) # type: ignore
assert e.value.args[0] == ("bool data attribute expected type "
"<class 'bool'>, but <class 'int'> given.")
class IntListMissingVerifierData(Data[list[int]]):
"""
An attribute holding a list of integers.
The definition should fail, since no verifier is provided, and the Data
type parameter is not a class.
"""
name = "missing_verifier_data"
@staticmethod
def parse_parameter(parser: Parser) -> list[int]:
raise NotImplementedError()
@staticmethod
def print_parameter(data: list[int], printer: Printer) -> None:
raise NotImplementedError()
def test_data_with_non_class_param_missing_verifier_failure():
"""
Test that a non-class Data parameter requires the definition of a verifier.
"""
with pytest.raises(Exception) as e:
irdl_attr_definition(IntListMissingVerifierData)
assert e.value.args[0] == (
'In IntListMissingVerifierData definition: '
'Cannot infer "verify" method. Type parameter of Data has type GenericAlias.'
)
@irdl_attr_definition
class IntListData(Data[list[int]]):
"""
An attribute holding a list of integers.
"""
name = "int_list"
@staticmethod
def parse_parameter(parser: Parser) -> list[int]:
raise NotImplementedError()
@staticmethod
def print_parameter(data: list[int], printer: Printer) -> None:
printer.print_string("[")
printer.print_list(data, lambda x: printer.print_string(str(x)))
printer.print_string("]")
def verify(self) -> None:
if not isinstance(self.data, list):
raise VerifyException("int_list data should hold a list.")
for elem in self.data:
if not isinstance(elem, int):
raise VerifyException(
"int_list list elements should be integers.")
def test_non_class_data():
"""Test the definition of a Data with a non-class parameter."""
attr = IntListData([0, 1, 42])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue() == "!int_list<[0, 1, 42]>"
def test_simple_data_constructor_failure():
"""
Test that the verifier of a Data with a non-class parameter fails when
given wrong arguments.
"""
with pytest.raises(VerifyException) as e:
IntListData([0, 1, 42, ""]) # type: ignore
assert e.value.args[0] == "int_list list elements should be integers."
# ____ ____ _ _ _
# | __ ) __ _ ___ ___ / ___|___ _ __ ___| |_ _ __ __ _(_)_ __ | |_
# | _ \ / _` / __|/ _ \ | / _ \| '_ \/ __| __| '__/ _` | | '_ \| __|
# | |_) | (_| \__ \ __/ |__| (_) | | | \__ \ |_| | | (_| | | | | | |_
# |____/ \__,_|___/\___|\____\___/|_| |_|___/\__|_| \__,_|_|_| |_|\__|
#
@irdl_attr_definition
class BoolWrapperAttr(ParametrizedAttribute):
name = "bool_wrapper"
param: ParameterDef[BoolData]
def test_bose_constraint():
"""Test the verifier of a base attribute type constraint."""
attr = BoolWrapperAttr([BoolData(True)])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue() == "!bool_wrapper<!bool<True>>"
def test_base_constraint_fail():
"""Test the verifier of a union constraint."""
with pytest.raises(Exception) as e:
BoolWrapperAttr([StringData("foo")])
assert e.value.args[
0] == "StringData(data='foo') should be of base attribute bool"
# _ _ _ ____ _ _ _
# | | | |_ __ (_) ___ _ __ / ___|___ _ __ ___| |_ _ __ __ _(_)_ __ | |_
# | | | | '_ \| |/ _ \| '_ \| | / _ \| '_ \/ __| __| '__/ _` | | '_ \| __|
# | |_| | | | | | (_) | | | | |__| (_) | | | \__ \ |_| | | (_| | | | | | |_
# \___/|_| |_|_|\___/|_| |_|\____\___/|_| |_|___/\__|_| \__,_|_|_| |_|\__|
#
@irdl_attr_definition
class BoolOrIntParamAttr(ParametrizedAttribute):
name = "bool_or_int"
param: ParameterDef[BoolData | IntData]
def test_union_constraint_left():
"""Test the verifier of a union constraint."""
attr = BoolOrIntParamAttr([BoolData(True)])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue() == "!bool_or_int<!bool<True>>"
def test_union_constraint_right():
"""Test the verifier of a union constraint."""
attr = BoolOrIntParamAttr([IntData(42)])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue() == "!bool_or_int<!int<42>>"
def test_union_constraint_fail():
"""Test the verifier of a union constraint."""
with pytest.raises(Exception) as e:
BoolOrIntParamAttr([StringData("foo")])
assert e.value.args[0] == "Unexpected attribute StringData(data='foo')"
# _ _ ____ _
# / \ _ __ _ __ ___ | |_ / ___|___ _ __ ___| |_ _ __
# / _ \ | '_ \| '_ \ / _ \| __| | / _ \| '_ \/ __| __| '__|
# / ___ \| | | | | | | (_) | |_| |__| (_) | | | \__ \ |_| |
# /_/ \_\_| |_|_| |_|\___/ \__|\____\___/|_| |_|___/\__|_|
class PositiveIntConstr(AttrConstraint):
def verify(self, attr: Attribute) -> None:
if not isinstance(attr, IntData):
raise VerifyException(
f"Expected {IntData.name} attribute, but got {attr.name}.")
if attr.data <= 0:
raise VerifyException(
f"Expected positive integer, got {attr.data}.")
@irdl_attr_definition
class PositiveIntAttr(ParametrizedAttribute):
name = "positive_int"
param: ParameterDef[Annotated[IntData, PositiveIntConstr()]]
def test_annotated_constraint():
"""Test the verifier of an annotated constraint."""
attr = PositiveIntAttr([IntData(42)])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue() == "!positive_int<!int<42>>"
def test_annotated_constraint_fail():
"""Test that the verifier of an annotated constraint can fail."""
with pytest.raises(Exception) as e:
PositiveIntAttr([IntData(-42)])
assert e.value.args[0] == "Expected positive integer, got -42."
# _____ __ __ ____ _
# |_ _| _ _ __ __\ \ / /_ _ _ __ / ___|___ _ __ ___| |_ _ __
# | || | | | '_ \ / _ \ \ / / _` | '__| | / _ \| '_ \/ __| __| '__|
# | || |_| | |_) | __/\ V / (_| | | | |__| (_) | | | \__ \ |_| |
# |_| \__, | .__/ \___| \_/ \__,_|_| \____\___/|_| |_|___/\__|_|
# |___/|_|
#
_T = TypeVar("_T", bound=BoolData | IntData)
@irdl_attr_definition
class ParamWrapperAttr(Generic[_T], ParametrizedAttribute):
name = "int_or_bool_generic"
param: ParameterDef[_T]
def test_typevar_attribute_int():
"""Test the verifier of a generic attribute."""
attr = ParamWrapperAttr[IntData]([IntData(42)])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue() == "!int_or_bool_generic<!int<42>>"
def test_typevar_attribute_bool():
"""Test the verifier of a generic attribute."""
attr = ParamWrapperAttr[BoolData]([BoolData(True)])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue() == "!int_or_bool_generic<!bool<True>>"
def test_typevar_attribute_fail():
"""Test that the verifier of an generic attribute can fail."""
with pytest.raises(Exception) as e:
ParamWrapperAttr([StringData("foo")])
assert e.value.args[0] == "Unexpected attribute StringData(data='foo')"
@irdl_attr_definition
class ParamConstrAttr(ParametrizedAttribute):
name = "param_constr"
param: ParameterDef[ParamWrapperAttr[IntData]]
def test_param_attr_constraint():
"""Test the verifier of an attribute with a parametric constraint."""
attr = ParamConstrAttr([ParamWrapperAttr([IntData(42)])])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue() == "!param_constr<!int_or_bool_generic<!int<42>>>"
def test_param_attr_constraint_fail():
"""
Test that the verifier of an attribute with
a parametric constraint can fail.
"""
with pytest.raises(Exception) as e:
ParamConstrAttr([ParamWrapperAttr([BoolData(True)])])
assert e.value.args[
0] == "BoolData(data=True) should be of base attribute int"
_U = TypeVar("_U", bound=IntData)
@irdl_attr_definition
class NestedParamWrapperAttr(Generic[_U], ParametrizedAttribute):
name = "nested_param_wrapper"
param: ParameterDef[ParamWrapperAttr[_U]]
def test_nested_generic_constraint():
"""
Test the verifier of an attribute with a generic
constraint used in a parametric constraint.
"""
attr = NestedParamWrapperAttr[IntData]([ParamWrapperAttr([IntData(42)])])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue(
) == "!nested_param_wrapper<!int_or_bool_generic<!int<42>>>"
def test_nested_generic_constraint_fail():
"""
Test that the verifier of an attribute with
a parametric constraint can fail.
"""
with pytest.raises(Exception) as e:
NestedParamWrapperAttr([ParamWrapperAttr([BoolData(True)])])
assert e.value.args[
0] == "BoolData(data=True) should be of base attribute int"
@irdl_attr_definition
class NestedParamConstrAttr(ParametrizedAttribute):
name = "nested_param_constr"
param: ParameterDef[NestedParamWrapperAttr[Annotated[IntData,
PositiveIntConstr()]]]
def test_nested_param_attr_constraint():
"""
Test the verifier of a nested parametric constraint.
"""
attr = NestedParamConstrAttr(
[NestedParamWrapperAttr([ParamWrapperAttr([IntData(42)])])])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue(
) == "!nested_param_constr<!nested_param_wrapper<!int_or_bool_generic<!int<42>>>>"
def test_nested_param_attr_constraint_fail():
"""
Test that the verifier of a nested parametric constraint can fail.
"""
with pytest.raises(Exception) as e:
NestedParamConstrAttr(
[NestedParamWrapperAttr([ParamWrapperAttr([IntData(-42)])])])
assert e.value.args[0] == "Expected positive integer, got -42."
# ____ _ ____ _
# / ___| ___ _ __ ___ _ __(_) ___| _ \ __ _| |_ __ _
# | | _ / _ \ '_ \ / _ \ '__| |/ __| | | |/ _` | __/ _` |
# | |_| | __/ | | | __/ | | | (__| |_| | (_| | || (_| |
# \____|\___|_| |_|\___|_| |_|\___|____/ \__,_|\__\__,_|
#
_MissingGenericDataData = TypeVar("_MissingGenericDataData")
@irdl_attr_definition
class MissingGenericDataData(Data[_MissingGenericDataData]):
name = "missing_genericdata"
@staticmethod
def parse_parameter(parser: Parser) -> _MissingGenericDataData:
raise NotImplementedError()
@staticmethod
def print_parameter(data: _MissingGenericDataData,
printer: Printer) -> None:
raise NotImplementedError()
def verify(self) -> None:
return
class MissingGenericDataDataWrapper(ParametrizedAttribute):
name = "missing_genericdata_wrapper"
param: ParameterDef[MissingGenericDataData[int]]
def test_data_with_generic_missing_generic_data_failure():
"""
Test error message when a generic data is used in constraints
without implementing GenericData.
"""
with pytest.raises(Exception) as e:
irdl_attr_definition(MissingGenericDataDataWrapper)
assert e.value.args[0] == (
"Generic `Data` type 'missing_genericdata' cannot be converted to "
"an attribute constraint. Consider making it inherit from "
"`GenericData` instead of `Data`.")
A = TypeVar("A", bound=Attribute)
@dataclass
class DataListAttr(AttrConstraint):
"""
A constraint that enforces that the elements of a ListData all respect
a constraint.
"""
elem_constr: AttrConstraint
def verify(self, attr: Attribute) -> None:
attr = cast(ListData[Any], attr)
for e in attr.data:
self.elem_constr.verify(e)
@irdl_attr_definition
class ListData(GenericData[list[A]]):
name = "list"
@staticmethod
def parse_parameter(parser: Parser) -> list[A]:
raise NotImplementedError()
@staticmethod
def print_parameter(data: list[A], printer: Printer) -> None:
printer.print_string("[")
printer.print_list(data, printer.print_attribute)
printer.print_string("]")
@staticmethod
def generic_constraint_coercion(args: tuple[Any]) -> AttrConstraint:
assert len(args) == 1
return DataListAttr(irdl_to_attr_constraint(args[0]))
@staticmethod
@builder
def from_list(data: list[A]) -> ListData[A]:
return ListData(data)
def verify(self) -> None:
if not isinstance(self.data, list):
raise VerifyException(
f"Wrong type given to attribute {self.name}: got"
f" {type(self.data)}, but expected list of"
" attributes.")
for idx, val in enumerate(self.data):
if not isinstance(val, Attribute):
raise VerifyException(
f"{self.name} data expects attribute list, but element "
f"{idx} is of type {type(val)}.")
AnyListData: TypeAlias = ListData[Attribute]
def test_generic_data_verifier():
"""
Test that a GenericData can be created.
"""
attr = ListData([BoolData(True), ListData([BoolData(False)])])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue() == "!list<[!bool<True>, !list<[!bool<False>]>]>"
def test_generic_data_verifier_fail():
"""
Test that a GenericData verifier fails when given wrong parameters.
"""
with pytest.raises(VerifyException) as e:
ListData([0]) # type: ignore
assert e.value.args[0] == ("list data expects attribute list, but"
" element 0 is of type <class 'int'>.")
@irdl_attr_definition
class ListDataWrapper(ParametrizedAttribute):
name = "list_wrapper"
val: ParameterDef[ListData[BoolData]]
def test_generic_data_wrapper_verifier():
"""
Test that a GenericData used in constraints pass the verifier when correct.
"""
attr = ListDataWrapper([ListData([BoolData(True), BoolData(False)])])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue(
) == "!list_wrapper<!list<[!bool<True>, !bool<False>]>>"
def test_generic_data_wrapper_verifier_failure():
"""
Test that a GenericData used in constraints fails
the verifier when constraints are not satisfied.
"""
with pytest.raises(VerifyException) as e:
ListDataWrapper(
[ListData([BoolData(True),
ListData([BoolData(False)])])])
assert e.value.args[
0] == "ListData(data=[BoolData(data=False)]) should be of base attribute bool"
@irdl_attr_definition
class ListDataNoGenericsWrapper(ParametrizedAttribute):
name = "list_no_generics_wrapper"
val: ParameterDef[AnyListData]
def test_generic_data_no_generics_wrapper_verifier():
"""
Test that GenericType can be used in constraints without a parameter.
"""
attr = ListDataNoGenericsWrapper(
[ListData([BoolData(True), ListData([BoolData(False)])])])
stream = StringIO()
p = Printer(stream=stream)
p.print_attribute(attr)
assert stream.getvalue(
) == "!list_no_generics_wrapper<!list<[!bool<True>, !list<[!bool<False>]>]>>"
# ____ _ _ _ ____ __
# | _ \ __ _ _ __ __ _ _ __ ___ / \ | |_| |_ _ __| _ \ ___ / _|
# | |_) / _` | '__/ _` | '_ ` _ \ / _ \| __| __| '__| | | |/ _ \ |_
# | __/ (_| | | | (_| | | | | | |/ ___ \ |_| |_| | | |_| | __/ _|
# |_| \__,_|_| \__,_|_| |_| |_/_/ \_\__|\__|_| |____/ \___|_|
#
@irdl_attr_definition
class ParamAttrDefAttr(ParametrizedAttribute):
name = "test.param_attr_def_attr"
arg1: ParameterDef[Attribute]
arg2: ParameterDef[BoolData]
def test_irdl_definition():
"""Test that we can get the IRDL definition of a parametrized attribute."""
assert ParamAttrDefAttr.irdl_definition == ParamAttrDef(
"test.param_attr_def_attr", [("arg1", AnyAttr()),
("arg2", BaseAttr(BoolData))])