Created
April 12, 2015 13:16
-
-
Save xavieryao/18cfce963d9e26dd1d14 to your computer and use it in GitHub Desktop.
Brainfuck DSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
code = '' | |
pos = 0 | |
offset = 10 | |
reg = (n)-> | |
offset + n | |
moveTo = (dest)-> | |
diff = dest-pos | |
if diff > 0 | |
code += '>' for [0...diff] | |
else if diff < 0 | |
code += '<' for [0...-diff] | |
pos = dest | |
addn = (a)-> | |
code += '+' for [1..a] | |
subn = (a)-> | |
code += '-' for [1..a] | |
startLoop =-> | |
code += '[' | |
endLoop =-> | |
code += ']' | |
print =-> | |
code += '.' | |
cleanUp = (a)-> | |
moveTo a | |
startLoop() | |
subn 1 | |
endLoop() | |
mov = (from,to)-> | |
moveTo from | |
startLoop() | |
moveTo to | |
addn 1 | |
moveTo from | |
subn 1 | |
endLoop() | |
# reg 0 | |
cp = (from,to)-> | |
moveTo from | |
startLoop() | |
moveTo to | |
addn 1 | |
moveTo reg 0 | |
addn 1 | |
moveTo from | |
subn 1 | |
endLoop() | |
mov (reg 0),from | |
cleanUp reg 0 | |
loopn = (n,regn,func)-> | |
cp n,reg regn | |
moveTo reg regn | |
startLoop() | |
func() | |
moveTo reg regn | |
subn 1 | |
endLoop() | |
cleanUp reg regn | |
add = (a,b,dest)-> | |
cp a,dest | |
cp b,dest | |
# reg 1 | |
sub = (a,b,dest)-> | |
cp a,dest | |
loopn b,1,-> | |
moveTo dest | |
subn 1 | |
mul = (a,b,dest)-> | |
loopn a,1,-> | |
cp b,dest | |
div = (a,b,dest)-> | |
cp a,reg 2 | |
moveTo reg 2 | |
startLoop() | |
sub (reg 2),b,reg 3 | |
cleanUp reg 2 | |
mov (reg 3),reg 2 | |
moveTo dest | |
addn 1 | |
moveTo reg 2 | |
endLoop() | |
FxxkMath = {} | |
FxxkMath.power = (a,n,dest)-> | |
moveTo dest | |
addn 1 | |
loopn n,1,-> | |
mul a,dest,reg 2 | |
cleanUp dest | |
mov (reg 2),dest | |
# Program itself | |
addn 2 | |
moveTo 1 | |
addn 5 | |
FxxkMath.power 0,1,2 | |
moveTo 2 | |
print() | |
console.log code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment