-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCW - BF - visualizer.py
287 lines (194 loc) · 8.92 KB
/
CW - BF - visualizer.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 23 21:59:51 2017
BrainFuck tape, pointer & output vizualizer
@author: Blind4Basics - for CodeWars
-----------------------------------------------------------------
Debugging commands usable in the BF code itself:
'?' char in the code to choose the debugging points.
You can name the check points with r'\w+' characters after the ?:
"?printThere"
'!' char to switch on/off the full debugging mode, meaning, print at the
execution of each segment (see the interpreter notes below)
Other global switches available:
ALL: vizualisation at each step of the code (each segment)
DEACTIVATE: force the deactivation of the vizualisation whatever is found in the code or the other switches are
CHAR_MODE: if True, the tape will display ascii chars instead of numbers (Note: unprintable chars won't show up...)
LIMITER: interrupt the executions after this number of printing
-----------------------------------------------------------------
About the BF interpreter used:
"Segments":
The instructions are executed by "segments" of identical consecutive
command characters other than control flow ones (meaning, only "+-<>"):
'[->+<]' -> 6 segments
'>>>>><<<' -> 2 segments
'>> >> >' -> 3 segments
Configuation data:
ADD_EOF: Automatically adds an EOF char at the end of the input
stream, if set to True (=default).
RAISE_IF_NO_INPUT: Raise an exception of ',' is used while the input
stream has already been consumed entirely.
(default: False -> return \0 instead)
LOW_TAPE_IDX: Raises an exception if the pointer goes below this value
(default: 0)
HIGH_TAPE_IDX: Raises an exception if the pointer goes above this value
(default: infinity)
"""
import re
def brainFuckInterpreter(code, prog):
def updateVizu(cmdSegment=''):
nonlocal countDisplay, lastP
if DEACTIVATE: return
def formatLst(lst, charMod=False):
formStr = "{: >" + str(max(map(len, map(str, data)), default=1)) + "}"
return "[{}]".format(', '.join(formStr.format(chr(v) if charMod else v) for v in lst))
def formatPointerLst(s):
return s.translate(str.maketrans(',[]01',' *'))
countDisplay += 1 # Update the number of display already done (cf. LIMITER)
vizu[-1][lastP] = 0 # Erase the previous position of the pointer
vizu[-1][p] = 1 # Place the pointer at the current position
lastP = p # archive the current position of the pointer
out = ''.join(output)
tape,point = vizu
print( "\n\n{}tape: {}\npointer: {}\nout = '{}'".format(
cmdSegment and cmdSegment+"\n",
formatLst(tape, CHAR_MODE),
formatPointerLst(formatLst(point)),
out
))
if LIMITER >= 0 and LIMITER == countDisplay: raise Exception("Too much printing: LIMITER = {}".format(LIMITER))
def tapeLenUpdater(): # Make the tape length consistent with the actual position of the pointer (even if no value yet in the cells)
if p < LOW_TAPE_IDX or p> HIGH_TAPE_IDX:
raise Exception("out of tape: "+str(p))
if p >= len(data):
data.extend( [0] * (p-len(data)+1) )
vizu[-1].extend( [0] * (len(data)-len(vizu[-1])) )
def getNextInput(): # Simulate getting u'0000' when trying to get an input char after their exhaustion
try:
return ord(next(prog))
except StopIteration:
if RAISE_IF_NO_INPUT: raise Exception("Input stream empty...")
return 0
p, lastP, i = 0, 0, 0 # p = pointer / lastP = previous P position (mutated) / i = segment of code index
data = [0] # Tape initialization
SWITCH, countDisplay = False, 0 # SWITCH: control for the "!" cmd swtich / countDisplay = control for LIMITER (as list to mutate it from a subroutine)
output, vizu = [], [data, [0]] # vizu: [cmd, tape, pointer list]
prog = iter(prog)
code = re.findall(r'\++|<+|>+|-+|[,.[\]]|\?\w*|!', code) # Make the executions more compact by using only segments of identical commands (=> '++++', '<<<', '[', '-', ']', check points with identifiers...)
while 0 <= i < len(code):
if p < 0: print(p)
c = code[i]
if False: print(c, data, p) # activate manually. Only for debugging of the vizualiser itself...
if c[0] == '+': data[p] = (data[p] + len(c)) % 256
elif c[0] == '-': data[p] = (data[p] - len(c)) % 256
elif c[0] == '>': p += len(c) ; tapeLenUpdater()
elif c[0] == '<': p -= len(c) ; tapeLenUpdater()
elif c[0] == '.': output.append(chr(data[p]))
elif c[0] == ',': data[p] = getNextInput()
elif c[0] == '[':
if not data[p]:
depth = 1
while depth > 0:
i += 1
c = code[i]
if c == '[': depth += 1
elif c== ']': depth -= 1
elif c == ']':
if data[p]:
depth = 1
while depth > 0:
i -= 1
c = code[i]
if c == ']': depth += 1
elif c == '[': depth -= 1
# Vizualisation commands/executions
#--------------------
if c[0] == '!': SWITCH = not SWITCH
if c[0] == '?' or ALL or SWITCH: updateVizu(c)
#--------------------
i += 1
return ''.join(output)
def runTests(inputs, exp, code):
print('\n----------------------------------\nProgram:\n\n{}\n\n----------------------------------\n\n'.format(code))
EOF = chr(0)*ADD_EOF
for p,e in zip(inputs,exp):
print("Input: ", p)
act = brainFuckInterpreter(code, p+EOF)
print("Input: ", p) # reminder of the input
print(repr(act), " should be ", repr(e)) # print actual/expected before assertion
assert act == e
print("SUCCESS\n---\n")
#-----------------------------------------------------------
code = """
[Your BF code here]
>>,. ?WhatIs_Here
[->>+>+<<<]
?TapeNow
>>.
?WithOut
"""
#-----------------------------------------------------------
""" GLOBAL SWITCHES """
ALL = False
DEACTIVATE = False
CHAR_MODE = False
LIMITER = 80
LOW_TAPE_IDX = 0
HIGH_TAPE_IDX = float('inf')
ADD_EOF = True
RAISE_IF_NO_INPUT = False
#------------------------------------------------------------
# Tests:
#
# 'inputs' and corresponding 'expected' values
# EOF char automatically added at the end of each input
#------------------------------------------------------------
inputs = ("aba", 'x')
exps = ['aa', 'xx']
runTests(inputs, exps, code)
"""
Example of informations printed to stdout:
----------------------------------
Programme:
[Your BF code here]
>>,. ?WhatIs_Here
[->>+>+<<<]
?TapeNow
>>.
?WithOut
----------------------------------
Input: a
?WhatIs_Here
tape: [ 0, 0, 97]
pointer: *
out = 'a'
?TapeNow
tape: [ 0, 0, 0, 0, 97, 97]
pointer: *
out = 'a'
?WithOut
tape: [ 0, 0, 0, 0, 97, 97]
pointer: *
out = 'aa'
Input: a
'aa' should be 'aa'
SUCCESS
---
Input: x
?WhatIs_Here
tape: [ 0, 0, 120]
pointer: *
out = 'x'
?TapeNow
tape: [ 0, 0, 0, 0, 120, 120]
pointer: *
out = 'x'
?WithOut
tape: [ 0, 0, 0, 0, 120, 120]
pointer: *
out = 'xx'
Input: x
'xx' should be 'xx'
SUCCESS
---
"""