copapy/tests/test_compile.py

80 lines
1.9 KiB
Python
Raw Permalink Normal View History

from copapy import variable, NumLike
from copapy.backend import Write, compile_to_dag, add_read_command
import copapy
2025-09-30 21:18:58 +00:00
import subprocess
import struct
from copapy import _binwrite
import copapy.backend
2025-08-29 20:58:50 +00:00
def run_command(command: list[str]) -> str:
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf8', check=False)
assert result.returncode != 11, f"SIGSEGV (segmentation fault)\n -Error occurred: {result.stderr}\n -Output: {result.stdout}"
assert result.returncode == 0, f"\n -Error occurred: {result.stderr}\n -Output: {result.stdout}"
return result.stdout
2025-09-26 21:25:51 +00:00
def test_example():
c1 = 4
c2 = 2
2025-08-29 20:58:50 +00:00
i1 = c1 * 2
r1 = i1 + 7 + (c2 + 7 * 9)
r2 = i1 + 9
2025-08-29 20:58:50 +00:00
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))
2025-10-18 21:20:40 +00:00
def function(c1: NumLike, c2: NumLike) -> tuple[NumLike, ...]:
i1 = c1 // 3.3 + 5
2025-10-08 20:47:49 +00:00
i2 = c2 * 5 + c1
r1 = i1 + i2 * 55 / 4
r2 = 4 * i2 + 5
2025-10-08 20:47:49 +00:00
return i1, i2, r1, r2
2025-10-08 20:47:49 +00:00
def test_compile():
c1 = variable(4)
c2 = variable(2)
2025-10-08 20:47:49 +00:00
2025-10-14 21:21:23 +00:00
ret = function(c1, c2)
#ret = [c1 // 3.3 + 5]
2025-10-08 20:47:49 +00:00
out = [Write(r) for r in ret]
il, variables = compile_to_dag(out, copapy.generic_sdb)
# run program command
il.write_com(_binwrite.Command.RUN_PROG)
2025-10-14 21:21:23 +00:00
for net in ret:
assert isinstance(net, copapy.backend.Net)
add_read_command(il, variables, net)
2025-08-29 20:58:50 +00:00
il.write_com(_binwrite.Command.END_COM)
2025-08-29 20:58:50 +00:00
print('* Data to runner:')
il.print()
2025-08-29 20:58:50 +00:00
2025-10-04 21:01:44 +00:00
il.to_file('bin/test.copapy')
2025-09-30 21:18:58 +00:00
2025-10-04 21:01:44 +00:00
result = run_command(['bin/coparun', 'bin/test.copapy'])
print('* Output from runner:\n--')
2025-09-30 21:18:58 +00:00
print(result)
print('--')
2025-09-30 21:18:58 +00:00
assert 'Return value: 1' in result
#assert 'END_COM' in result
2025-09-26 21:25:51 +00:00
2025-08-29 20:58:50 +00:00
if __name__ == "__main__":
#test_example()
test_compile()