copapy/tests/test_compile.py

85 lines
1.7 KiB
Python

from copapy import Write, const
import copapy
import subprocess
import struct
from copapy import binwrite
def run_command(command: list[str], encoding: str = 'utf8') -> str:
process = subprocess.Popen(command, stdout=subprocess.PIPE)
output, error = process.communicate()
assert error is None, f"Error occurred: {error.decode(encoding)}"
return output.decode(encoding)
def test_example():
c1 = 4
c2 = 2
i1 = c1 * 2
r1 = i1 + 7 + (c2 + 7 * 9)
r2 = i1 + 9
en = {'little': '<', 'big': '>'}['little']
data = struct.pack(en + 'i', r1)
print("example r1 " + ' '.join(f'{b:02X}' for b in data))
data = struct.pack(en + 'i', r2)
print("example r2 " + ' '.join(f'{b:02X}' for b in data))
# assert False
#example r1 42 A0 00 00
#example r2 41 88 00 00
def test_compile():
#c1 = const(1.11)
#c2 = const(2.22)
#i1 = c1 * 2
#i2 = i1 + 3
#r1 = i1 + i2
#r2 = c2 + 4 + c1
#out = [Write(r1), Write(r2)]
c1 = const(4)
c2 = const(2)
#i1 = c1 * 2
#r1 = i1 + 7 + (c2 + 7 * 9)
#r2 = i1 + 9
#out = [Write(r1), Write(r2)]
r1 = c1 * 5 + 8 + c2 * 3
out = [Write(r1)]
il, _ = copapy.compile_to_instruction_list(out, copapy.generic_sdb)
# run program command
il.write_com(binwrite.Command.RUN_PROG)
il.write_int(0)
il.write_com(binwrite.Command.READ_DATA)
il.write_int(0)
il.write_int(36)
il.write_com(binwrite.Command.END_PROG)
print('* Data to runner:')
il.print()
il.to_file('bin/test.copapy')
result = run_command(['bin/coparun', 'bin/test.copapy'])
print('* Output from runner:')
print(result)
assert 'Return value: 1' in result
if __name__ == "__main__":
#test_example()
test_compile()