nac3-spec/toy-impl/test_stmt.py

135 lines
2.9 KiB
Python

import ast
from type_def import *
from inference import *
from helper import *
from parse_stmt import *
types = {
'int32': PrimitiveType('int32'),
'int64': PrimitiveType('int64'),
'str': PrimitiveType('str'),
'bool': PrimitiveType('bool')
}
i32 = types['int32']
i64 = types['int64']
s = types['str']
b = types['bool']
variables = {
'X': TypeVariable('X', []),
'Y': TypeVariable('Y', []),
'I': TypeVariable('I', [i32, i64]),
'A': TypeVariable('A', [i32, i64, s]),
}
X = variables['X']
Y = variables['Y']
I = variables['I']
A = variables['A']
i32.methods['__init__'] = ([SelfType(), I], None, set())
i32.methods['__add__'] = ([SelfType(), i32], i32, set())
i32.methods['__sub__'] = ([SelfType(), i32], i32, set())
i32.methods['__neg__'] = ([SelfType()], i32, set())
i32.methods['__lt__'] = ([SelfType(), i32], b, set())
i32.methods['__gt__'] = ([SelfType(), i32], b, set())
i32.methods['__eq__'] = ([SelfType(), i32], b, set())
i32.methods['__ne__'] = ([SelfType(), i32], b, set())
i32.methods['__le__'] = ([SelfType(), i32], b, set())
i32.methods['__ge__'] = ([SelfType(), i32], b, set())
i64.methods['__init__'] = ([SelfType(), I], None, set())
i64.methods['__add__'] = ([SelfType(), i64], i64, set())
i64.methods['__sub__'] = ([SelfType(), i64], i64, set())
i64.methods['__neg__'] = ([SelfType()], i64, set())
i64.methods['__lt__'] = ([SelfType(), i64], b, set())
i64.methods['__gt__'] = ([SelfType(), i64], b, set())
i64.methods['__eq__'] = ([SelfType(), i64], b, set())
i64.methods['__ne__'] = ([SelfType(), i64], b, set())
i64.methods['__le__'] = ([SelfType(), i64], b, set())
i64.methods['__ge__'] = ([SelfType(), i64], b, set())
ctx = Context(variables, types)
def test_stmt(stmt, sym_table = {}, return_ty = None):
print(f'Testing:\n{stmt}\n\nw.r.t. {stringify_subst(sym_table)}')
try:
tree = ast.parse(stmt)
a, b, returned = parse_stmts(ctx, sym_table, sym_table, return_ty, tree.body)
print(f'defined variables: {stringify_subst(a)}')
print(f'returned: {returned}')
print('---')
except CustomError as err:
print(f'error: {err.msg}')
print('---')
test_stmt('a, b = 1, 2', {})
test_stmt('a, b = 1, [1, 2, 3]', {})
test_stmt('a, b[c] = 1, 2', {'b': ListType(i32), 'c': i32})
test_stmt('a, b[c] = 1, [1, 2]', {'b': ListType(i32), 'c': i32})
test_stmt('b = [1, 2, 3]\nc = 1\na, b[c] = 1, 2\na = 2')
test_stmt("""
if True:
a = 1
else:
a = 2
b = 1
c = a
""")
test_stmt("""
if True:
a = 1
else:
a = 2
b = 1
c = a
d = b
""")
test_stmt("""
if True:
a = 1
else:
a = 2
b = 1
c = a
b = [1, 2, 3]
""")
test_stmt("""
c = 0
for i in [1, 2, 3]:
c = c + i
""")
test_stmt("""
c = 0
for i in [1, 2, 3]:
c = c + i
if c > 0:
return c
else:
return -c
""", {}, i32)
test_stmt("""
c = 0
for i in [1, 2, 3]:
c = c + i
if c > 0:
return c
""", {}, i32)
test_stmt("""
c = i = 0
for i in [True, True, False]:
c = c + 1
if c > 0:
return c
""", {}, i32)