-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathtest_printer.py
1019 lines (780 loc) · 27.3 KB
/
test_printer.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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from io import StringIO
import pytest
from xdsl.builder import ImplicitBuilder
from xdsl.context import Context
from xdsl.dialects import test
from xdsl.dialects.arith import AddiOp, Arith, ConstantOp
from xdsl.dialects.builtin import (
AnyFloat,
Builtin,
FloatAttr,
FunctionType,
IntAttr,
IntegerType,
ModuleOp,
SymbolRefAttr,
UnitAttr,
f32,
i32,
)
from xdsl.dialects.func import Func
from xdsl.ir import (
Attribute,
Block,
Operation,
ParametrizedAttribute,
Region,
)
from xdsl.irdl import (
IRDLOperation,
ParameterDef,
irdl_attr_definition,
irdl_op_definition,
operand_def,
opt_attr_def,
result_def,
var_operand_def,
var_result_def,
)
from xdsl.parser import AttrParser, Parser
from xdsl.printer import Printer
from xdsl.utils.diagnostic import Diagnostic
from xdsl.utils.exceptions import DiagnosticException, ParseError
from xdsl.utils.test_value import TestSSAValue
def test_simple_forgotten_op():
"""Test that the parsing of an undefined operand gives it a name."""
ctx = Context()
ctx.load_dialect(Arith)
lit = ConstantOp.from_int_and_width(42, 32)
add = AddiOp(lit, lit)
add.verify()
expected = """%0 = "arith.addi"(%1, %1) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32"""
assert_print_op(add, expected)
def test_print_op_location():
"""Test that an op can be printed with its location."""
ctx = Context()
ctx.load_dialect(test.Test)
add = test.TestOp(result_types=[i32])
add.verify()
expected = """%0 = "test.op"() : () -> i32 loc(unknown)"""
assert_print_op(add, expected, print_debuginfo=True)
@irdl_op_definition
class UnitAttrOp(IRDLOperation):
name = "unit_attr_op"
parallelize = opt_attr_def(UnitAttr)
def test_unit_attr():
"""Test that a UnitAttr can be defined and printed"""
expected = """
"unit_attr_op"() {parallelize} : () -> ()
"""
unit_op = UnitAttrOp.build(attributes={"parallelize": UnitAttr([])})
assert_print_op(unit_op, expected)
def test_added_unit_attr():
"""Test that a UnitAttr can be added to an op, even if its not defined as a field."""
expected = """
"unit_attr_op"() {parallelize, vectorize} : () -> ()
"""
unitop = UnitAttrOp.build(
attributes={"parallelize": UnitAttr([]), "vectorize": UnitAttr([])}
)
assert_print_op(unitop, expected)
# ____ _ _ _
# | _ \(_) __ _ __ _ _ __ ___ ___| |_(_) ___
# | | | | |/ _` |/ _` | '_ \ / _ \/ __| __| |/ __|
# | |_| | | (_| | (_| | | | | (_) \__ \ |_| | (__
# |____/|_|\__,_|\__, |_| |_|\___/|___/\__|_|\___|
# |___/
#
def test_op_message():
"""Test that an operation message can be printed."""
prog = """\
"builtin.module"() ({
%0 = arith.constant 42 : i32
%1 = "arith.addi"(%0, %0) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()
"""
expected = """\
"builtin.module"() ({
%0 = "arith.constant"() <{value = 42 : i32}> : () -> i32
^^^^^^^^^^^^^^^^^^^^^
| Test message
---------------------
%1 = "arith.addi"(%0, %0) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()
"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
parser = Parser(ctx, prog)
module = parser.parse_module()
diagnostic = Diagnostic()
first_op = module.ops.first
assert first_op is not None
diagnostic.add_message(first_op, "Test message")
assert_print_op(module, expected, diagnostic=diagnostic)
def test_two_different_op_messages():
"""Test that an operation message can be printed."""
prog = """\
"builtin.module"() ({
%0 = arith.constant 42 : i32
%1 = "arith.addi"(%0, %0) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()"""
expected = """\
"builtin.module"() ({
%0 = "arith.constant"() <{value = 42 : i32}> : () -> i32
^^^^^^^^^^^^^^^^^^^^^
| Test message 1
---------------------
%1 = "arith.addi"(%0, %0) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
^^^^^^^^^^^^^^^^^
| Test message 2
-----------------
}) : () -> ()"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
parser = Parser(ctx, prog)
module = parser.parse_module()
diagnostic = Diagnostic()
first_op, second_op = list(module.ops)
diagnostic.add_message(first_op, "Test message 1")
diagnostic.add_message(second_op, "Test message 2")
assert_print_op(module, expected, diagnostic=diagnostic)
def test_two_same_op_messages():
"""Test that an operation message can be printed."""
prog = """\
"builtin.module"() ({
%0 = arith.constant 42 : i32
%1 = "arith.addi"(%0, %0) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()"""
expected = """\
"builtin.module"() ({
%0 = "arith.constant"() <{value = 42 : i32}> : () -> i32
^^^^^^^^^^^^^^^^^^^^^
| Test message 1
---------------------
^^^^^^^^^^^^^^^^^^^^^
| Test message 2
---------------------
%1 = "arith.addi"(%0, %0) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
parser = Parser(ctx, prog)
module = parser.parse_module()
diagnostic = Diagnostic()
first_op, _second_op = list(module.ops)
diagnostic.add_message(first_op, "Test message 1")
diagnostic.add_message(first_op, "Test message 2")
assert_print_op(module, expected, diagnostic=diagnostic)
def test_op_message_with_region():
"""Test that an operation message can be printed on an operation with a region."""
prog = """\
"builtin.module"() ({
%0 = arith.constant 42 : i32
%1 = "arith.addi"(%0, %0) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()"""
expected = """\
"builtin.module"() ({
^^^^^^^^^^^^^^^^
| Test
----------------
%0 = "arith.constant"() <{value = 42 : i32}> : () -> i32
%1 = "arith.addi"(%0, %0) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
parser = Parser(ctx, prog)
module = parser.parse_op()
diagnostic = Diagnostic()
diagnostic.add_message(module, "Test")
assert_print_op(module, expected, diagnostic=diagnostic)
def test_op_message_with_region_and_overflow():
"""
Test that an operation message can be printed on an operation with a region,
where the message is bigger than the operation.
"""
prog = """\
"builtin.module"() ({
%0 = arith.constant 42 : i32
%1 = "arith.addi"(%0, %0) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()"""
expected = """\
"builtin.module"() ({
^^^^^^^^^^^^^^^^---
| Test long message
-------------------
%0 = "arith.constant"() <{value = 42 : i32}> : () -> i32
%1 = "arith.addi"(%0, %0) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
parser = Parser(ctx, prog)
module = parser.parse_op()
diagnostic = Diagnostic()
diagnostic.add_message(module, "Test long message")
assert_print_op(module, expected, diagnostic=diagnostic)
def test_diagnostic():
"""
Test that an operation message can be printed on an operation with a region,
where the message is bigger than the operation.
"""
prog = """\
"builtin.module"() ({
%0 = arith.constant 42 : i32
%1 = "arith.addi"(%0, %0) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
parser = Parser(ctx, prog)
module = parser.parse_op()
diag = Diagnostic()
diag.add_message(module, "Test")
with pytest.raises(DiagnosticException):
diag.raise_exception("test message", module)
# ____ ____ _ _ _
# / ___/ ___| / \ | \ | | __ _ _ __ ___ ___
# \___ \___ \ / _ \ | \| |/ _` | '_ ` _ \ / _ \
# ___) |__) / ___ \| |\ | (_| | | | | | | __/
# |____/____/_/ \_\_| \_|\__,_|_| |_| |_|\___|
#
def test_print_custom_name():
"""
Test that an SSAValue, that is a name and not a number, reserves that name
"""
prog = """\
"builtin.module"() ({
%i = arith.constant 42 : i32
%213 = "arith.addi"(%i, %i) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()
"""
expected = """\
"builtin.module"() ({
%i = "arith.constant"() <{value = 42 : i32}> : () -> i32
%0 = "arith.addi"(%i, %i) <{overflowFlags = #arith.overflow<none>}> : (i32, i32) -> i32
}) : () -> ()
"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
parser = Parser(ctx, prog)
module = parser.parse_op()
assert_print_op(module, expected)
def test_print_clashing_names():
"""
Test the printer's value name printing logic's robustness against clashing names.
This example now expects to print names i, i_1, i_2; it used to print i, i_1, i_1,
printing a duplicate name for two values, meaning invalid IR as input for both MLIR
and xDSL.
"""
expected = """\
"builtin.module"() ({
%i = "test.op"() : () -> i32
%i_1 = "test.op"() : () -> i32
%i_2 = "test.op"() : () -> i32
}) : () -> ()
"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
with ImplicitBuilder((module := ModuleOp([])).body):
i = test.TestOp.create(result_types=[i32])
i.results[0].name_hint = "i"
j = test.TestOp.create(result_types=[i32])
j.results[0].name_hint = "i"
k = test.TestOp.create(result_types=[i32])
k.results[0].name_hint = "i_1"
assert_print_op(module, expected)
def test_print_custom_block_arg_name():
block = Block(arg_types=[i32, i32])
block.args[0].name_hint = "test"
block.args[1].name_hint = "test"
io = StringIO()
p = Printer(stream=io)
p.print_block(block)
assert io.getvalue() == """\n^0(%test : i32, %test_1 : i32):"""
def test_print_block_argument():
"""Print a block argument."""
block = Block(arg_types=[i32, i32])
io = StringIO()
p = Printer(stream=io)
p.print_block_argument(block.args[0])
p.print(", ")
p.print_block_argument(block.args[1], print_type=False)
assert io.getvalue() == """%0 : i32, %1"""
def test_print_block_argument_location():
"""Print a block argument with location."""
block = Block(arg_types=[i32, i32])
io = StringIO()
p = Printer(stream=io, print_debuginfo=True)
p.print_block_argument(block.args[0])
p.print(", ")
p.print_block_argument(block.args[1])
assert io.getvalue() == """%0 : i32 loc(unknown), %1 : i32 loc(unknown)"""
def test_print_block():
"""Print a block."""
block = Block(arg_types=[i32, i32])
block.add_op(test.TestOp(operands=(block.args[1],)))
# Print block arguments inside the block
io = StringIO()
p = Printer(stream=io)
p.print_block(block)
assert (
io.getvalue() == """\n^0(%0 : i32, %1 : i32):\n "test.op"(%1) : (i32) -> ()"""
)
def test_print_block_without_arguments():
"""Print a block and its arguments separately."""
block = Block(arg_types=[i32, i32])
block.add_op(test.TestOp(operands=(block.args[1],)))
# Print block arguments separately from the block
io = StringIO()
p = Printer(stream=io)
p.print_block_argument(block.args[0])
p.print(", ")
p.print_block_argument(block.args[1])
p.print_block(block, print_block_args=False)
assert io.getvalue() == """%0 : i32, %1 : i32\n "test.op"(%1) : (i32) -> ()"""
def test_print_block_with_terminator():
"""Print a block and with its terminator."""
block = Block(ops=[test.TestOp.create(), test.TestTermOp.create()])
# Print block ops including block terminator
io = StringIO()
p = Printer(stream=io)
p.print_block(block, print_block_terminator=True)
assert (
io.getvalue()
== """
^0:
"test.op"() : () -> ()
"test.termop"() : () -> ()"""
)
def test_print_block_without_terminator():
"""Print a block and its terminator separately."""
term_op = test.TestTermOp.create()
block = Block(ops=[test.TestOp.create(), term_op])
# Print block ops separately from the block terminator
io = StringIO()
p = Printer(stream=io)
p.print_block(block, print_block_terminator=False)
assert (
io.getvalue()
== """
^0:
"test.op"() : () -> ()"""
)
def test_print_region():
"""Print a region."""
block = Block(arg_types=[i32, i32])
block.add_op(test.TestOp(operands=(block.args[1],)))
region = Region(block)
io = StringIO()
p = Printer(stream=io)
p.print_region(region)
assert (
io.getvalue()
== """{\n^0(%0 : i32, %1 : i32):\n "test.op"(%1) : (i32) -> ()\n}"""
)
def test_print_region_without_arguments():
"""Print a region and its arguments separately."""
block = Block(arg_types=[i32, i32])
block.add_op(test.TestOp(operands=(block.args[1],)))
region = Region(block)
io = StringIO()
p = Printer(stream=io)
p.print_block_argument(block.args[0])
p.print(", ")
p.print_block_argument(block.args[1])
p.print(" ")
p.print_region(region, print_entry_block_args=False)
assert io.getvalue() == """%0 : i32, %1 : i32 {\n "test.op"(%1) : (i32) -> ()\n}"""
def test_print_region_empty_block():
"""
Print a region with an empty block, and specify that
empty entry blocks shouldn't be printed.
"""
block = Block()
region = Region(block)
io = StringIO()
p = Printer(stream=io)
p.print_region(region, print_empty_block=False)
assert io.getvalue() == """{\n}"""
def test_print_region_empty_block_with_args():
"""
Print a region with an empty block and arguments, and specify that
empty entry blocks shouldn't be printed.
"""
block = Block(arg_types=[i32, i32])
region = Region(block)
io = StringIO()
p = Printer(stream=io)
p.print_region(region, print_empty_block=False)
assert io.getvalue() == """{\n^0(%0 : i32, %1 : i32):\n}"""
# ____ _ _____ _
# / ___| _ ___| |_ ___ _ __ ___ | ___|__ _ __ _ __ ___ __ _| |_
# | | | | | / __| __/ _ \| '_ ` _ \| |_ / _ \| '__| '_ ` _ \ / _` | __|
# | |__| |_| \__ \ || (_) | | | | | | _| (_) | | | | | | | | (_| | |_
# \____\__,_|___/\__\___/|_| |_| |_|_| \___/|_| |_| |_| |_|\__,_|\__|
#
@irdl_op_definition
class PlusCustomFormatOp(IRDLOperation):
name = "test.add"
lhs = operand_def(IntegerType)
rhs = operand_def(IntegerType)
res = result_def(IntegerType)
@classmethod
def parse(cls, parser: Parser) -> PlusCustomFormatOp:
lhs = parser.parse_operand("Expected SSA Value name here!")
parser.parse_characters("+", "Malformed operation format, expected `+`!")
rhs = parser.parse_operand("Expected SSA Value name here!")
parser.parse_punctuation(":")
type = parser.parse_type()
return PlusCustomFormatOp.create(operands=[lhs, rhs], result_types=[type])
def print(self, printer: Printer):
printer.print(" ", self.lhs, " + ", self.rhs, " : ", self.res.type)
def test_generic_format():
"""
Test that we can use generic formats in operations.
"""
prog = """
"builtin.module"() ({
%0 = arith.constant 42 : i32
%1 = "test.add"(%0, %0) : (i32, i32) -> i32
}) : () -> ()"""
expected = """\
builtin.module {
%0 = arith.constant 42 : i32
%1 = test.add %0 + %0 : i32
}
"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
ctx.load_op(PlusCustomFormatOp)
parser = Parser(ctx, prog)
module = parser.parse_op()
assert_print_op(module, expected, print_generic_format=False)
def test_custom_format():
"""
Test that we can use custom formats in operations.
"""
prog = """\
builtin.module {
%0 = "arith.constant"() <{value = 42 : i32}> : () -> i32
%1 = test.add %0 + %0 : i32
}
"""
expected = """\
builtin.module {
%0 = arith.constant 42 : i32
%1 = test.add %0 + %0 : i32
}
"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
ctx.load_op(PlusCustomFormatOp)
parser = Parser(ctx, prog)
module = parser.parse_op()
assert_print_op(module, expected, print_generic_format=False)
def test_custom_format_II():
"""
Test that we can print using generic formats.
"""
prog = """\
"builtin.module"() ({
%0 = arith.constant 42 : i32
%1 = test.add %0 + %0 : i32
}) : () -> ()
"""
expected = """\
"builtin.module"() ({
%0 = "arith.constant"() <{value = 42 : i32}> : () -> i32
%1 = "test.add"(%0, %0) : (i32, i32) -> i32
}) : () -> ()
"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
ctx.load_op(PlusCustomFormatOp)
parser = Parser(ctx, prog)
module = parser.parse_op()
assert_print_op(module, expected, print_generic_format=True)
@irdl_op_definition
class NoCustomFormatOp(IRDLOperation):
name = "test.no_custom_format"
ops = var_operand_def()
res = var_result_def()
def test_missing_custom_format():
"""
Test that we can print using generic formats.
"""
prog = """\
"builtin.module"() ({
%0 = arith.constant 42 : i32
%1 = test.no_custom_format(%0) : (i32) -> i32
}) : () -> ()
"""
ctx = Context()
ctx.load_dialect(Arith)
ctx.load_dialect(Builtin)
ctx.load_op(NoCustomFormatOp)
parser = Parser(ctx, prog)
with pytest.raises(ParseError):
parser.parse_op()
@irdl_attr_definition
class CustomFormatAttr(ParametrizedAttribute):
name = "test.custom"
attr: ParameterDef[IntAttr]
@classmethod
def parse_parameters(cls, parser: AttrParser) -> list[Attribute]:
parser.parse_characters("<")
if parser.parse_optional_keyword("zero") is not None:
parser.parse_characters(">")
return [IntAttr(0)]
if parser.parse_optional_keyword("one") is not None:
parser.parse_characters(">")
return [IntAttr(1)]
pytest.fail("zero or one expected")
def print_parameters(self, printer: Printer) -> None:
assert 0 <= self.attr.data <= 1
printer.print("<", "zero" if self.attr.data == 0 else "one", ">")
@irdl_op_definition
class AnyOp(IRDLOperation):
name = "test.any"
def test_custom_format_attr():
"""
Test that we can parse and print attributes using custom formats.
"""
prog = """\
"builtin.module"() ({
"test.any"() {attr = #test.custom<zero>} : () -> ()
}) : () -> ()
"""
expected = """\
"builtin.module"() ({
"test.any"() {attr = #test.custom<zero>} : () -> ()
}) : () -> ()"""
ctx = Context()
ctx.load_dialect(Builtin)
ctx.load_op(AnyOp)
ctx.load_attr(CustomFormatAttr)
parser = Parser(ctx, prog)
module = parser.parse_op()
assert_print_op(module, expected)
def test_dictionary_attr():
"""Test that a DictionaryAttr can be parsed and then printed."""
prog = """
"func.func"() <{sym_name = "test", function_type = i64, sym_visibility = "private", unit_attr}> {arg_attrs = {key_one = "value_one", key_two = "value_two", key_three = 72 : i64, unit_attr}} : () -> ()
"""
ctx = Context()
ctx.load_dialect(Builtin)
ctx.load_dialect(Func)
parser = Parser(ctx, prog)
parsed = parser.parse_op()
assert_print_op(parsed, prog)
def test_densearray_attr():
"""Test that a DenseArrayAttr can be parsed and then printed."""
prog = """
"func.func"() <{sym_name = "test", function_type = i64, sym_visibility = "private", unit_attr}> {bool_attrs = array<i1: false, true>, int_attr = array<i32: 19, 23, 55>, float_attr = array<f32: 0.3400000035762787>} : () -> ()
"""
ctx = Context()
ctx.load_dialect(Builtin)
ctx.load_dialect(Func)
parser = Parser(ctx, prog)
parsed = parser.parse_op()
assert_print_op(parsed, prog)
def test_float():
printer = Printer()
def _test_float_print(expected: str, value: float, type: AnyFloat):
value = FloatAttr(value, type).value.data
io = StringIO()
printer.stream = io
printer.print_float(value, type)
assert io.getvalue() == expected
_test_float_print("3.000000e+00", 3, f32)
_test_float_print("-3.000000e+00", -3, f32)
_test_float_print("3.140000e+00", 3.14, f32)
_test_float_print("3.140000e+08", 3.14e8, f32)
_test_float_print("3.14285707", 22 / 7, f32)
_test_float_print("0x4D95DCF5", 22e8 / 7, f32)
_test_float_print("3.14285714e+16", 22e16 / 7, f32)
_test_float_print("-3.14285707", -22 / 7, f32)
def test_float_attr():
printer = Printer()
def _test_float_attr(value: float, type: AnyFloat):
value = FloatAttr(value, type).value.data
io_float = StringIO()
printer.stream = io_float
printer.print_float(value, type)
io_attr = StringIO()
printer.stream = io_attr
printer.print_float_attr(FloatAttr(value, type))
assert io_float.getvalue() == io_attr.getvalue()
for value in (
3,
3.14,
22 / 7,
float("nan"),
float("inf"),
float("-inf"),
):
_test_float_attr(value, f32)
def test_float_attr_specials():
printer = Printer()
def _test_attr_print(expected: str, attr: FloatAttr):
io = StringIO()
printer.stream = io
printer.print_attribute(attr)
assert io.getvalue() == expected
_test_attr_print("0x7e00 : f16", FloatAttr(float("nan"), 16))
_test_attr_print("0x7c00 : f16", FloatAttr(float("inf"), 16))
_test_attr_print("0xfc00 : f16", FloatAttr(float("-inf"), 16))
_test_attr_print("0x7fc00000 : f32", FloatAttr(float("nan"), 32))
_test_attr_print("0x7f800000 : f32", FloatAttr(float("inf"), 32))
_test_attr_print("0xff800000 : f32", FloatAttr(float("-inf"), 32))
_test_attr_print("0x7ff8000000000000 : f64", FloatAttr(float("nan"), 64))
_test_attr_print("0x7ff0000000000000 : f64", FloatAttr(float("inf"), 64))
_test_attr_print("0xfff0000000000000 : f64", FloatAttr(float("-inf"), 64))
def test_print_function_type():
io = StringIO()
printer = Printer(stream=io)
printer.print_function_type((), ())
assert io.getvalue() == "() -> ()"
io = StringIO()
printer.stream = io
printer.print_function_type((i32,), ())
assert io.getvalue() == "(i32) -> ()"
io = StringIO()
printer.stream = io
printer.print_function_type((i32,), (i32,))
assert io.getvalue() == "(i32) -> i32"
io = StringIO()
printer.stream = io
printer.print_function_type((i32,), (i32, i32))
assert io.getvalue() == "(i32) -> (i32, i32)"
io = StringIO()
printer.stream = io
printer.print_function_type((i32,), (FunctionType.from_lists((i32,), (i32,)),))
assert io.getvalue() == "(i32) -> ((i32) -> i32)"
def test_print_properties_as_attributes():
"""Test that properties can be printed as attributes."""
prog = """
"func.func"() <{sym_name = "test", function_type = i64, sym_visibility = "private"}> {extra_attr} : () -> ()
"""
retro_prog = """
"func.func"() {extra_attr, sym_name = "test", function_type = i64, sym_visibility = "private"} : () -> ()
"""
ctx = Context()
ctx.load_dialect(Builtin)
ctx.load_dialect(Func)
parser = Parser(ctx, prog)
parsed = parser.parse_op()
assert_print_op(parsed, retro_prog, print_properties_as_attributes=True)
def test_print_properties_as_attributes_safeguard():
"""Test that properties can be printed as attributes."""
prog = """
"func.func"() <{sym_name = "test", function_type = i64, sym_visibility = "private"}> {extra_attr, sym_name = "this should be overriden by the property"} : () -> ()
"""
retro_prog = """
"func.func"() {extra_attr, sym_name = "test", function_type = i64, sym_visibility = "private"} : () -> ()
"""
ctx = Context()
ctx.load_dialect(Builtin)
ctx.load_dialect(Func)
parser = Parser(ctx, prog)
parsed = parser.parse_op()
with pytest.raises(
ValueError,
match="Properties sym_name would overwrite the attributes of the same names.",
):
assert_print_op(parsed, retro_prog, print_properties_as_attributes=True)
@pytest.mark.parametrize(
"attr,expected",
[
(SymbolRefAttr("foo"), "@foo"),
(SymbolRefAttr("weird name!!"), '@"weird name!!"'),
(
SymbolRefAttr("weird nested", ["yes", "very nested"]),
'@"weird nested"::@yes::@"very nested"',
),
],
)
def test_symbol_ref(attr: SymbolRefAttr, expected: str):
ctx = Context()
ctx.load_dialect(Builtin)
printed = StringIO()
Printer(printed).print_attribute(attr)
assert printed.getvalue() == expected
def test_get_printed_name():
ctx = Context()
ctx.load_dialect(Builtin)
printer = Printer()
val = TestSSAValue(i32)
# Test printing without constraints
stream = StringIO()
printer.stream = stream
picked_name = printer.print_ssa_value(val)
assert f"%{picked_name}" == printer.stream.getvalue()
# Test printing when name has already been picked
stream = StringIO()
printer.stream = stream
picked_name = printer.print_ssa_value(val)
assert f"%{picked_name}" == printer.stream.getvalue()
# Test printing with name hint
val = TestSSAValue(i32)
val.name_hint = "foo"
printed = StringIO()
picked_name = Printer(printed).print_ssa_value(val)
assert f"%{picked_name}" == printed.getvalue()
def assert_print_op(
operation: Operation,
expected: str,
*,
diagnostic: Diagnostic | None = None,
print_generic_format: bool = True,
print_debuginfo: bool = False,
print_properties_as_attributes: bool = False,
indent_num_spaces: int = 2,
):
"""
Utility function that helps to check the printing of an operation compared to
some string.
### Example:
To check that an operation, e.g. `arith.addi` prints as expected:
.. code-block:: py
expected = \"\"\"
builtin.module() {
%0 : !i32 = arith.addi(%<UNKNOWN> : !i32, %<UNKNOWN> : !i32)
-----------------------^^^^^^^^^^----------------------------------------------------------------
| ERROR: SSAValue is not part of the IR, are you sure all operations are added before their uses?
-------------------------------------------------------------------------------------------------
------------------------------------------^^^^^^^^^^---------------------------------------------
| ERROR: SSAValue is not part of the IR, are you sure all operations are added before their uses?
-------------------------------------------------------------------------------------------------
%1 : !i32 = arith.addi(%0 : !i32, %0 : !i32)
}\"\"\"
we call:
.. code-block:: python
assert_print_op(add, expected)
Additional options can be passed to the printer using keyword arguments:
.. code-block:: python