add python implementation of pali (thanks arland!)

This commit is contained in:
crc 2024-09-03 16:55:12 +02:00
parent c66e6979df
commit 75615c8755

116
pali.py Executable file
View file

@ -0,0 +1,116 @@
#!/usr/bin/env python3
import ctypes, sys, struct
memory = [0]*65536
here = 0
pointers = {}
def extract_code(code):
ret = ''
comment = True
for i in code.split('\n'):
if i == '~~~':
comment = comment == False
elif not comment:
ret += i+'\n'
return ret
ops = [ '..', 'li', 'du', 'dr', 'sw', 'pu',
'po', 'ju', 'ca', 'cc', 'cj', 're',
'eq', 'ne', 'lt', 'gt', 'fe', 'st',
'ad', 'su', 'mu', 'di', 'an', 'or',
'xo', 'sl', 'sr', 'cp', 'cy', 'io' ]
def comment(a):
pass
def origin(a):
global here
here = int(a)
def intw(a):
global memory, here
memory[here] = int(ctypes.c_int32(int(a)).value)
here += 1
def bundle(a):
A = ops.index(a[0:2])
B = ops.index(a[2:4])
C = ops.index(a[4:6])
D = ops.index(a[6:8])
intw((D<<24)+(C<<16)+(B<<8)+A)
def spacer(a):
global here
here += int(a)
def sstr(a):
intw(len(a))
for c in a:
intw(ord(c))
def zstr(a):
for c in a:
intw(ord(c))
intw(0)
def ref(a):
if a in pointers:
intw(pointers[a])
else:
intw(0)
def iref(a):
if a in pointers:
intw(-1 * pointers[a])
else:
intw(0)
def label(a):
global pointers
pointers[a] = here
def rc(code):
global here
here = 0
ops = {
'c': comment,
'o': origin,
'i': bundle,
'd': intw,
'*': spacer,
's': sstr,
'z': zstr,
'r': ref,
'R': iref,
'-': ref,
':': label
}
for line in code.split('\n'):
if ' ' in line.lstrip():
op,a = line.lstrip().split(' ', 1)
ops[op](a)
def save_image():
with open("ilo.rom", "wb") as f:
f.write(struct.pack('65536i', *memory[:65536]))
def pali(code):
code = extract_code(code)
rc(code) #pre processing
rc(code) #post processing
print('{} words ({} bytes) used'.format(here, here*4))
if __name__ == '__main__':
a = sys.argv
if len(a) > 1:
with open(a[1], 'r') as code:
pali(code.read())
save_image()
else:
with open('pali.output', 'w') as f:
pali(input('paste in Pali code:\n'))
save_image()