1# RUN: %PYTHON %s | FileCheck %s
2
3import gc
4from mlir.ir import *
5
6def run(f):
7  print("\nTEST:", f.__name__)
8  f()
9  gc.collect()
10  assert Context._get_live_count() == 0
11  return f
12
13
14# CHECK-LABEL: TEST: testParsePrint
15@run
16def testParsePrint():
17  with Context() as ctx:
18    t = Attribute.parse('"hello"')
19  assert t.context is ctx
20  ctx = None
21  gc.collect()
22  # CHECK: "hello"
23  print(str(t))
24  # CHECK: Attribute("hello")
25  print(repr(t))
26
27
28# CHECK-LABEL: TEST: testParseError
29# TODO: Hook the diagnostic manager to capture a more meaningful error
30# message.
31@run
32def testParseError():
33  with Context():
34    try:
35      t = Attribute.parse("BAD_ATTR_DOES_NOT_EXIST")
36    except ValueError as e:
37      # CHECK: Unable to parse attribute: 'BAD_ATTR_DOES_NOT_EXIST'
38      print("testParseError:", e)
39    else:
40      print("Exception not produced")
41
42
43# CHECK-LABEL: TEST: testAttrEq
44@run
45def testAttrEq():
46  with Context():
47    a1 = Attribute.parse('"attr1"')
48    a2 = Attribute.parse('"attr2"')
49    a3 = Attribute.parse('"attr1"')
50    # CHECK: a1 == a1: True
51    print("a1 == a1:", a1 == a1)
52    # CHECK: a1 == a2: False
53    print("a1 == a2:", a1 == a2)
54    # CHECK: a1 == a3: True
55    print("a1 == a3:", a1 == a3)
56    # CHECK: a1 == None: False
57    print("a1 == None:", a1 == None)
58
59
60# CHECK-LABEL: TEST: testAttrHash
61@run
62def testAttrHash():
63  with Context():
64    a1 = Attribute.parse('"attr1"')
65    a2 = Attribute.parse('"attr2"')
66    a3 = Attribute.parse('"attr1"')
67    # CHECK: hash(a1) == hash(a3): True
68    print("hash(a1) == hash(a3):", a1.__hash__() == a3.__hash__())
69
70    s = set()
71    s.add(a1)
72    s.add(a2)
73    s.add(a3)
74    # CHECK: len(s): 2
75    print("len(s): ", len(s))
76
77
78# CHECK-LABEL: TEST: testAttrCast
79@run
80def testAttrCast():
81  with Context():
82    a1 = Attribute.parse('"attr1"')
83    a2 = Attribute(a1)
84    # CHECK: a1 == a2: True
85    print("a1 == a2:", a1 == a2)
86
87
88# CHECK-LABEL: TEST: testAttrIsInstance
89@run
90def testAttrIsInstance():
91  with Context():
92    a1 = Attribute.parse("42")
93    a2 = Attribute.parse("[42]")
94    assert IntegerAttr.isinstance(a1)
95    assert not IntegerAttr.isinstance(a2)
96    assert not ArrayAttr.isinstance(a1)
97    assert ArrayAttr.isinstance(a2)
98
99
100# CHECK-LABEL: TEST: testAttrEqDoesNotRaise
101@run
102def testAttrEqDoesNotRaise():
103  with Context():
104    a1 = Attribute.parse('"attr1"')
105    not_an_attr = "foo"
106    # CHECK: False
107    print(a1 == not_an_attr)
108    # CHECK: False
109    print(a1 == None)
110    # CHECK: True
111    print(a1 != None)
112
113
114# CHECK-LABEL: TEST: testAttrCapsule
115@run
116def testAttrCapsule():
117  with Context() as ctx:
118    a1 = Attribute.parse('"attr1"')
119  # CHECK: mlir.ir.Attribute._CAPIPtr
120  attr_capsule = a1._CAPIPtr
121  print(attr_capsule)
122  a2 = Attribute._CAPICreate(attr_capsule)
123  assert a2 == a1
124  assert a2.context is ctx
125
126
127# CHECK-LABEL: TEST: testStandardAttrCasts
128@run
129def testStandardAttrCasts():
130  with Context():
131    a1 = Attribute.parse('"attr1"')
132    astr = StringAttr(a1)
133    aself = StringAttr(astr)
134    # CHECK: Attribute("attr1")
135    print(repr(astr))
136    try:
137      tillegal = StringAttr(Attribute.parse("1.0"))
138    except ValueError as e:
139      # CHECK: ValueError: Cannot cast attribute to StringAttr (from Attribute(1.000000e+00 : f64))
140      print("ValueError:", e)
141    else:
142      print("Exception not produced")
143
144
145# CHECK-LABEL: TEST: testAffineMapAttr
146@run
147def testAffineMapAttr():
148  with Context() as ctx:
149    d0 = AffineDimExpr.get(0)
150    d1 = AffineDimExpr.get(1)
151    c2 = AffineConstantExpr.get(2)
152    map0 = AffineMap.get(2, 3, [])
153
154    # CHECK: affine_map<(d0, d1)[s0, s1, s2] -> ()>
155    attr_built = AffineMapAttr.get(map0)
156    print(str(attr_built))
157
158    attr_parsed = Attribute.parse(str(attr_built))
159    assert attr_built == attr_parsed
160
161
162# CHECK-LABEL: TEST: testFloatAttr
163@run
164def testFloatAttr():
165  with Context(), Location.unknown():
166    fattr = FloatAttr(Attribute.parse("42.0 : f32"))
167    # CHECK: fattr value: 42.0
168    print("fattr value:", fattr.value)
169
170    # Test factory methods.
171    # CHECK: default_get: 4.200000e+01 : f32
172    print("default_get:", FloatAttr.get(
173        F32Type.get(), 42.0))
174    # CHECK: f32_get: 4.200000e+01 : f32
175    print("f32_get:", FloatAttr.get_f32(42.0))
176    # CHECK: f64_get: 4.200000e+01 : f64
177    print("f64_get:", FloatAttr.get_f64(42.0))
178    try:
179      fattr_invalid = FloatAttr.get(
180          IntegerType.get_signless(32), 42)
181    except ValueError as e:
182      # CHECK: invalid 'Type(i32)' and expected floating point type.
183      print(e)
184    else:
185      print("Exception not produced")
186
187
188# CHECK-LABEL: TEST: testIntegerAttr
189@run
190def testIntegerAttr():
191  with Context() as ctx:
192    i_attr = IntegerAttr(Attribute.parse("42"))
193    # CHECK: i_attr value: 42
194    print("i_attr value:", i_attr.value)
195    # CHECK: i_attr type: i64
196    print("i_attr type:", i_attr.type)
197    si_attr = IntegerAttr(Attribute.parse("-1 : si8"))
198    # CHECK: si_attr value: -1
199    print("si_attr value:", si_attr.value)
200    ui_attr = IntegerAttr(Attribute.parse("255 : ui8"))
201    # CHECK: ui_attr value: 255
202    print("ui_attr value:", ui_attr.value)
203    idx_attr = IntegerAttr(Attribute.parse("-1 : index"))
204    # CHECK: idx_attr value: -1
205    print("idx_attr value:", idx_attr.value)
206
207    # Test factory methods.
208    # CHECK: default_get: 42 : i32
209    print("default_get:", IntegerAttr.get(
210        IntegerType.get_signless(32), 42))
211
212
213# CHECK-LABEL: TEST: testBoolAttr
214@run
215def testBoolAttr():
216  with Context() as ctx:
217    battr = BoolAttr(Attribute.parse("true"))
218    # CHECK: iattr value: True
219    print("iattr value:", battr.value)
220
221    # Test factory methods.
222    # CHECK: default_get: true
223    print("default_get:", BoolAttr.get(True))
224
225
226# CHECK-LABEL: TEST: testFlatSymbolRefAttr
227@run
228def testFlatSymbolRefAttr():
229  with Context() as ctx:
230    sattr = FlatSymbolRefAttr(Attribute.parse('@symbol'))
231    # CHECK: symattr value: symbol
232    print("symattr value:", sattr.value)
233
234    # Test factory methods.
235    # CHECK: default_get: @foobar
236    print("default_get:", FlatSymbolRefAttr.get("foobar"))
237
238
239# CHECK-LABEL: TEST: testStringAttr
240@run
241def testStringAttr():
242  with Context() as ctx:
243    sattr = StringAttr(Attribute.parse('"stringattr"'))
244    # CHECK: sattr value: stringattr
245    print("sattr value:", sattr.value)
246
247    # Test factory methods.
248    # CHECK: default_get: "foobar"
249    print("default_get:", StringAttr.get("foobar"))
250    # CHECK: typed_get: "12345" : i32
251    print("typed_get:", StringAttr.get_typed(
252        IntegerType.get_signless(32), "12345"))
253
254
255# CHECK-LABEL: TEST: testNamedAttr
256@run
257def testNamedAttr():
258  with Context():
259    a = Attribute.parse('"stringattr"')
260    named = a.get_named("foobar")  # Note: under the small object threshold
261    # CHECK: attr: "stringattr"
262    print("attr:", named.attr)
263    # CHECK: name: foobar
264    print("name:", named.name)
265    # CHECK: named: NamedAttribute(foobar="stringattr")
266    print("named:", named)
267
268
269# CHECK-LABEL: TEST: testDenseIntAttr
270@run
271def testDenseIntAttr():
272  with Context():
273    raw = Attribute.parse("dense<[[0,1,2],[3,4,5]]> : vector<2x3xi32>")
274    # CHECK: attr: dense<[{{\[}}0, 1, 2], [3, 4, 5]]>
275    print("attr:", raw)
276
277    a = DenseIntElementsAttr(raw)
278    assert len(a) == 6
279
280    # CHECK: 0 1 2 3 4 5
281    for value in a:
282      print(value, end=" ")
283    print()
284
285    # CHECK: i32
286    print(ShapedType(a.type).element_type)
287
288    raw = Attribute.parse("dense<[true,false,true,false]> : vector<4xi1>")
289    # CHECK: attr: dense<[true, false, true, false]>
290    print("attr:", raw)
291
292    a = DenseIntElementsAttr(raw)
293    assert len(a) == 4
294
295    # CHECK: 1 0 1 0
296    for value in a:
297      print(value, end=" ")
298    print()
299
300    # CHECK: i1
301    print(ShapedType(a.type).element_type)
302
303
304# CHECK-LABEL: TEST: testDenseIntAttrGetItem
305@run
306def testDenseIntAttrGetItem():
307  def print_item(attr_asm):
308    attr = DenseIntElementsAttr(Attribute.parse(attr_asm))
309    dtype = ShapedType(attr.type).element_type
310    try:
311      item = attr[0]
312      print(f"{dtype}:", item)
313    except TypeError as e:
314      print(f"{dtype}:", e)
315
316  with Context():
317    # CHECK: i1: 1
318    print_item("dense<true> : tensor<i1>")
319    # CHECK: i8: 123
320    print_item("dense<123> : tensor<i8>")
321    # CHECK: i16: 123
322    print_item("dense<123> : tensor<i16>")
323    # CHECK: i32: 123
324    print_item("dense<123> : tensor<i32>")
325    # CHECK: i64: 123
326    print_item("dense<123> : tensor<i64>")
327    # CHECK: ui8: 123
328    print_item("dense<123> : tensor<ui8>")
329    # CHECK: ui16: 123
330    print_item("dense<123> : tensor<ui16>")
331    # CHECK: ui32: 123
332    print_item("dense<123> : tensor<ui32>")
333    # CHECK: ui64: 123
334    print_item("dense<123> : tensor<ui64>")
335    # CHECK: si8: -123
336    print_item("dense<-123> : tensor<si8>")
337    # CHECK: si16: -123
338    print_item("dense<-123> : tensor<si16>")
339    # CHECK: si32: -123
340    print_item("dense<-123> : tensor<si32>")
341    # CHECK: si64: -123
342    print_item("dense<-123> : tensor<si64>")
343
344    # CHECK: i7: Unsupported integer type
345    print_item("dense<123> : tensor<i7>")
346
347
348# CHECK-LABEL: TEST: testDenseFPAttr
349@run
350def testDenseFPAttr():
351  with Context():
352    raw = Attribute.parse("dense<[0.0, 1.0, 2.0, 3.0]> : vector<4xf32>")
353    # CHECK: attr: dense<[0.000000e+00, 1.000000e+00, 2.000000e+00, 3.000000e+00]>
354
355    print("attr:", raw)
356
357    a = DenseFPElementsAttr(raw)
358    assert len(a) == 4
359
360    # CHECK: 0.0 1.0 2.0 3.0
361    for value in a:
362      print(value, end=" ")
363    print()
364
365    # CHECK: f32
366    print(ShapedType(a.type).element_type)
367
368
369# CHECK-LABEL: TEST: testDictAttr
370@run
371def testDictAttr():
372  with Context():
373    dict_attr = {
374      'stringattr':  StringAttr.get('string'),
375      'integerattr' : IntegerAttr.get(
376        IntegerType.get_signless(32), 42)
377    }
378
379    a = DictAttr.get(dict_attr)
380
381    # CHECK attr: {integerattr = 42 : i32, stringattr = "string"}
382    print("attr:", a)
383
384    assert len(a) == 2
385
386    # CHECK: 42 : i32
387    print(a['integerattr'])
388
389    # CHECK: "string"
390    print(a['stringattr'])
391
392    # CHECK: True
393    print('stringattr' in a)
394
395    # CHECK: False
396    print('not_in_dict' in a)
397
398    # Check that exceptions are raised as expected.
399    try:
400      _ = a['does_not_exist']
401    except KeyError:
402      pass
403    else:
404      assert False, "Exception not produced"
405
406    try:
407      _ = a[42]
408    except IndexError:
409      pass
410    else:
411      assert False, "expected IndexError on accessing an out-of-bounds attribute"
412
413    # CHECK "empty: {}"
414    print("empty: ", DictAttr.get())
415
416
417# CHECK-LABEL: TEST: testTypeAttr
418@run
419def testTypeAttr():
420  with Context():
421    raw = Attribute.parse("vector<4xf32>")
422    # CHECK: attr: vector<4xf32>
423    print("attr:", raw)
424    type_attr = TypeAttr(raw)
425    # CHECK: f32
426    print(ShapedType(type_attr.value).element_type)
427
428
429# CHECK-LABEL: TEST: testArrayAttr
430@run
431def testArrayAttr():
432  with Context():
433    raw = Attribute.parse("[42, true, vector<4xf32>]")
434  # CHECK: attr: [42, true, vector<4xf32>]
435  print("raw attr:", raw)
436  # CHECK: - 42
437  # CHECK: - true
438  # CHECK: - vector<4xf32>
439  for attr in ArrayAttr(raw):
440    print("- ", attr)
441
442  with Context():
443    intAttr = Attribute.parse("42")
444    vecAttr = Attribute.parse("vector<4xf32>")
445    boolAttr = BoolAttr.get(True)
446    raw = ArrayAttr.get([vecAttr, boolAttr, intAttr])
447  # CHECK: attr: [vector<4xf32>, true, 42]
448  print("raw attr:", raw)
449  # CHECK: - vector<4xf32>
450  # CHECK: - true
451  # CHECK: - 42
452  arr = ArrayAttr(raw)
453  for attr in arr:
454    print("- ", attr)
455  # CHECK: attr[0]: vector<4xf32>
456  print("attr[0]:", arr[0])
457  # CHECK: attr[1]: true
458  print("attr[1]:", arr[1])
459  # CHECK: attr[2]: 42
460  print("attr[2]:", arr[2])
461  try:
462    print("attr[3]:", arr[3])
463  except IndexError as e:
464    # CHECK: Error: ArrayAttribute index out of range
465    print("Error: ", e)
466  with Context():
467    try:
468      ArrayAttr.get([None])
469    except RuntimeError as e:
470      # CHECK: Error: Invalid attribute (None?) when attempting to create an ArrayAttribute
471      print("Error: ", e)
472    try:
473      ArrayAttr.get([42])
474    except RuntimeError as e:
475      # CHECK: Error: Invalid attribute when attempting to create an ArrayAttribute
476      print("Error: ", e)
477
478  with Context():
479    array = ArrayAttr.get([StringAttr.get("a"), StringAttr.get("b")])
480    array = array + [StringAttr.get("c")]
481    # CHECK: concat: ["a", "b", "c"]
482    print("concat: ", array)
483