nac3-spec/toy-impl/test_inference.py

64 lines
1.7 KiB
Python

from type_def import *
from inference import *
from helper import *
types = {
'int32': PrimitiveType('int32'),
'int64': PrimitiveType('int64'),
'str': PrimitiveType('str'),
}
i32 = types['int32']
i64 = types['int64']
s = types['str']
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['foo'] = ([SelfType(), i32], i32, set())
i64.methods['__init__'] = ([SelfType(), I], None, set())
i64.methods['__add__'] = ([SelfType(), i64], i64, set())
i64.methods['__sub__'] = ([SelfType(), i64], i64, set())
i64.methods['foo'] = ([SelfType(), i64], i32, set())
ctx = Context(variables, types)
def test_call(obj, fn, args, assumptions = {}):
args_str = ', '.join([str(v) for v in args])
obj_str = '' if obj is None else str(obj) + '.'
print(f'Testing {obj_str}{fn}({args_str}) w.r.t. {stringify_subst(assumptions)}')
try:
result = resolve_call(obj, fn, args, assumptions, ctx)
print(result)
except CustomError as err:
print(f'error: {err.msg}')
test_call(None, 'int32', [])
test_call(None, 'int32', [i32])
test_call(None, 'int32', [i64])
test_call(None, 'int32', [I])
test_call(None, 'int32', [A])
test_call(None, 'int32', [i32, i64])
test_call(i32, '__add__', [])
test_call(i32, '__add__', [i32])
test_call(i32, '__add__', [i64])
test_call(i32, '__add__', [i32, i32])
test_call(I, '__add__', [I])
test_call(I, 'foo', [I])