forked from xdslproject/xdsl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_parser.py
960 lines (812 loc) · 27.6 KB
/
test_parser.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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
import re
from io import StringIO
from typing import cast
import pytest
from xdsl.context import MLContext
from xdsl.dialects.builtin import (
AnyFloatAttr,
AnyIntegerAttr,
ArrayAttr,
Builtin,
DictionaryAttr,
IntAttr,
IntegerAttr,
IntegerType,
LocationAttr,
StringAttr,
SymbolRefAttr,
i32,
)
from xdsl.dialects.test import Test
from xdsl.ir import Attribute, ParametrizedAttribute
from xdsl.irdl import (
IRDLOperation,
irdl_attr_definition,
irdl_op_definition,
prop_def,
region_def,
)
from xdsl.parser import Parser
from xdsl.printer import Printer
from xdsl.utils.exceptions import ParseError, VerifyException
from xdsl.utils.mlir_lexer import MLIRTokenKind, PunctuationSpelling
from xdsl.utils.str_enum import StrEnum
# pyright: reportPrivateUsage=false
@pytest.mark.parametrize(
"data",
[
dict(a=IntAttr(1), b=IntAttr(2), c=IntAttr(3)),
dict(
a=StringAttr("hello"),
b=IntAttr(2),
c=ArrayAttr([IntAttr(2), StringAttr("world")]),
),
{},
],
)
def test_dictionary_attr(data: dict[str, Attribute]):
attr = DictionaryAttr(data)
with StringIO() as io:
Printer(io).print(attr)
text = io.getvalue()
ctx = MLContext()
ctx.load_dialect(Builtin)
attr1 = Parser(ctx, text).parse_attribute()
attr2 = Parser(ctx, "attributes " + text).parse_optional_attr_dict_with_keyword()
assert isinstance(attr1, DictionaryAttr)
assert isinstance(attr2, DictionaryAttr)
assert attr1.data == data
assert attr2.data == data
@pytest.mark.parametrize("text", ["{}", "{a = 1}", "attr {}"])
def test_dictionary_attr_with_keyword_missing(text: str):
ctx = MLContext()
ctx.load_dialect(Builtin)
assert Parser(ctx, text).parse_optional_attr_dict_with_keyword() is None
@pytest.mark.parametrize(
"text, reserved_names",
[("{a = 1}", ["a"]), ("{a = 1}", ["b", "a"]), ("{b = 1, a = 1}", ["a"])],
)
def test_dictionary_attr_with_keyword_reserved(text: str, reserved_names: list[str]):
ctx = MLContext()
ctx.load_dialect(Builtin)
with pytest.raises(ParseError):
Parser(ctx, "attributes" + text).parse_optional_attr_dict_with_keyword(
reserved_names
)
@pytest.mark.parametrize(
"text, expected",
[("{b = 1}", ["a"]), ("{c = 1}", ["b", "a"]), ("{b = 1, a = 1}", ["c"])],
)
def test_dictionary_attr_with_keyword_not_reserved(text: str, expected: list[str]):
ctx = MLContext()
ctx.load_dialect(Builtin)
res = Parser(ctx, "attributes" + text).parse_optional_attr_dict_with_keyword(
expected
)
assert isinstance(res, DictionaryAttr)
@irdl_attr_definition
class DummyAttr(ParametrizedAttribute):
name = "dummy.attr"
def test_parsing():
"""
Test that the default attribute parser does not try to
parse attribute arguments without the delimiters.
"""
ctx = MLContext()
ctx.load_attr(DummyAttr)
prog = '#dummy.attr "foo"'
parser = Parser(ctx, prog)
r = parser.parse_attribute()
assert r == DummyAttr()
@pytest.mark.parametrize(
"text,expected",
[
("@a", StringAttr("a")),
("@_", StringAttr("_")),
("@a1_2", StringAttr("a1_2")),
("@a$_.", StringAttr("a$_.")),
('@"foo"', StringAttr("foo")),
('@"@"', StringAttr("@")),
('@"\\t"', StringAttr("\t")),
("f", None),
('"f"', None),
],
)
def test_symbol_name(text: str, expected: StringAttr | None):
ctx = MLContext()
ctx.load_dialect(Builtin)
parser = Parser(ctx, text)
assert parser.parse_optional_symbol_name() == expected
parser = Parser(ctx, text)
if expected is not None:
assert parser.parse_symbol_name() == expected
else:
with pytest.raises(ParseError):
parser.parse_symbol_name()
@pytest.mark.parametrize(
"ref,expected",
[
("@foo", SymbolRefAttr("foo")),
("@foo::@bar", SymbolRefAttr("foo", ["bar"])),
("@foo::@bar:", SymbolRefAttr("foo", ["bar"])),
('@foo::@"bar"', SymbolRefAttr("foo", ["bar"])),
("@foo::@bar::@baz", SymbolRefAttr("foo", ["bar", "baz"])),
],
)
def test_symref(ref: str, expected: Attribute | None):
"""
Test that symbol references are correctly parsed.
"""
ctx = MLContext()
ctx.load_dialect(Builtin)
parser = Parser(ctx, ref)
parsed_ref = parser.parse_attribute()
assert parsed_ref == expected
@pytest.mark.parametrize(
"text,expected,expect_type",
[
("%foo", ("foo", None), False),
("%-1foo", ("-1foo", None), False),
("%foo : i32", ("foo", i32), True),
("i32 : %bar", None, False),
("i32 : %bar", None, True),
("i32 %bar", None, False),
("i32 %bar", None, True),
("i32", None, False),
("i32", None, True),
],
)
def test_parse_argument(
text: str, expected: tuple[str, Attribute | None] | None, expect_type: bool
):
"""
arg ::= percent-id if expect_type is False
arg ::= percent-id ':' type if expect_type is True
"""
ctx = MLContext()
ctx.load_dialect(Builtin)
# parse_optional_argument
parser = Parser(ctx, text)
res = parser.parse_optional_argument(expect_type)
if expected is not None:
assert res is not None
assert res.name.text[1:] == expected[0]
if expected[1] is not None:
assert isinstance(res, Parser.Argument)
assert res.type == expected[1]
else:
assert isinstance(res, parser.UnresolvedArgument)
else:
assert res is None
# parse_argument
parser = Parser(ctx, text)
if expected is not None:
res = parser.parse_argument(expect_type=expect_type)
assert res is not None
assert res.name.text[1:] == expected[0]
if expected[1] is not None:
assert isinstance(res, Parser.Argument)
assert res.type == expected[1]
else:
assert isinstance(res, parser.UnresolvedArgument)
else:
with pytest.raises(ParseError):
parser.parse_argument(expect_type=expect_type)
@pytest.mark.parametrize(
"text,expect_type",
[
("%foo : %bar", True),
("%foo : ", True),
("%foo", True),
("%foo %bar", True),
],
)
def test_parse_argument_fail(text: str, expect_type: bool):
ctx = MLContext()
ctx.load_dialect(Builtin)
# parse_optional_argument
parser = Parser(ctx, text)
with pytest.raises(ParseError):
parser.parse_optional_argument(expect_type)
# parse_argument
parser = Parser(ctx, text)
with pytest.raises(ParseError):
parser.parse_argument(expect_type=expect_type)
@pytest.mark.parametrize(
"text,num_ops_and_args",
[
# no blocks
("{}", []),
# One entry block
("""{ "test.op"() : () -> () }""", [(1, 0)]),
# One entry block and another block
(
"""{
"test.op"() : () -> ()
^bb0(%x: i32):
"test.op"() : () -> ()
"test.op"() : () -> ()
}""",
[(1, 0), (2, 1)],
),
# One labeled entry block and another block
(
"""{
^bb0:
"test.op"() : () -> ()
"test.op"() : () -> ()
^bb1:
"test.op"() : () -> ()
}""",
[(2, 0), (1, 0)],
),
# One labeled entry block with args and another block
(
"""{
^bb0(%x: i32, %y: i32):
"test.op"() : () -> ()
"test.op"() : () -> ()
^bb1(%z: i32):
"test.op"() : () -> ()
}""",
[(2, 2), (1, 1)],
),
# Not regions
("""^bb:""", None),
("""}""", None),
(""""test.op"() : () -> ()""", None),
],
)
def test_parse_region_no_args(
text: str, num_ops_and_args: list[tuple[int, int]] | None
):
ctx = MLContext()
ctx.load_dialect(Builtin)
ctx.load_dialect(Test)
parser = Parser(ctx, text)
if num_ops_and_args is None:
with pytest.raises(ParseError):
parser.parse_region()
else:
res = parser.parse_region()
for block, (n_ops, n_args) in zip(res.blocks, num_ops_and_args):
assert len(block.ops) == n_ops
assert len(block.args) == n_args
parser = Parser(ctx, text)
res = parser.parse_optional_region()
if num_ops_and_args is None:
assert res is None
else:
assert res is not None
for block, (n_ops, n_args) in zip(res.blocks, num_ops_and_args):
assert len(block.ops) == n_ops
assert len(block.args) == n_args
@pytest.mark.parametrize(
"text",
[
"""{""",
"""{ "test.op"() : () -> ()""",
],
)
def test_parse_region_fail(text: str):
ctx = MLContext()
ctx.load_dialect(Builtin)
ctx.load_dialect(Test)
parser = Parser(ctx, text)
with pytest.raises(ParseError):
parser.parse_region()
parser = Parser(ctx, text)
with pytest.raises(ParseError):
parser.parse_optional_region()
@pytest.mark.parametrize(
"text",
[
"""%x : i32 { "test.op"(%x) : (i32) -> () }""",
"""%x : i32 { "test.op"(%x) : (i32) -> () ^bb0: }""",
],
)
def test_parse_region_with_args(text: str):
"""Parse a region with args already provided."""
ctx = MLContext()
ctx.load_dialect(Builtin)
ctx.load_dialect(Test)
parser = Parser(ctx, text)
arg = parser.parse_argument()
region = parser.parse_region((arg,))
assert len(region.blocks[0].args) == 1
parser = Parser(ctx, text)
arg = parser.parse_argument()
region = parser.parse_optional_region((arg,))
assert region is not None
assert len(region.blocks[0].args) == 1
@pytest.mark.parametrize(
"text",
[
"""%x : i32 { ^bb: "test.op"(%x) : (i32) -> () }""",
"""%x : i32 { ^bb(%y : i32): "test.op"(%x) : (i32) -> () }""",
"""%x : i32 { %x = "test.op"() : () -> (i32) }""",
],
)
def test_parse_region_with_args_fail(text: str):
"""Parse a region with args already provided."""
ctx = MLContext()
ctx.load_dialect(Builtin)
ctx.load_dialect(Test)
parser = Parser(ctx, text)
arg = parser.parse_argument()
with pytest.raises(ParseError):
parser.parse_region((arg,))
parser = Parser(ctx, text)
arg = parser.parse_argument()
with pytest.raises(ParseError):
parser.parse_optional_region((arg,))
@irdl_op_definition
class MultiRegionOp(IRDLOperation):
name = "test.multi_region"
r1 = region_def()
r2 = region_def()
def test_parse_multi_region_mlir():
ctx = MLContext()
ctx.load_op(MultiRegionOp)
op_str = """
"test.multi_region" () ({
}, {
}) : () -> ()
"""
parser = Parser(ctx, op_str)
op = parser.parse_op()
assert len(op.regions) == 2
def test_parse_block_name():
block_str = """
^bb0(%name: i32, %100: i32):
"""
ctx = MLContext()
parser = Parser(ctx, block_str)
block = parser._parse_block()
assert block.args[0].name_hint == "name"
assert block.args[1].name_hint is None
@pytest.mark.parametrize(
"delimiter,open_bracket,close_bracket",
[
(Parser.Delimiter.NONE, "", ""),
(Parser.Delimiter.PAREN, "(", ")"),
(Parser.Delimiter.SQUARE, "[", "]"),
(Parser.Delimiter.BRACES, "{", "}"),
(Parser.Delimiter.ANGLE, "<", ">"),
],
)
def test_parse_comma_separated_list(
delimiter: Parser.Delimiter, open_bracket: str, close_bracket: str
):
input = open_bracket + "2, 4, 5" + close_bracket
parser = Parser(MLContext(), input)
res = parser.parse_comma_separated_list(delimiter, parser.parse_integer, " in test")
assert res == [2, 4, 5]
parser = Parser(MLContext(), input)
if delimiter is Parser.Delimiter.NONE:
res = parser.parse_optional_undelimited_comma_separated_list(
parser.parse_optional_integer, parser.parse_integer
)
else:
res = parser.parse_optional_comma_separated_list(
delimiter, parser.parse_integer, " in test"
)
assert res == [2, 4, 5]
@pytest.mark.parametrize(
"delimiter,open_bracket,close_bracket",
[
(Parser.Delimiter.PAREN, "(", ")"),
(Parser.Delimiter.SQUARE, "[", "]"),
(Parser.Delimiter.BRACES, "{", "}"),
(Parser.Delimiter.ANGLE, "<", ">"),
],
)
def test_parse_comma_separated_list_empty(
delimiter: Parser.Delimiter, open_bracket: str, close_bracket: str
):
input = open_bracket + close_bracket
parser = Parser(MLContext(), input)
res = parser.parse_comma_separated_list(delimiter, parser.parse_integer, " in test")
assert res == []
def test_parse_comma_separated_list_none_delimiter_empty():
parser = Parser(MLContext(), "o")
with pytest.raises(ParseError):
parser.parse_comma_separated_list(
Parser.Delimiter.NONE, parser.parse_integer, " in test"
)
def test_parse_comma_separated_list_none_delimiter_two_no_comma():
"""Test that a list without commas will only parse the first element."""
parser = Parser(MLContext(), "1 2")
res = parser.parse_comma_separated_list(
Parser.Delimiter.NONE, parser.parse_integer, " in test"
)
assert res == [1]
assert parser.parse_optional_integer() is not None
parser = Parser(MLContext(), "1 2")
parser.parse_optional_undelimited_comma_separated_list(
parser.parse_optional_integer, parser.parse_integer
)
assert res == [1]
assert parser.parse_optional_integer() is not None
@pytest.mark.parametrize(
"delimiter",
[
(Parser.Delimiter.PAREN),
(Parser.Delimiter.SQUARE),
(Parser.Delimiter.BRACES),
(Parser.Delimiter.ANGLE),
],
)
def test_parse_optional_comma_separated_list(delimiter: Parser.Delimiter):
parser = Parser(MLContext(), "o")
res = parser.parse_optional_comma_separated_list(delimiter, parser.parse_integer)
assert res is None
def test_parse_optional_undelimited_comma_separated_list_empty():
parser = Parser(MLContext(), "o")
res = parser.parse_optional_undelimited_comma_separated_list(
parser.parse_optional_integer, parser.parse_integer
)
assert res is None
@pytest.mark.parametrize(
"delimiter,open_bracket,close_bracket",
[
(Parser.Delimiter.PAREN, "(", ")"),
(Parser.Delimiter.SQUARE, "[", "]"),
(Parser.Delimiter.BRACES, "{", "}"),
(Parser.Delimiter.ANGLE, "<", ">"),
],
)
def test_parse_comma_separated_list_error_element(
delimiter: Parser.Delimiter, open_bracket: str, close_bracket: str
):
input = open_bracket + "o" + close_bracket
parser = Parser(MLContext(), input)
with pytest.raises(ParseError, match="Expected integer literal"):
parser.parse_comma_separated_list(delimiter, parser.parse_integer, " in test")
parser = Parser(MLContext(), input)
with pytest.raises(ParseError, match="Expected integer literal"):
parser.parse_optional_comma_separated_list(
delimiter, parser.parse_integer, " in test"
)
@pytest.mark.parametrize(
"delimiter,open_bracket,close_bracket",
[
(Parser.Delimiter.PAREN, "(", ")"),
(Parser.Delimiter.SQUARE, "[", "]"),
(Parser.Delimiter.BRACES, "{", "}"),
(Parser.Delimiter.ANGLE, "<", ">"),
],
)
def test_parse_comma_separated_list_error_delimiters(
delimiter: Parser.Delimiter, open_bracket: str, close_bracket: str
):
input = open_bracket + "2, 4 5"
parser = Parser(MLContext(), input)
with pytest.raises(
ParseError, match=re.escape(f"'{close_bracket}' expected in test")
) as e:
parser.parse_comma_separated_list(delimiter, parser.parse_integer, " in test")
assert e.value.span.text == "5"
parser = Parser(MLContext(), input)
with pytest.raises(
ParseError, match=re.escape(f"'{close_bracket}' expected in test")
) as e:
parser.parse_optional_comma_separated_list(
delimiter, parser.parse_integer, " in test"
)
assert e.value.span.text == "5"
@pytest.mark.parametrize(
"punctuation", list(MLIRTokenKind.get_punctuation_spelling_to_kind_dict().values())
)
def test_is_punctuation_true(punctuation: MLIRTokenKind):
assert punctuation.is_punctuation()
@pytest.mark.parametrize(
"punctuation",
[MLIRTokenKind.BARE_IDENT, MLIRTokenKind.EOF, MLIRTokenKind.INTEGER_LIT],
)
def test_is_punctuation_false(punctuation: MLIRTokenKind):
assert not punctuation.is_punctuation()
@pytest.mark.parametrize(
"punctuation", list(MLIRTokenKind.get_punctuation_spelling_to_kind_dict().values())
)
def test_is_spelling_of_punctuation_true(punctuation: MLIRTokenKind):
value = cast(PunctuationSpelling, punctuation.value)
assert MLIRTokenKind.is_spelling_of_punctuation(value)
@pytest.mark.parametrize("punctuation", [">-", "o", "4", "$", "_", "@"])
def test_is_spelling_of_punctuation_false(punctuation: str):
assert not MLIRTokenKind.is_spelling_of_punctuation(punctuation)
@pytest.mark.parametrize(
"punctuation", list(MLIRTokenKind.get_punctuation_spelling_to_kind_dict().values())
)
def test_get_punctuation_kind(punctuation: MLIRTokenKind):
value = cast(PunctuationSpelling, punctuation.value)
assert punctuation.get_punctuation_kind_from_spelling(value) == punctuation
@pytest.mark.parametrize(
"punctuation", list(MLIRTokenKind.get_punctuation_spelling_to_kind_dict().keys())
)
def test_parse_punctuation(punctuation: PunctuationSpelling):
parser = Parser(MLContext(), punctuation)
res = parser.parse_punctuation(punctuation)
assert res == punctuation
assert parser._parse_token(MLIRTokenKind.EOF, "").kind == MLIRTokenKind.EOF
@pytest.mark.parametrize(
"punctuation", list(MLIRTokenKind.get_punctuation_spelling_to_kind_dict().keys())
)
def test_parse_punctuation_fail(punctuation: PunctuationSpelling):
parser = Parser(MLContext(), "e +")
with pytest.raises(ParseError) as e:
parser.parse_punctuation(punctuation, " in test")
assert e.value.span.text == "e"
assert e.value.msg == "Expected '" + punctuation + "' in test"
@pytest.mark.parametrize(
"punctuation", list(MLIRTokenKind.get_punctuation_spelling_to_kind_dict().keys())
)
def test_parse_optional_punctuation(punctuation: PunctuationSpelling):
parser = Parser(MLContext(), punctuation)
res = parser.parse_optional_punctuation(punctuation)
assert res == punctuation
assert parser._parse_token(MLIRTokenKind.EOF, "").kind == MLIRTokenKind.EOF
@pytest.mark.parametrize(
"punctuation", list(MLIRTokenKind.get_punctuation_spelling_to_kind_dict().keys())
)
def test_parse_optional_punctuation_fail(punctuation: PunctuationSpelling):
parser = Parser(MLContext(), "e +")
assert parser.parse_optional_punctuation(punctuation) is None
@pytest.mark.parametrize(
"text, expected_value",
[
("true", True),
("false", False),
("True", None),
("False", None),
],
)
def test_parse_boolean(text: str, expected_value: bool | None):
parser = Parser(MLContext(), text)
assert parser.parse_optional_boolean() == expected_value
parser = Parser(MLContext(), text)
if expected_value is None:
with pytest.raises(ParseError):
parser.parse_boolean()
else:
assert parser.parse_boolean() == expected_value
@pytest.mark.parametrize(
"text, expected_value, allow_boolean, allow_negative",
[
("42", 42, False, False),
("42", 42, True, False),
("42", 42, False, True),
("42", 42, True, True),
("-1", None, False, False),
("-1", None, True, False),
("-1", -1, False, True),
("-1", -1, True, True),
("true", None, False, False),
("true", 1, True, False),
("true", None, False, True),
("true", 1, True, True),
("false", None, False, False),
("false", 0, True, False),
("false", None, False, True),
("false", 0, True, True),
("True", None, True, True),
("False", None, True, True),
("0x1a", 26, False, False),
("0x1a", 26, True, False),
("0x1a", 26, False, True),
("0x1a", 26, True, True),
("-0x1a", None, False, False),
("-0x1a", None, True, False),
("-0x1a", -26, False, True),
("-0x1a", -26, True, True),
],
)
def test_parse_int(
text: str, expected_value: int | None, allow_boolean: bool, allow_negative: bool
):
parser = Parser(MLContext(), text)
assert (
parser.parse_optional_integer(
allow_boolean=allow_boolean, allow_negative=allow_negative
)
== expected_value
)
parser = Parser(MLContext(), text)
if expected_value is None:
with pytest.raises(ParseError):
parser.parse_integer(
allow_boolean=allow_boolean, allow_negative=allow_negative
)
else:
assert (
parser.parse_integer(
allow_boolean=allow_boolean, allow_negative=allow_negative
)
== expected_value
)
@pytest.mark.parametrize(
"text, allow_boolean, allow_negative",
[
("-false", False, True),
("-false", True, True),
("-true", False, True),
("-true", True, True),
("-k", True, True),
("-(", False, True),
],
)
def test_parse_optional_int_error(text: str, allow_boolean: bool, allow_negative: bool):
"""Test that parsing a negative without an integer after raise an error."""
parser = Parser(MLContext(), text)
with pytest.raises(ParseError):
parser.parse_optional_integer(
allow_boolean=allow_boolean, allow_negative=allow_negative
)
parser = Parser(MLContext(), text)
with pytest.raises(ParseError):
parser.parse_integer(allow_boolean=allow_boolean, allow_negative=allow_negative)
@pytest.mark.parametrize(
"text, allow_boolean, expected_value",
[
("42", False, 42),
("-1", False, -1),
("true", False, None),
("false", False, None),
("0x1a", False, 26),
("-0x1a", False, -26),
("0.", False, 0.0),
("1.", False, 1.0),
("0.2", False, 0.2),
("38.1243", False, 38.1243),
("92.54e43", False, 92.54e43),
("92.5E43", False, 92.5e43),
("43.3e-54", False, 43.3e-54),
("32.E+25", False, 32.0e25),
("true", True, 1),
("false", True, 0),
("42", True, 42),
("0.2", True, 0.2),
],
)
def test_parse_number(
text: str, allow_boolean: bool, expected_value: int | float | None
):
parser = Parser(MLContext(), text)
assert parser.parse_optional_number(allow_boolean=allow_boolean) == expected_value
parser = Parser(MLContext(), text)
if expected_value is None:
with pytest.raises(ParseError):
parser.parse_number()
else:
assert parser.parse_number(allow_boolean=allow_boolean) == expected_value
@pytest.mark.parametrize(
"text, expected_value",
[
("3: i16", IntegerAttr(3, 16)),
("24: i32", IntegerAttr(24, 32)),
("0: index", IntegerAttr.from_index_int_value(0)),
("-64: i64", IntegerAttr(-64, 64)),
("-64.4: f64", AnyFloatAttr(-64.4, 64)),
("32.4: f32", AnyFloatAttr(32.4, 32)),
("0x7e00 : f16", AnyFloatAttr(float("nan"), 16)),
("0x7c00 : f16", AnyFloatAttr(float("inf"), 16)),
("0xfc00 : f16", AnyFloatAttr(float("-inf"), 16)),
("0x7fc00000 : f32", AnyFloatAttr(float("nan"), 32)),
("0x7f800000 : f32", AnyFloatAttr(float("inf"), 32)),
("0xff800000 : f32", AnyFloatAttr(float("-inf"), 32)),
("0x7ff8000000000000 : f64", AnyFloatAttr(float("nan"), 64)),
("0x7ff0000000000000 : f64", AnyFloatAttr(float("inf"), 64)),
("0xfff0000000000000 : f64", AnyFloatAttr(float("-inf"), 64)),
# ("3 : f64", None), # todo this fails in mlir-opt but not in xdsl
],
)
def test_parse_optional_builtin_int_or_float_attr(
text: str, expected_value: AnyIntegerAttr | AnyFloatAttr | None
):
parser = Parser(MLContext(), text)
if expected_value is None:
with pytest.raises(ValueError):
parser.parse_optional_builtin_int_or_float_attr()
else:
assert parser.parse_optional_builtin_int_or_float_attr() == expected_value
@pytest.mark.parametrize(
"text, allow_boolean",
[
("-false", False),
("-true", False),
("-false", True),
("-true", True),
("-k", False),
("-(", False),
],
)
def test_parse_number_error(text: str, allow_boolean: bool):
"""
Test that parsing a negative without an
integer or a float after raise an error.
"""
parser = Parser(MLContext(), text)
with pytest.raises(ParseError):
parser.parse_optional_number(allow_boolean=allow_boolean)
parser = Parser(MLContext(), text)
with pytest.raises(ParseError):
parser.parse_number(allow_boolean=allow_boolean)
@irdl_op_definition
class PropertyOp(IRDLOperation):
name = "test.prop_op"
first = prop_def(StringAttr)
second = prop_def(IntegerAttr[IntegerType])
def test_properties_retrocompatibility():
# Straightforward case
ctx = MLContext()
ctx.load_op(PropertyOp)
parser = Parser(ctx, '"test.prop_op"() <{first = "str", second = 42}> : () -> ()')
op = parser.parse_op()
assert isinstance(op, PropertyOp)
op.verify()
# Retrocompatibility case, only target
parser = Parser(ctx, '"test.prop_op"() {first = "str", second = 42} : () -> ()')
retro_op = parser.parse_op()
assert isinstance(retro_op, PropertyOp)
retro_op.verify()
assert op.attributes == retro_op.attributes
assert op.properties == retro_op.properties
# We ***do not*** try to be smarter than this. If properties are present, we parse
# and verify as-is.
parser = Parser(ctx, '"test.prop_op"() <{first = "str"}> {second = 42} : () -> ()')
wrong_op = parser.parse_op()
assert list(wrong_op.properties.keys()) == ["first"]
assert list(wrong_op.attributes.keys()) == ["second"]
with pytest.raises(
VerifyException, match="Operation does not verify: property second expected"
):
wrong_op.verify()
def test_parse_location():
ctx = MLContext()
attr = Parser(ctx, "loc(unknown)").parse_optional_location()
assert attr == LocationAttr()
@pytest.mark.parametrize(
"keyword,expected",
[
("public", StringAttr("public")),
("nested", StringAttr("nested")),
("private", StringAttr("private")),
("privateeee", None),
("unknown", None),
],
)
def test_parse_visibility(keyword: str, expected: StringAttr | None):
assert Parser(MLContext(), keyword).parse_optional_visibility_keyword() == expected
parser = Parser(MLContext(), keyword)
if expected is None:
with pytest.raises(ParseError, match="expect symbol visibility keyword"):
parser.parse_visibility_keyword()
else:
assert parser.parse_visibility_keyword() == expected
class MyEnum(StrEnum):
A = "a"
B = "b"
C = "c"
@pytest.mark.parametrize(
"keyword, expected",
[
("a", MyEnum.A),
("b", MyEnum.B),
("c", MyEnum.C),
("cc", None),
],
)
def test_parse_str_enum(keyword: str, expected: MyEnum | None):
assert Parser(MLContext(), keyword).parse_optional_str_enum(MyEnum) == expected
parser = Parser(MLContext(), keyword)
if expected is None:
with pytest.raises(ParseError, match="Expected `a`, `b`, or `c`"):
parser.parse_str_enum(MyEnum)
else:
assert parser.parse_str_enum(MyEnum) == expected
class MySingletonEnum(StrEnum):
A = "a"
def test_parse_singleton_enum_fail():
parser = Parser(MLContext(), "b")
with pytest.raises(ParseError, match="Expected `a`"):
parser.parse_str_enum(MySingletonEnum)