-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compile_bash.py
106 lines (74 loc) · 3 KB
/
compile_bash.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#! /usr/bin/python
# Written by Folkert van Heusden
# Released in the public domain
import sys
from compile_base import CompileBase
class CompileToBash(CompileBase):
def header(self):
print('Brainfuck to Bash compiler.', file=sys.stderr)
def get_name():
return ('bash', None)
def genindent(self, level):
return ' ' * (level * 4)
def invokeFunction(self, funcNr):
print('%sf%d' % (self.genindent(self.lindentlevel), funcNr))
def addToDataPtr(self, n, dot, position):
ind = self.genindent(self.lindentlevel)
print('%sdata_ptr=$((data_ptr + %d))' % (ind, n))
def subFromDataPtr(self, n, dot, position):
ind = self.genindent(self.lindentlevel)
print('%sdata_ptr=$((data_ptr - %d))' % (ind, n))
def addToData(self, n, dot, position):
ind = self.genindent(self.lindentlevel)
print('%sdata_mem[$data_ptr]=$((data_mem[data_ptr] + %d))' % (ind, n))
print('%sdata_mem[$data_ptr]=$((data_mem[data_ptr] & 255))' % ind)
def subFromData(self, n, dot, position):
ind = self.genindent(self.lindentlevel)
print('%sdata_mem[$data_ptr]=$((data_mem[data_ptr] - %d))' % (ind, n))
print('%sdata_mem[$data_ptr]=$((data_mem[data_ptr] & 255))' % ind)
def emitCharacter(self, n, dot):
for i in range(0, n):
print("%sperl -e \"print chr(${data_mem[$data_ptr]});\"" % self.genindent(self.lindentlevel))
def startLoop(self, n, position):
for j in range(0, n):
print('%swhile [ ${data_mem[$data_ptr]} -gt 0 ] ; do' % self.genindent(self.lindentlevel))
self.lindentlevel += 1
def finishLoop(self, n, dot, position):
for j in range(0, n):
self.lindentlevel -= 1
print('%sdone' % self.genindent(self.lindentlevel))
def addComment(self, s):
print('# %s' % s)
def multilineCommentStart(self):
print('#')
def multilineCommentLine(self, s):
print('# %s' % s)
def multilineCommentEnd(self):
print('#')
def emitProgramBootstrap(self, file):
print('#! /bin/bash')
print('')
print(f'# This is a translation of "{file}".')
print('data_ptr=1')
print('')
print('memory_size=32768')
print('i=0')
print('while [ $i -lt $memory_size ] ; do')
self.lindentlevel += 1
print('%sdata_mem[$i]=0' % self.genindent(self.lindentlevel))
print('%si=$((i + 1))' % self.genindent(self.lindentlevel))
self.lindentlevel -= 1
print('done')
self.addComments(self.copyrightNotice)
print('')
def emitFunctions(self):
self.lindentlevel += 1
for blkLoop in range(0, len(self.blocks)):
print('function f%d {' % blkLoop)
self.translate(self.blocks[blkLoop][0], self.blocks[blkLoop][1])
print('}')
self.lindentlevel -= 1
def emitMainFunction(self):
print('')
self.translate(0, len(self.allCode))
print('exit 0')