nac3-spec/toy-impl/test_stmt.py

99 lines
2.3 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['__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['__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 = {}):
print(f'Testing {stmt} w.r.t. {stringify_subst(sym_table)}')
try:
tree = ast.parse(stmt)
a, b, _ = parse_stmts(ctx, sym_table, sym_table, tree.body)
print(stringify_subst(a))
except CustomError as err:
print(f'error: {err.msg}')
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]
""")