-
Notifications
You must be signed in to change notification settings - Fork 27
/
compiler_01_separado.py
84 lines (58 loc) · 1.99 KB
/
compiler_01_separado.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
from collections import defaultdict
class Parser:
_valid_tokens = list('+-><[].')
def parse(self, source):
def is_valid(token):
return token in self._valid_tokens
return list(filter(is_valid, source))
class EventEmitter:
def __init__(self):
self._listeners = defaultdict(lambda: [])
def on(self, event, listener):
self._listeners[event].append(listener)
def emit(self, event, *args, **kwargs):
for listener in self._listeners[event]:
listener(*args, **kwargs)
class Compiler(EventEmitter):
_translations_map = {
'+': 'AddOne',
'-': 'SubOne',
'>': 'Next',
'<': 'Previous',
'[': 'StartLoop',
']': 'EndLoop',
'.': 'Output'
}
def compile(self, source):
self._notify_start()
instructions = Parser().parse(source)
total = len(instructions)
translation = []
for index, line in enumerate(instructions):
self._notify_progress(index/total)
translation.append(self._translations_map[line])
self._notify_end()
return '\n'.join(translation)
def _notify_start(self):
self.emit('compilation-started')
def _notify_end(self):
self.emit('compilation-finished')
def _notify_progress(self, progress):
self.emit('compilation-progress', progress)
class ProgressDisplay:
def connect(self, compiler):
def _print_start():
print('Compilation started')
def _print_end():
print('Compilation end')
def _print_progress(progress):
print(f'{progress:.2%}')
compiler.on('compilation-started', _print_start)
compiler.on('compilation-finished', _print_end)
compiler.on('compilation-progress', _print_progress)
if __name__ == '__main__':
program = '+++>++[-<+>].'
compiler = Compiler()
progress = ProgressDisplay()
progress.connect(compiler)
print(compiler.compile(program))