import gc
from mlir.ir import *
def run(f):
print("\nTEST:", f.__name__)
f()
gc.collect()
assert Context._get_live_count() == 0
return f
@run
def testParsePrint():
with Context() as ctx:
t = Attribute.parse('"hello"')
assert t.context is ctx
ctx = None
gc.collect()
print(str(t))
print(repr(t))
@run
def testParseError():
with Context():
try:
t = Attribute.parse("BAD_ATTR_DOES_NOT_EXIST")
except ValueError as e:
print("testParseError:", e)
else:
print("Exception not produced")
@run
def testAttrEq():
with Context():
a1 = Attribute.parse('"attr1"')
a2 = Attribute.parse('"attr2"')
a3 = Attribute.parse('"attr1"')
print("a1 == a1:", a1 == a1)
print("a1 == a2:", a1 == a2)
print("a1 == a3:", a1 == a3)
print("a1 == None:", a1 == None)
@run
def testAttrHash():
with Context():
a1 = Attribute.parse('"attr1"')
a2 = Attribute.parse('"attr2"')
a3 = Attribute.parse('"attr1"')
print("hash(a1) == hash(a3):", a1.__hash__() == a3.__hash__())
s = set()
s.add(a1)
s.add(a2)
s.add(a3)
print("len(s): ", len(s))
@run
def testAttrCast():
with Context():
a1 = Attribute.parse('"attr1"')
a2 = Attribute(a1)
print("a1 == a2:", a1 == a2)
@run
def testAttrIsInstance():
with Context():
a1 = Attribute.parse("42")
a2 = Attribute.parse("[42]")
assert IntegerAttr.isinstance(a1)
assert not IntegerAttr.isinstance(a2)
assert not ArrayAttr.isinstance(a1)
assert ArrayAttr.isinstance(a2)
@run
def testAttrEqDoesNotRaise():
with Context():
a1 = Attribute.parse('"attr1"')
not_an_attr = "foo"
print(a1 == not_an_attr)
print(a1 == None)
print(a1 != None)
@run
def testAttrCapsule():
with Context() as ctx:
a1 = Attribute.parse('"attr1"')
attr_capsule = a1._CAPIPtr
print(attr_capsule)
a2 = Attribute._CAPICreate(attr_capsule)
assert a2 == a1
assert a2.context is ctx
@run
def testStandardAttrCasts():
with Context():
a1 = Attribute.parse('"attr1"')
astr = StringAttr(a1)
aself = StringAttr(astr)
print(repr(astr))
try:
tillegal = StringAttr(Attribute.parse("1.0"))
except ValueError as e:
print("ValueError:", e)
else:
print("Exception not produced")
@run
def testAffineMapAttr():
with Context() as ctx:
d0 = AffineDimExpr.get(0)
d1 = AffineDimExpr.get(1)
c2 = AffineConstantExpr.get(2)
map0 = AffineMap.get(2, 3, [])
attr_built = AffineMapAttr.get(map0)
print(str(attr_built))
attr_parsed = Attribute.parse(str(attr_built))
assert attr_built == attr_parsed
@run
def testFloatAttr():
with Context(), Location.unknown():
fattr = FloatAttr(Attribute.parse("42.0 : f32"))
print("fattr value:", fattr.value)
print("default_get:", FloatAttr.get(
F32Type.get(), 42.0))
print("f32_get:", FloatAttr.get_f32(42.0))
print("f64_get:", FloatAttr.get_f64(42.0))
try:
fattr_invalid = FloatAttr.get(
IntegerType.get_signless(32), 42)
except ValueError as e:
print(e)
else:
print("Exception not produced")
@run
def testIntegerAttr():
with Context() as ctx:
i_attr = IntegerAttr(Attribute.parse("42"))
print("i_attr value:", i_attr.value)
print("i_attr type:", i_attr.type)
si_attr = IntegerAttr(Attribute.parse("-1 : si8"))
print("si_attr value:", si_attr.value)
ui_attr = IntegerAttr(Attribute.parse("255 : ui8"))
print("ui_attr value:", ui_attr.value)
idx_attr = IntegerAttr(Attribute.parse("-1 : index"))
print("idx_attr value:", idx_attr.value)
print("default_get:", IntegerAttr.get(
IntegerType.get_signless(32), 42))
@run
def testBoolAttr():
with Context() as ctx:
battr = BoolAttr(Attribute.parse("true"))
print("iattr value:", battr.value)
print("default_get:", BoolAttr.get(True))
@run
def testFlatSymbolRefAttr():
with Context() as ctx:
sattr = FlatSymbolRefAttr(Attribute.parse('@symbol'))
print("symattr value:", sattr.value)
print("default_get:", FlatSymbolRefAttr.get("foobar"))
@run
def testOpaqueAttr():
with Context() as ctx:
ctx.allow_unregistered_dialects = True
oattr = OpaqueAttr(Attribute.parse("#pytest_dummy.dummyattr<>"))
print("oattr value:", oattr.dialect_namespace)
print("oattr value:", oattr.data)
print(
"default_get:",
OpaqueAttr.get("foobar", bytes("123", "utf-8"), NoneType.get()))
@run
def testStringAttr():
with Context() as ctx:
sattr = StringAttr(Attribute.parse('"stringattr"'))
print("sattr value:", sattr.value)
print("default_get:", StringAttr.get("foobar"))
print("typed_get:", StringAttr.get_typed(
IntegerType.get_signless(32), "12345"))
@run
def testNamedAttr():
with Context():
a = Attribute.parse('"stringattr"')
named = a.get_named("foobar")
print("attr:", named.attr)
print("name:", named.name)
print("named:", named)
@run
def testDenseIntAttr():
with Context():
raw = Attribute.parse("dense<[[0,1,2],[3,4,5]]> : vector<2x3xi32>")
print("attr:", raw)
a = DenseIntElementsAttr(raw)
assert len(a) == 6
for value in a:
print(value, end=" ")
print()
print(ShapedType(a.type).element_type)
raw = Attribute.parse("dense<[true,false,true,false]> : vector<4xi1>")
print("attr:", raw)
a = DenseIntElementsAttr(raw)
assert len(a) == 4
for value in a:
print(value, end=" ")
print()
print(ShapedType(a.type).element_type)
@run
def testDenseIntAttrGetItem():
def print_item(attr_asm):
attr = DenseIntElementsAttr(Attribute.parse(attr_asm))
dtype = ShapedType(attr.type).element_type
try:
item = attr[0]
print(f"{dtype}:", item)
except TypeError as e:
print(f"{dtype}:", e)
with Context():
print_item("dense<true> : tensor<i1>")
print_item("dense<123> : tensor<i8>")
print_item("dense<123> : tensor<i16>")
print_item("dense<123> : tensor<i32>")
print_item("dense<123> : tensor<i64>")
print_item("dense<123> : tensor<ui8>")
print_item("dense<123> : tensor<ui16>")
print_item("dense<123> : tensor<ui32>")
print_item("dense<123> : tensor<ui64>")
print_item("dense<-123> : tensor<si8>")
print_item("dense<-123> : tensor<si16>")
print_item("dense<-123> : tensor<si32>")
print_item("dense<-123> : tensor<si64>")
print_item("dense<123> : tensor<i7>")
@run
def testDenseFPAttr():
with Context():
raw = Attribute.parse("dense<[0.0, 1.0, 2.0, 3.0]> : vector<4xf32>")
print("attr:", raw)
a = DenseFPElementsAttr(raw)
assert len(a) == 4
for value in a:
print(value, end=" ")
print()
print(ShapedType(a.type).element_type)
@run
def testDictAttr():
with Context():
dict_attr = {
'stringattr': StringAttr.get('string'),
'integerattr' : IntegerAttr.get(
IntegerType.get_signless(32), 42)
}
a = DictAttr.get(dict_attr)
print("attr:", a)
assert len(a) == 2
print(a['integerattr'])
print(a['stringattr'])
print('stringattr' in a)
print('not_in_dict' in a)
try:
_ = a['does_not_exist']
except KeyError:
pass
else:
assert False, "Exception not produced"
try:
_ = a[42]
except IndexError:
pass
else:
assert False, "expected IndexError on accessing an out-of-bounds attribute"
print("empty: ", DictAttr.get())
@run
def testTypeAttr():
with Context():
raw = Attribute.parse("vector<4xf32>")
print("attr:", raw)
type_attr = TypeAttr(raw)
print(ShapedType(type_attr.value).element_type)
@run
def testArrayAttr():
with Context():
raw = Attribute.parse("[42, true, vector<4xf32>]")
print("raw attr:", raw)
for attr in ArrayAttr(raw):
print("- ", attr)
with Context():
intAttr = Attribute.parse("42")
vecAttr = Attribute.parse("vector<4xf32>")
boolAttr = BoolAttr.get(True)
raw = ArrayAttr.get([vecAttr, boolAttr, intAttr])
print("raw attr:", raw)
arr = ArrayAttr(raw)
for attr in arr:
print("- ", attr)
print("attr[0]:", arr[0])
print("attr[1]:", arr[1])
print("attr[2]:", arr[2])
try:
print("attr[3]:", arr[3])
except IndexError as e:
print("Error: ", e)
with Context():
try:
ArrayAttr.get([None])
except RuntimeError as e:
print("Error: ", e)
try:
ArrayAttr.get([42])
except RuntimeError as e:
print("Error: ", e)
with Context():
array = ArrayAttr.get([StringAttr.get("a"), StringAttr.get("b")])
array = array + [StringAttr.get("c")]
print("concat: ", array)