-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPyGrok.py
651 lines (557 loc) · 21 KB
/
PyGrok.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
#!/usr/bin/python
"""
Modified from official ><> interpreter found at https://gist.github.com/anonymous/6392418
Python interpreter for the esoteric language Grok.
Usage: ./Grok.py --help
More information: http://esolangs.org/wiki/Grok
Requires python 3 or higher.
"""
import sys
import time
import random
from collections import defaultdict
# constants
NCHARS = "0123456789"
ARITHMETIC = "+-*%" # not division, as it requires special handling
COMPARISON = { "=": "==", ">": ">" }
DIRECTIONS = { "l": (1,0), "h": (-1,0), "j": (0,1), "k": (0,-1) }
class _Getch:
"""
Provide cross-platform getch functionality. Shamelessly stolen from
http://code.activestate.com/recipes/134892/
"""
def __init__(self):
try:
self._impl = _GetchWindows()
except ImportError:
self._impl = _GetchUnix()
def __call__(self): return self._impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
def read_string():
#Read one character from stdin. Returns 0 when no input is available.
if online:
# we're online, take input from the input box
try:
string = inputs.pop(0)
except:
string = "0"
return string
elif sys.stdin.isatty():
# we're in console, read a character from the user
char = " "
string = ""
sys.stdout.write("> ")
sys.stdout.flush()
while (True): # while character isn't carriage return or line feed
char = getch()
if ord(char) == 3: # check for ctrl-c (break)
sys.stdout.write("^C")
sys.stdout.flush()
raise KeyboardInterrupt
elif ord(char) in {10, 13}: # check for \n and/or \r
break
elif ord(char) in {8, 127}: # check for BS or DEL
if string:
string = string[:-1]
char = ""
string += str(char)
sys.stdout.write("\033[2K\r> " + string)
sys.stdout.flush()
sys.stdout.write("\n")
if not string:
string = "0"
return string
else:
# input is redirected using pipes
string = input()
# return 0 if there is no more input available
return string if string != "" else 0
class Interpreter:
"""
Grok interpreter.
"""
def __init__(self, code):
"""
Initialize a new interpreter.
Arguments:
code -- the code to execute as a string
"""
# check for hashbang in first line
lines = code.split("\n")
if lines[0][:2] == "#!":
code = "\n".join(lines[1:])
# construct a 2D defaultdict to contain the code
self._wordbox = defaultdict(lambda: defaultdict(int))
line_n = char_n = 0
for char in code:
if char != "\n":
self._wordbox[line_n][char_n] = 0 if char == " " else ord(char)
char_n += 1
else:
char_n = 0
line_n += 1
self._position = [-1,0]
self._direction = DIRECTIONS["l"]
# are we in debug mode? (real error messages displayed)
self._debug = False
# are we using integer division?
self._int_div = False
# the register is initially empty
self._register = 0
# string mode is initially disabled
self._string_mode = None
self._num_entered = False
# have we encountered a skip instruction?
self._skip = False
self._insert_string = ""
self._stack = []
# is the last outputted character a newline?
self._newline = None
def move(self):
"""
Move one step in the execution process, and handle the instruction (if
any) at the new position.
"""
# move one step in the current direction
self._position[0] += self._direction[0]
self._position[1] += self._direction[1]
# wrap around if we reach the borders of the wordbox
if self._position[1] > max(self._wordbox.keys()):
# if the current position is beyond the number of lines, wrap to the top
self._position[1] = 0
elif self._position[1] < 0:
# if we're above the top, move to the bottom
self._position[1] = max(self._wordbox.keys())
if self._direction[0] == 1 and self._position[0] > max(self._wordbox[self._position[1]].keys()):
# wrap to the beginning if we are beyond the last character on a line and moving rightwards
self._position[0] = 0;
elif self._position[0] < 0:
# also wrap if we reach the left hand side
self._position[0] = max(self._wordbox[self._position[1]].keys())
# execute the instruction found
if not self._skip:
instruction = int(self._wordbox[self._position[1]][self._position[0]])
# the current position might not be a valid character
try:
# use space if current cell is 0
instruction = chr(instruction) if instruction > 0 else " "
except:
instruction = None
if self._debug:
try:
self._handle_instruction(instruction)
except StopExecution:
raise
except KeyboardInterrupt:
# avoid catching as error
raise KeyboardInterrupt
else:
try:
self._handle_instruction(instruction)
except StopExecution:
raise
except KeyboardInterrupt:
# avoid catching as error
raise KeyboardInterrupt
except Exception as e:
raise StopExecution("You don't grok Grok.")
return instruction
self._skip = False
def _handle_instruction(self, instruction):
"""
Execute an instruction.
"""
if instruction == None:
# error on invalid characters
raise Exception
# handle insert mode
if self._string_mode == "insert" and instruction != "`":
self._insert_string += str(instruction)
return
# handle insert escape
elif self._string_mode == "insert" and instruction == "`":
is_num = True
string = self._insert_string
for char in string:
if char not in NCHARS:
is_num = False
break
if is_num:
try:
self._push(int(string))
except: # for empty string, push nothing
pass
else:
string = string[::-1]
for char in string:
self._push(ord(char))
self._insert_string = ""
self._string_mode = None
# handle regin mode
elif self._string_mode == "regin" and instruction != "`":
if instruction in NCHARS: # if the instruction is a number, push it and continue in regin
self._register = ( str(instruction) if not self._num_entered else self._register + str(instruction) )
self._num_entered = True
return
elif instruction not in NCHARS:
self._string_mode = None # if the instruction is not a number, end regin mode and execute it
if self._num_entered:
self._register = int(self._register)
self._num_entered = False
self._handle_instruction(instruction)
else:
self._register = ord(instruction) # if not a number and is first instruction in regin,
return # push it and end regin mode
# handle regin escape
elif self._string_mode == "regin" and instruction == "`":
if self._num_entered:
self._register = int(self._register)
self._num_entered = False
self._skip = True
self._string_mode = None
# handle escape
elif self._string_mode == None and instruction == "`":
self._skip = True
# instruction is one of kjlh, change direction
elif instruction in DIRECTIONS:
self._direction = DIRECTIONS[instruction]
# instruction is 0-9, push corresponding int value
elif instruction in NCHARS:
self._push(int(instruction))
# instruction is an arithmetic operator
elif instruction in ARITHMETIC:
a, b = self._pop(), self._pop()
exec("self._push(b{}a)".format(instruction))
# division
elif instruction == "/":
a, b = self._pop(), self._pop()
if self._int_div:
a, b = int(a), int(b)
self._push(b//a)
else:
# try converting them to floats for python 2 compability
try:
a, b = float(a), float(b)
except OverflowError:
pass
self._push(b/a)
# comparison operators
elif instruction in COMPARISON:
a, b = self._pop(), self._pop()
exec("self._push(1 if b{}a else 0)".format(COMPARISON[instruction]))
# logical NOT
elif instruction == "!":
a = self._pop()
self._push(0) if a else self._push(1)
# turn on string mode
elif instruction == "i": # turn on string parsing
self._string_mode = "insert"
elif instruction == "I": # turn on "regin" string parsing
self._string_mode = "regin"
# duplicate ath value on stack to the register
elif instruction == "y":
a = self._pop()
self._register = self._copy(-(1+a))
# duplicate top of stack to the register
elif instruction == "Y":
self._register = self._copy(-1)
# pop register value and push it to the stack
elif instruction == "p":
self._push(self._register)
self._register = 0
# duplicate register value to the stack
elif instruction == "P":
self._push(self._register)
# remove top of stack
elif instruction == "x":
self._pop()
# remove register value
elif instruction == "X":
self._register = 0
# remove a values from stack, or push to register if a == 0
elif instruction == "d":
a = self._pop()
if a:
for x in range(a): self._pop()
else: self._register = self._pop()
# rotate pointer right
elif instruction == "}":
d = self._direction
a = self._pop()
if not a:
if d == DIRECTIONS["l"]:
self._direction = DIRECTIONS["j"]
elif d == DIRECTIONS["j"]:
self._direction = DIRECTIONS["h"]
elif d == DIRECTIONS["h"]:
self._direction = DIRECTIONS["k"]
elif d == DIRECTIONS["k"]:
self._direction = DIRECTIONS["l"]
# rotate pointer left
elif instruction == "{":
d = self._direction
a = self._pop()
if not a:
if d == DIRECTIONS["l"]:
self._direction = DIRECTIONS["k"]
elif d == DIRECTIONS["k"]:
self._direction = DIRECTIONS["h"]
elif d == DIRECTIONS["h"]:
self._direction = DIRECTIONS["j"]
elif d == DIRECTIONS["j"]:
self._direction = DIRECTIONS["l"]
# pop and output as character
elif instruction == "w":
self._output(chr(int(self._pop())))
# pop from register and output as character
elif instruction == "W":
self._output(chr(int(self._register)))
self._register = 0
# pop and output as number
elif instruction == "z":
n = self._pop()
# try outputting without the decimal point if possible
self._output(int(n) if int(n) == n else n)
# pop from register and output as number
elif instruction == "Z":
n = self._register
self._output(int(n) if int(n) == n else n)
self._register = 0
# handle input
elif instruction == ":":
i = self._input()
is_num = True
for char in i:
if char not in NCHARS:
is_num = False
break
if is_num:
self._push(int(i))
else:
i = i[::-1]
for char in i:
self._push(ord(char))
# the end
elif instruction == "q":
raise StopExecution()
# space is NOP
elif instruction == " ":
pass
# invalid instruction
else:
raise Exception("Invalid instruction", instruction)
def _push(self, value, index=None):
"""
Push a value to the stack.
Keyword arguments:
index -- the index to push/insert to. (default: end of stack)
"""
self._stack.insert(len(self._stack) if index == None else index, value)
def _pop(self, index=None):
"""
Pop and return a value from the current stack.
Keyword arguments:
index -- the index to pop from (default: end of stack)
"""
# if there are no values to pop, return 0
try:
value = self._stack.pop(len(self._stack)-1 if index == None else index)
except IndexError:
value = 0
# convert to int where possible to avoid float overflow
if value == int(value):
value = int(value)
return value
def _copy(self, index):
"""
Copy and return a value from the stack.
Keyword arguments:
index -- the index to copy from (default: end of stack)
"""
# if there are no values to copy, return 0
try:
value = self._stack[index]
except IndexError:
value = 0
# convert to int where possible to avoid float overflow
if value == int(value):
value = int(value)
return value
def _input(self):
"""
Return an inputted character.
"""
return read_string()
def _output(self, output):
"""
Output a string without a newline appended.
"""
global online
global out
output = str(output)
if online:
out[1] += output
else:
self._newline = output.endswith("\n")
sys.stdout.write(output)
sys.stdout.flush()
class StopExecution(Exception):
"""
Exception raised when a script has finished execution.
"""
def __init__(self, message = None):
self.message = message
def execute(code, flags, input_list, output_var):
global out
global online
global inputs
out = output_var
out[1] = ""
out[2] = ""
flags = flags
online = True
inputs = input_list.split("\n")
interpreter = Interpreter(code)
if flags:
if 'd' in flags:
interpreter._int_div = True
if 'e' in flags:
interpreter._debug = True
if 'h' in flags:
out[1] = """
Flags should be used without a '-' prefix
\td\tUse integer division instead of float division
\te\tEnable more detailed error messages
\th\tOutput this help message and exit
\tf\tMake the interpreter timeout after 10 seconds
\tF\tMake the interpreter timeout after 15 seconds
\tb\tMake the interpreter timeout after 30 seconds
\tT\tMake the interpreter timeout after 60 seconds
\tB\tMake the interpreter timeout after 120 seconds
"""
return
while True:
try:
instr = interpreter.move()
except StopExecution as stop:
out[2] += stop.message
return
except Exception as e:
out[2] += f"{e}"
return
if __name__ == "__main__":
import argparse
global online
online = False
parser = argparse.ArgumentParser(description="""
Execute a Grok script.
Executing a script is as easy as:
%(prog)s <script file>
You can also execute code directly using the -c/--code flag:
%(prog)s -c '1z23zzq'
> 132
The -v and -s flags can be used to prepopulate the stack:
%(prog)s echo.grk -s "hello, world" -v 32 49 50 51 -s "456"
> hello, world 123456""", usage="""%(prog)s [-h] (<script file> | -c <code>) [<options>]""",
formatter_class=argparse.RawDescriptionHelpFormatter)
group = parser.add_argument_group("code")
# group script file and --code together to only allow one
code_group = group.add_mutually_exclusive_group(required=True)
code_group.add_argument("script",
type=argparse.FileType("r"),
nargs="?",
help=".grk file to execute")
code_group.add_argument("-c", "--code",
metavar="<code>",
help="string of instructions to execute")
setup = parser.add_argument_group("setup")
setup.add_argument("-s", "--string",
action="append",
metavar="<string>",
dest="stack")
setup.add_argument("-v", "--value",
type=float,
nargs="+",
action="append",
metavar="<number>",
dest="stack",
help="push numbers or strings onto the stack before execution starts")
options = parser.add_argument_group("options")
options.add_argument("-d", "--int-divide",
action="store_true",
default=False,
dest="int_div",
help="enable integer division instead of float division")
options.add_argument("-n", "--no-newline",
action="store_true",
default=False,
dest="no_newline",
help="disable implicit trailing newline outputted at the end of execution")
options.add_argument("-t", "--tick",
type=float,
default=0.0,
metavar="<seconds>",
help="define a tick time, or a delay between the execution of each instruction")
options.add_argument("-a", "--always-tick",
action="store_true",
default=False,
dest="always_tick",
help="make every instruction cause a tick (delay), even whitespace and skipped instructions")
options.add_argument("-e", "--show-errors",
action="store_true",
default=False,
dest="show_errors",
help="disable \"You don't grok Grok.\" error message and show true error message")
# parse arguments from sys.argv
arguments = parser.parse_args()
# initialize an interpreter
if arguments.script:
code = arguments.script.read()
arguments.script.close()
else:
code = arguments.code
interpreter = Interpreter(code)
if arguments.show_errors:
interpreter._debug = True
if arguments.int_div:
interpreter._int_div = True
# add supplied values to the interpreters stack
if arguments.stack:
for x in arguments.stack:
if isinstance(x, str):
interpreter._stack += [float(ord(c)) for c in x]
else:
interpreter._stack += x
# run the script
try:
while True:
try:
instr = interpreter.move()
except StopExecution as stop:
# only print a newline if the script didn't and it hasn't been disabled
newline = ("\n" if (not interpreter._newline) and interpreter._newline != None and (not arguments.no_newline) else "")
parser.exit(message=(newline+stop.message+"\n") if stop.message else newline)
if instr and not instr == " " or arguments.always_tick:
time.sleep(arguments.tick)
except KeyboardInterrupt:
# exit cleanly
parser.exit(message="\n")