nxu/uxnrepl.py

81 lines
1.8 KiB
Python
Raw Normal View History

2024-01-23 10:46:23 -05:00
#!/usr/bin/python
from os import system
2024-01-23 11:07:09 -05:00
from subprocess import run, TimeoutExpired
2024-01-23 10:46:23 -05:00
from sys import stdin, stdout
from tempfile import mkstemp
sandbox = None
template = '''
|0100
( start ) %s ( end )
#05 DEI ,emit-wst/n STR
;wst print
@dump-wst
#04 DEI #01 GTH ?&next !emit-wst &next STH !dump-wst
@emit-wst
#05 DEI LIT [ &n $1 ] GTH ?&next #0a18 DEO !start-rst
&next STHr emit #2018 DEO !emit-wst
@start-rst
;rst print
@dump-rst
#05 DEI #00 GTH ?&next !emit-rst &next STHr !dump-rst
@emit-rst
#04 DEI #01 GTH ?&next #0a18 DEO #800f DEO BRK
&next emit #2018 DEO !emit-rst
@print ( addr* -> )
LDAk DUP ?{ POP POP2 JMP2r } #18 DEO INC2 !print
@emit
DUP #04 SFT ,&ch JSR
&ch #0f AND DUP #09 GTH #27 MUL ADD #30 ADD #18 DEO JMP2r
@rst "rst 20 00
@wst "wst 20 00
'''
def write_rom(path, s):
f = open(path, 'w')
2024-01-23 10:51:53 -05:00
prog = template % s
2024-01-23 10:46:23 -05:00
f.write(prog)
f.close()
2024-01-23 10:51:53 -05:00
def execute(s, sandbox=None, timeout=2.0):
2024-01-23 10:46:23 -05:00
_, tmp_tal = mkstemp(suffix='.tal', prefix='uxnrepl')
_, tmp_rom = mkstemp(suffix='.rom', prefix='uxnrepl')
write_rom(tmp_tal, s)
2024-01-23 10:51:53 -05:00
try:
res = run(['uxnasm', tmp_tal, tmp_rom], cwd=sandbox, capture_output=True, timeout=timeout)
except TimeoutExpired:
2024-01-23 11:07:09 -05:00
return b'uxnasm: timed out'
2024-01-23 10:46:23 -05:00
if res.returncode != 0:
return res.stderr
2024-01-23 10:51:53 -05:00
try:
res = run(['uxncli', tmp_rom], cwd=sandbox, capture_output=True, timeout=timeout)
except TimeoutExpired:
2024-01-23 11:07:09 -05:00
return b'uxncli: timed out'
2024-01-23 10:46:23 -05:00
return res.stdout
def main():
print('uxnrepl (ctrl-d to exit)')
while True:
stdout.write('> ')
stdout.flush()
s = stdin.readline()
if not s:
print('bye!')
break
stdout.write(execute(s).decode('utf-8'))
stdout.flush()
if __name__ == "__main__":
main()