nxu/uxnrepl.py

81 lines
1.8 KiB
Python

#!/usr/bin/python
from os import system
from subprocess import run
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')
prog = template % s
f.write(prog)
f.close()
def execute(s, sandbox=None, timeout=2.0):
_, tmp_tal = mkstemp(suffix='.tal', prefix='uxnrepl')
_, tmp_rom = mkstemp(suffix='.rom', prefix='uxnrepl')
write_rom(tmp_tal, s)
try:
res = run(['uxnasm', tmp_tal, tmp_rom], cwd=sandbox, capture_output=True, timeout=timeout)
except TimeoutExpired:
return 'uxnasm: timed out'
if res.returncode != 0:
return res.stderr
try:
res = run(['uxncli', tmp_rom], cwd=sandbox, capture_output=True, timeout=timeout)
except TimeoutExpired:
return 'uxncli: timed out'
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()