Skip to content

Instantly share code, notes, and snippets.

@feresum
Created September 27, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feresum/794a9bafd07424fc4ae6 to your computer and use it in GitHub Desktop.
Save feresum/794a9bafd07424fc4ae6 to your computer and use it in GitHub Desktop.
"BF to BF*" compiler
R = lambda d: -d*'<' if d<0 else d*'>'
L = lambda d: R(-d)
w0 = '{-}'
w1 = '{-}+'
bcopy = lambda dtmp, ddst: (
R(dtmp)+w0+R(ddst-dtmp)+w0+L(ddst)
+'+{'+R(dtmp)+'+'+R(ddst-dtmp)+'+'+L(ddst)+'-}'
+ '-'+R(dtmp)+'{'+L(dtmp)+'+'+R(dtmp)+'-}'
+ R(ddst-dtmp)+'-' )
def depth(p):
l = m = 0
for c in p:
l += c=='['
l -= c==']'
m = max(m,l)
return m
# returns (start, stride, program)
# begin at 0-indexed cell start and read every stride'th cell to find final tape values
def assemble(p):
lmax = depth(p)
k = 9 + lmax
layout = dict(zip(range(lmax,-1,-1)+list('aqtxbcde'),range(k)))
dif = lambda a,b: layout[b]-layout[a]
mov = lambda a,b: R(dif(a,b))
inc = lambda c: lambda l:(
mov('x',l) +
bcopy(dif(l,'a'),dif(l,'q')) +
mov('q','a') +
'{>}>' +
c +
'<{<}' +
mov('a','t') +
w0 +
mov('t','x')
)
bra = lambda l: (
mov('x',l) +
w0 +
mov(l,'b') +
'{' +
'>>>>{<}<<<'
)
qet = lambda l: (
mov('x',l-1) +
bcopy(dif(l-1,'a'),dif(l-1,l)) +
bcopy(dif(l,'a'),dif(l,'c')) +
mov('c','d') +
'{<}<' +
'}' +
'>>>>{<}<<<'
)
move = lambda d: lambda l: (
mov('x',0) +
''.join(bcopy(dif(i,'a'),d*k) + L(d*k+1) for i in range(l+1)) +
R(d*k + dif(l,'e') + 1) +
w1 +
mov('e','q') +
w0 +
R(-d*k + dif('q',l)) +
bcopy(dif(l,'a'),dif(l,'q')) +
L(d*k) +
'{' +
R(d*k) +
'}' +
mov('q','x')
)
inst = { '+': inc('+'),
'-': inc('-'),
'<': move(-1),
'>': move(1),
'[': bra,
']': qet
}
pad = 2*k
out = (
R(pad) +
mov(lmax,0) +
w1 +
mov(0,'e') +
w1 +
mov('e','x')
)
l = 0
for c in p:
l += c=='['
out += inst.get(c,lambda _:'')(l)
l -= c==']'
return 4+pad+lmax, k, out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment