-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·284 lines (257 loc) · 8.18 KB
/
main.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
#!/bin/env python3
import math, tty, sys, time
from copy import deepcopy
from decimal import Decimal
from shutil import get_terminal_size
import re
class InputError(Exception):
"""Exception raised for errors in the input.
Attributes:
message -- explanation of the error
"""
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
def _cclen(string):
"""Return printable length of string.
Attributes:
string -- string to be measured
"""
sequence = re.compile(r"\x1b\[([0-9]|[:;<=>?])*[ !\"#$%&'()*+,\-./]*([A–Z]|[a-z]|[\\\]^_`{|}~])", re.IGNORECASE)
string = sequence.sub('', string)
count = 0
escaped = False
for char in string:
if char == '\x1b': # escape
escaped = True
elif escaped:
escaped = False
elif not escaped:
count += 1
return count
operators = {
'+': lambda x : x[-2] + x[-1],
'-': lambda x : x[-2] - x[-1],
'/': lambda x : x[-2] / x[-1],
'*': lambda x : x[-2] * x[-1],
'**': lambda x : x[-2] ** x[-1],
'^': lambda x : x[-2] ** x[-1],
'mod': lambda x : math.fmod(x[-2], x[-1]),
'%': lambda x : math.fmod(x[-2], x[-1]),
'log': lambda x : math.log(x[-2], x[-1]),
}
singleops = {
'ceil': lambda x : math.ceil(x[-1]),
'abs': lambda x : abs(x[-1]),
'factorial': lambda x : math.factorial(x[-1]),
'!': lambda x : math.factorial(x[-1]),
'floor': lambda x : math.floor(x[-1]),
'exp': lambda x : math.exp(x[-1]), # e^x
'sqrt': lambda x : math.sqrt(x[-1]),
'acos': lambda x : math.acos(x[-1]),
'asin': lambda x : math.asin(x[-1]),
'atan': lambda x : math.atan(x[-1]),
'cos': lambda x : math.cos(x[-1]),
'sin': lambda x : math.sin(x[-1]),
'tan': lambda x : math.tan(x[-1]),
'ln': lambda x : math.log(x[-1]),
'round': lambda x : round(x[-1]),
}
consts = {
__doc__: '''π τ e''',
'pi': math.pi,
'tau': math.tau,
'e': math.e,
}
printconsts = {
math.pi: f'\u001b[35;1mπ\x1b[0m ({str(math.pi)[:6] + "…"})',
math.tau: f'\u001b[35;1mτ\x1b[0m ({str(math.tau)[:6] + "…"})',
math.e: f'\u001b[35;1me\x1b[0m ({str(math.e)[:6] + "…"})',
}
flags = {
'help': False,
}
helps = [
"┢ x y operator (1 2 + -> 3)",
f"┡ {' '.join(operators.keys())}",
"┢ x operator (16 sqrt -> 4)",
f"┡ {' '.join(singleops.keys())}",
"┝ constants `pi` `tau` `e`"
]
def _mark (inp = ''):
temp = inp.split()
for i, t in enumerate(temp):
if t in operators:
temp[i] = '\x1b[34m' + t + '\x1b[0m'
if t in singleops:
temp[i] = '\x1b[36m' + t + '\x1b[0m'
if t in consts:
temp[i] = '\u001b[35;1m' + t + '\x1b[0m'
return ' '.join(temp)
def _pr (stack = [], inp = '', index = 0, warning = ''):
st = deepcopy(stack[-4:])
for i, t in enumerate(st):
if t in printconsts:
st[i] = printconsts[t]
elif isinstance(t, Decimal):
st[i] = 'D: ' + str(t)
if len(st) < 4:
st = [''] * (4 - len(st)) + st
if warning:
st[-4] = '\x1b[31m' + str(warning) + '\x1b[0m'
shift = max(8, _cclen(str(st[0])), _cclen(str(st[1])), _cclen(str(st[2])), _cclen(str(st[3])), _cclen(inp))
sys.stdout.write(u"\u001b[1000D") # Move all the way left
sys.stdout.write('\u001b[4A') # Move 4 lines up
width = get_terminal_size().columns
for i in range(4):
sys.stdout.write(u"\u001b[0K") # Clear the line
if flags['help']:
line = ' ' + str(st[i]) + ' ' * (shift - _cclen(str(st[i]))) + helps[i]
if _cclen(line) > width:
line = line[:width-1] + '\x1b[0m…'
line += '\n'
sys.stdout.write(line)
else:
line = ' ' + str(st[i])
if _cclen(line) > width:
line = line[:width-1] + '\x1b[0m…'
line += '\n'
sys.stdout.write(line)
sys.stdout.write(u"\u001b[1000D") # Move all the way left again
sys.stdout.write(u"\u001b[0K") # Clear the line
if flags['help']:
line = '> ' + _mark(inp = inp) + ' ' * (shift - _cclen(_mark(inp = inp))) + helps[4]
if _cclen(line) > width:
if index + 2 > width:
line = '…' + line[index+4-width:index+2] + '\x1b[0m…'
else:
line = line[:width-1] + '\x1b[0m…'
sys.stdout.write(line)
else:
line = '> ' + _mark(inp = inp)
if _cclen(line) > width:
if index + 2 > width:
line = '…' + line[index+4-width:index+2] + '\x1b[0m…'
else:
line = line[:width-1] + '\x1b[0m…'
sys.stdout.write(line)
sys.stdout.write(u"\u001b[1000D") # Move all the way left again
sys.stdout.write(u"\u001b[" + str(index + 2) + "C") # Move cursor to index
sys.stdout.flush()
def main():
tty.setraw(sys.stdin)
sys.stdout.write('\n\n\n\n> ') # initial prompt
stack = []
history = []
histindex = 0
inp = ''
index = 0
warning = ''
while True: # loop for each line
# Define data-model for an input-string with a cursor
inp = ''
index = 0
histindex = 0
warning = ''
while True: # loop for each character
char = ord(sys.stdin.read(1)) # read one char and get char code
if char == 3: # CTRL-C
inp = ""
index = 0
if char == 4: # CTRL-D / EOF
exit()
elif 32 <= char <= 126: # Printablee
inp = inp[:index] + chr(char).lower() + inp[index:]
index += 1
elif char in {10, 13}: # Enter
try:
stack, history = parse(stack = stack, inputs = inp, history = history)
except InputError as w:
warning = w
except Exception as e:
warning = e
inp = ""
index = 0
_pr(stack = stack, inp = inp, index = index, warning = warning)
break
elif char == 27: # ESC
next1, next2 = ord(sys.stdin.read(1)), ord(sys.stdin.read(1))
if next1 == 91:
if next2 == 65: # Up
if len(history) >= histindex:
histindex = min(len(history), histindex + 1)
if histindex != 0:
inp = str(history[-histindex])
if len(history) == 1:
inp = str(history[0])
index = len(inp)
elif next2 == 66: # Down
if len(history) >= histindex:
histindex = max(0, histindex - 1)
if histindex == 0:
inp = ''
else:
inp = str(history[-histindex])
index = len(inp)
elif len(history) == 0:
inp = str(history[0])
index = len(inp)
elif next2 == 67: # Right
index = min(len(inp), index + 1)
elif next2 == 68: # Left
index = max(0, index - 1)
elif char == 127: # DEL
inp = inp[:index-1] + inp[index:]
index = max(0, index - 1)
# Print current inp-string
_pr(stack = stack, inp = inp, index = index, warning = warning)
def _calculate (stack = [], inp = ''):
temp = []
if inp == '':
return stack
elif len(stack) < 2 and (inp in operators):
raise InputError(inp + ': not enough values in stack')
elif len(stack) < 1 and (inp in singleops):
raise InputError(inp + ': not enough values in stack')
elif inp in singleops:
temp = stack[:-1] + [singleops[inp](stack)]
elif inp in consts:
temp = stack[:] + [consts[inp]]
elif inp in operators:
temp = stack[:-2] + [operators[inp](stack)]
else:
raise InputError(inp + ': operator or flag unknown')
if isinstance(temp[-1], complex):
raise InputError('i: Complex numbers not supported')
return temp
def _parse (stack = [], inp = '', history = []):
if inp == 'exit':
exit()
history.append(inp)
try:
#temp = Decimal(inp)
temp = float(inp)
if temp.is_integer():
temp = int(inp)
if math.isinf(temp):
raise InputError('∞: Value too big/small for python')
stack.append(temp)
except ValueError:
if inp in flags:
flags[inp] = not flags[inp]
elif inp in ['del', 'delete']:
stack = stack[:-1]
elif inp == 'clear':
stack = []
else:
stack = _calculate(stack = stack, inp = inp)
if stack:
history.append(stack[-1])
return stack, history
def parse (stack = [], inputs = '', history = []):
for inp in inputs.split():
stack,history = _parse(stack = stack, inp = inp, history = history)
return stack, history
if __name__ == '__main__':
main()